PackageManagerService.java revision eaa1c9ae4248810ed30c52d85e348712f5621a50
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(), ephemeralPrefixMask, 5004 ephemeralPrefixCount); 5005 final int[] shaPrefix = digest.getDigestPrefix(); 5006 final byte[][] digestBytes = digest.getDigestBytes(); 5007 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5008 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5009 shaPrefix, ephemeralPrefixMask); 5010 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5011 // No hash prefix match; there are no ephemeral apps for this domain. 5012 return null; 5013 } 5014 5015 // Go in reverse order so we match the narrowest scope first. 5016 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5017 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5018 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5019 continue; 5020 } 5021 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5022 // No filters; this should never happen. 5023 if (filters.isEmpty()) { 5024 continue; 5025 } 5026 // We have a domain match; resolve the filters to see if anything matches. 5027 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5028 for (int j = filters.size() - 1; j >= 0; --j) { 5029 final EphemeralResolveIntentInfo intentInfo = 5030 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5031 ephemeralResolver.addFilter(intentInfo); 5032 } 5033 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5034 intent, resolvedType, false /*defaultOnly*/, userId); 5035 if (!matchedResolveInfoList.isEmpty()) { 5036 return matchedResolveInfoList.get(0); 5037 } 5038 } 5039 } 5040 // Hash or filter mis-match; no ephemeral apps for this domain. 5041 return null; 5042 } 5043 5044 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5045 int flags, List<ResolveInfo> query, int userId) { 5046 if (query != null) { 5047 final int N = query.size(); 5048 if (N == 1) { 5049 return query.get(0); 5050 } else if (N > 1) { 5051 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5052 // If there is more than one activity with the same priority, 5053 // then let the user decide between them. 5054 ResolveInfo r0 = query.get(0); 5055 ResolveInfo r1 = query.get(1); 5056 if (DEBUG_INTENT_MATCHING || debug) { 5057 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5058 + r1.activityInfo.name + "=" + r1.priority); 5059 } 5060 // If the first activity has a higher priority, or a different 5061 // default, then it is always desirable to pick it. 5062 if (r0.priority != r1.priority 5063 || r0.preferredOrder != r1.preferredOrder 5064 || r0.isDefault != r1.isDefault) { 5065 return query.get(0); 5066 } 5067 // If we have saved a preference for a preferred activity for 5068 // this Intent, use that. 5069 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5070 flags, query, r0.priority, true, false, debug, userId); 5071 if (ri != null) { 5072 return ri; 5073 } 5074 ri = new ResolveInfo(mResolveInfo); 5075 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5076 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5077 // If all of the options come from the same package, show the application's 5078 // label and icon instead of the generic resolver's. 5079 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5080 // and then throw away the ResolveInfo itself, meaning that the caller loses 5081 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5082 // a fallback for this case; we only set the target package's resources on 5083 // the ResolveInfo, not the ActivityInfo. 5084 final String intentPackage = intent.getPackage(); 5085 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5086 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5087 ri.resolvePackageName = intentPackage; 5088 if (userNeedsBadging(userId)) { 5089 ri.noResourceId = true; 5090 } else { 5091 ri.icon = appi.icon; 5092 } 5093 ri.iconResourceId = appi.icon; 5094 ri.labelRes = appi.labelRes; 5095 } 5096 ri.activityInfo.applicationInfo = new ApplicationInfo( 5097 ri.activityInfo.applicationInfo); 5098 if (userId != 0) { 5099 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5100 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5101 } 5102 // Make sure that the resolver is displayable in car mode 5103 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5104 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5105 return ri; 5106 } 5107 } 5108 return null; 5109 } 5110 5111 /** 5112 * Return true if the given list is not empty and all of its contents have 5113 * an activityInfo with the given package name. 5114 */ 5115 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5116 if (ArrayUtils.isEmpty(list)) { 5117 return false; 5118 } 5119 for (int i = 0, N = list.size(); i < N; i++) { 5120 final ResolveInfo ri = list.get(i); 5121 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5122 if (ai == null || !packageName.equals(ai.packageName)) { 5123 return false; 5124 } 5125 } 5126 return true; 5127 } 5128 5129 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5130 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5131 final int N = query.size(); 5132 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5133 .get(userId); 5134 // Get the list of persistent preferred activities that handle the intent 5135 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5136 List<PersistentPreferredActivity> pprefs = ppir != null 5137 ? ppir.queryIntent(intent, resolvedType, 5138 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5139 : null; 5140 if (pprefs != null && pprefs.size() > 0) { 5141 final int M = pprefs.size(); 5142 for (int i=0; i<M; i++) { 5143 final PersistentPreferredActivity ppa = pprefs.get(i); 5144 if (DEBUG_PREFERRED || debug) { 5145 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5146 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5147 + "\n component=" + ppa.mComponent); 5148 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5149 } 5150 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5151 flags | MATCH_DISABLED_COMPONENTS, userId); 5152 if (DEBUG_PREFERRED || debug) { 5153 Slog.v(TAG, "Found persistent preferred activity:"); 5154 if (ai != null) { 5155 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5156 } else { 5157 Slog.v(TAG, " null"); 5158 } 5159 } 5160 if (ai == null) { 5161 // This previously registered persistent preferred activity 5162 // component is no longer known. Ignore it and do NOT remove it. 5163 continue; 5164 } 5165 for (int j=0; j<N; j++) { 5166 final ResolveInfo ri = query.get(j); 5167 if (!ri.activityInfo.applicationInfo.packageName 5168 .equals(ai.applicationInfo.packageName)) { 5169 continue; 5170 } 5171 if (!ri.activityInfo.name.equals(ai.name)) { 5172 continue; 5173 } 5174 // Found a persistent preference that can handle the intent. 5175 if (DEBUG_PREFERRED || debug) { 5176 Slog.v(TAG, "Returning persistent preferred activity: " + 5177 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5178 } 5179 return ri; 5180 } 5181 } 5182 } 5183 return null; 5184 } 5185 5186 // TODO: handle preferred activities missing while user has amnesia 5187 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5188 List<ResolveInfo> query, int priority, boolean always, 5189 boolean removeMatches, boolean debug, int userId) { 5190 if (!sUserManager.exists(userId)) return null; 5191 flags = updateFlagsForResolve(flags, userId, intent); 5192 // writer 5193 synchronized (mPackages) { 5194 if (intent.getSelector() != null) { 5195 intent = intent.getSelector(); 5196 } 5197 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5198 5199 // Try to find a matching persistent preferred activity. 5200 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5201 debug, userId); 5202 5203 // If a persistent preferred activity matched, use it. 5204 if (pri != null) { 5205 return pri; 5206 } 5207 5208 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5209 // Get the list of preferred activities that handle the intent 5210 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5211 List<PreferredActivity> prefs = pir != null 5212 ? pir.queryIntent(intent, resolvedType, 5213 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5214 : null; 5215 if (prefs != null && prefs.size() > 0) { 5216 boolean changed = false; 5217 try { 5218 // First figure out how good the original match set is. 5219 // We will only allow preferred activities that came 5220 // from the same match quality. 5221 int match = 0; 5222 5223 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5224 5225 final int N = query.size(); 5226 for (int j=0; j<N; j++) { 5227 final ResolveInfo ri = query.get(j); 5228 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5229 + ": 0x" + Integer.toHexString(match)); 5230 if (ri.match > match) { 5231 match = ri.match; 5232 } 5233 } 5234 5235 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5236 + Integer.toHexString(match)); 5237 5238 match &= IntentFilter.MATCH_CATEGORY_MASK; 5239 final int M = prefs.size(); 5240 for (int i=0; i<M; i++) { 5241 final PreferredActivity pa = prefs.get(i); 5242 if (DEBUG_PREFERRED || debug) { 5243 Slog.v(TAG, "Checking PreferredActivity ds=" 5244 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5245 + "\n component=" + pa.mPref.mComponent); 5246 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5247 } 5248 if (pa.mPref.mMatch != match) { 5249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5250 + Integer.toHexString(pa.mPref.mMatch)); 5251 continue; 5252 } 5253 // If it's not an "always" type preferred activity and that's what we're 5254 // looking for, skip it. 5255 if (always && !pa.mPref.mAlways) { 5256 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5257 continue; 5258 } 5259 final ActivityInfo ai = getActivityInfo( 5260 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5261 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5262 userId); 5263 if (DEBUG_PREFERRED || debug) { 5264 Slog.v(TAG, "Found preferred activity:"); 5265 if (ai != null) { 5266 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5267 } else { 5268 Slog.v(TAG, " null"); 5269 } 5270 } 5271 if (ai == null) { 5272 // This previously registered preferred activity 5273 // component is no longer known. Most likely an update 5274 // to the app was installed and in the new version this 5275 // component no longer exists. Clean it up by removing 5276 // it from the preferred activities list, and skip it. 5277 Slog.w(TAG, "Removing dangling preferred activity: " 5278 + pa.mPref.mComponent); 5279 pir.removeFilter(pa); 5280 changed = true; 5281 continue; 5282 } 5283 for (int j=0; j<N; j++) { 5284 final ResolveInfo ri = query.get(j); 5285 if (!ri.activityInfo.applicationInfo.packageName 5286 .equals(ai.applicationInfo.packageName)) { 5287 continue; 5288 } 5289 if (!ri.activityInfo.name.equals(ai.name)) { 5290 continue; 5291 } 5292 5293 if (removeMatches) { 5294 pir.removeFilter(pa); 5295 changed = true; 5296 if (DEBUG_PREFERRED) { 5297 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5298 } 5299 break; 5300 } 5301 5302 // Okay we found a previously set preferred or last chosen app. 5303 // If the result set is different from when this 5304 // was created, we need to clear it and re-ask the 5305 // user their preference, if we're looking for an "always" type entry. 5306 if (always && !pa.mPref.sameSet(query)) { 5307 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5308 + intent + " type " + resolvedType); 5309 if (DEBUG_PREFERRED) { 5310 Slog.v(TAG, "Removing preferred activity since set changed " 5311 + pa.mPref.mComponent); 5312 } 5313 pir.removeFilter(pa); 5314 // Re-add the filter as a "last chosen" entry (!always) 5315 PreferredActivity lastChosen = new PreferredActivity( 5316 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5317 pir.addFilter(lastChosen); 5318 changed = true; 5319 return null; 5320 } 5321 5322 // Yay! Either the set matched or we're looking for the last chosen 5323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5324 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5325 return ri; 5326 } 5327 } 5328 } finally { 5329 if (changed) { 5330 if (DEBUG_PREFERRED) { 5331 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5332 } 5333 scheduleWritePackageRestrictionsLocked(userId); 5334 } 5335 } 5336 } 5337 } 5338 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5339 return null; 5340 } 5341 5342 /* 5343 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5344 */ 5345 @Override 5346 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5347 int targetUserId) { 5348 mContext.enforceCallingOrSelfPermission( 5349 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5350 List<CrossProfileIntentFilter> matches = 5351 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5352 if (matches != null) { 5353 int size = matches.size(); 5354 for (int i = 0; i < size; i++) { 5355 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5356 } 5357 } 5358 if (hasWebURI(intent)) { 5359 // cross-profile app linking works only towards the parent. 5360 final UserInfo parent = getProfileParent(sourceUserId); 5361 synchronized(mPackages) { 5362 int flags = updateFlagsForResolve(0, parent.id, intent); 5363 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5364 intent, resolvedType, flags, sourceUserId, parent.id); 5365 return xpDomainInfo != null; 5366 } 5367 } 5368 return false; 5369 } 5370 5371 private UserInfo getProfileParent(int userId) { 5372 final long identity = Binder.clearCallingIdentity(); 5373 try { 5374 return sUserManager.getProfileParent(userId); 5375 } finally { 5376 Binder.restoreCallingIdentity(identity); 5377 } 5378 } 5379 5380 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5381 String resolvedType, int userId) { 5382 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5383 if (resolver != null) { 5384 return resolver.queryIntent(intent, resolvedType, false, userId); 5385 } 5386 return null; 5387 } 5388 5389 @Override 5390 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5391 String resolvedType, int flags, int userId) { 5392 try { 5393 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5394 5395 return new ParceledListSlice<>( 5396 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5397 } finally { 5398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5399 } 5400 } 5401 5402 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5403 String resolvedType, int flags, int userId) { 5404 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5405 flags = updateFlagsForResolve(flags, userId, intent); 5406 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5407 false /* requireFullPermission */, false /* checkShell */, 5408 "query intent activities"); 5409 ComponentName comp = intent.getComponent(); 5410 if (comp == null) { 5411 if (intent.getSelector() != null) { 5412 intent = intent.getSelector(); 5413 comp = intent.getComponent(); 5414 } 5415 } 5416 5417 if (comp != null) { 5418 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5419 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5420 if (ai != null) { 5421 final ResolveInfo ri = new ResolveInfo(); 5422 ri.activityInfo = ai; 5423 list.add(ri); 5424 } 5425 return list; 5426 } 5427 5428 // reader 5429 synchronized (mPackages) { 5430 final String pkgName = intent.getPackage(); 5431 if (pkgName == null) { 5432 List<CrossProfileIntentFilter> matchingFilters = 5433 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5434 // Check for results that need to skip the current profile. 5435 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5436 resolvedType, flags, userId); 5437 if (xpResolveInfo != null) { 5438 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5439 result.add(xpResolveInfo); 5440 return filterIfNotSystemUser(result, userId); 5441 } 5442 5443 // Check for results in the current profile. 5444 List<ResolveInfo> result = mActivities.queryIntent( 5445 intent, resolvedType, flags, userId); 5446 result = filterIfNotSystemUser(result, userId); 5447 5448 // Check for cross profile results. 5449 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5450 xpResolveInfo = queryCrossProfileIntents( 5451 matchingFilters, intent, resolvedType, flags, userId, 5452 hasNonNegativePriorityResult); 5453 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5454 boolean isVisibleToUser = filterIfNotSystemUser( 5455 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5456 if (isVisibleToUser) { 5457 result.add(xpResolveInfo); 5458 Collections.sort(result, mResolvePrioritySorter); 5459 } 5460 } 5461 if (hasWebURI(intent)) { 5462 CrossProfileDomainInfo xpDomainInfo = null; 5463 final UserInfo parent = getProfileParent(userId); 5464 if (parent != null) { 5465 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5466 flags, userId, parent.id); 5467 } 5468 if (xpDomainInfo != null) { 5469 if (xpResolveInfo != null) { 5470 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5471 // in the result. 5472 result.remove(xpResolveInfo); 5473 } 5474 if (result.size() == 0) { 5475 result.add(xpDomainInfo.resolveInfo); 5476 return result; 5477 } 5478 } else if (result.size() <= 1) { 5479 return result; 5480 } 5481 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5482 xpDomainInfo, userId); 5483 Collections.sort(result, mResolvePrioritySorter); 5484 } 5485 return result; 5486 } 5487 final PackageParser.Package pkg = mPackages.get(pkgName); 5488 if (pkg != null) { 5489 return filterIfNotSystemUser( 5490 mActivities.queryIntentForPackage( 5491 intent, resolvedType, flags, pkg.activities, userId), 5492 userId); 5493 } 5494 return new ArrayList<ResolveInfo>(); 5495 } 5496 } 5497 5498 private static class CrossProfileDomainInfo { 5499 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5500 ResolveInfo resolveInfo; 5501 /* Best domain verification status of the activities found in the other profile */ 5502 int bestDomainVerificationStatus; 5503 } 5504 5505 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5506 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5507 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5508 sourceUserId)) { 5509 return null; 5510 } 5511 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5512 resolvedType, flags, parentUserId); 5513 5514 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5515 return null; 5516 } 5517 CrossProfileDomainInfo result = null; 5518 int size = resultTargetUser.size(); 5519 for (int i = 0; i < size; i++) { 5520 ResolveInfo riTargetUser = resultTargetUser.get(i); 5521 // Intent filter verification is only for filters that specify a host. So don't return 5522 // those that handle all web uris. 5523 if (riTargetUser.handleAllWebDataURI) { 5524 continue; 5525 } 5526 String packageName = riTargetUser.activityInfo.packageName; 5527 PackageSetting ps = mSettings.mPackages.get(packageName); 5528 if (ps == null) { 5529 continue; 5530 } 5531 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5532 int status = (int)(verificationState >> 32); 5533 if (result == null) { 5534 result = new CrossProfileDomainInfo(); 5535 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5536 sourceUserId, parentUserId); 5537 result.bestDomainVerificationStatus = status; 5538 } else { 5539 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5540 result.bestDomainVerificationStatus); 5541 } 5542 } 5543 // Don't consider matches with status NEVER across profiles. 5544 if (result != null && result.bestDomainVerificationStatus 5545 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5546 return null; 5547 } 5548 return result; 5549 } 5550 5551 /** 5552 * Verification statuses are ordered from the worse to the best, except for 5553 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5554 */ 5555 private int bestDomainVerificationStatus(int status1, int status2) { 5556 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5557 return status2; 5558 } 5559 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5560 return status1; 5561 } 5562 return (int) MathUtils.max(status1, status2); 5563 } 5564 5565 private boolean isUserEnabled(int userId) { 5566 long callingId = Binder.clearCallingIdentity(); 5567 try { 5568 UserInfo userInfo = sUserManager.getUserInfo(userId); 5569 return userInfo != null && userInfo.isEnabled(); 5570 } finally { 5571 Binder.restoreCallingIdentity(callingId); 5572 } 5573 } 5574 5575 /** 5576 * Filter out activities with systemUserOnly flag set, when current user is not System. 5577 * 5578 * @return filtered list 5579 */ 5580 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5581 if (userId == UserHandle.USER_SYSTEM) { 5582 return resolveInfos; 5583 } 5584 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5585 ResolveInfo info = resolveInfos.get(i); 5586 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5587 resolveInfos.remove(i); 5588 } 5589 } 5590 return resolveInfos; 5591 } 5592 5593 /** 5594 * @param resolveInfos list of resolve infos in descending priority order 5595 * @return if the list contains a resolve info with non-negative priority 5596 */ 5597 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5598 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5599 } 5600 5601 private static boolean hasWebURI(Intent intent) { 5602 if (intent.getData() == null) { 5603 return false; 5604 } 5605 final String scheme = intent.getScheme(); 5606 if (TextUtils.isEmpty(scheme)) { 5607 return false; 5608 } 5609 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5610 } 5611 5612 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5613 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5614 int userId) { 5615 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5616 5617 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5618 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5619 candidates.size()); 5620 } 5621 5622 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5623 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5624 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5625 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5626 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5627 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5628 5629 synchronized (mPackages) { 5630 final int count = candidates.size(); 5631 // First, try to use linked apps. Partition the candidates into four lists: 5632 // one for the final results, one for the "do not use ever", one for "undefined status" 5633 // and finally one for "browser app type". 5634 for (int n=0; n<count; n++) { 5635 ResolveInfo info = candidates.get(n); 5636 String packageName = info.activityInfo.packageName; 5637 PackageSetting ps = mSettings.mPackages.get(packageName); 5638 if (ps != null) { 5639 // Add to the special match all list (Browser use case) 5640 if (info.handleAllWebDataURI) { 5641 matchAllList.add(info); 5642 continue; 5643 } 5644 // Try to get the status from User settings first 5645 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5646 int status = (int)(packedStatus >> 32); 5647 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5648 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5649 if (DEBUG_DOMAIN_VERIFICATION) { 5650 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5651 + " : linkgen=" + linkGeneration); 5652 } 5653 // Use link-enabled generation as preferredOrder, i.e. 5654 // prefer newly-enabled over earlier-enabled. 5655 info.preferredOrder = linkGeneration; 5656 alwaysList.add(info); 5657 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5658 if (DEBUG_DOMAIN_VERIFICATION) { 5659 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5660 } 5661 neverList.add(info); 5662 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5663 if (DEBUG_DOMAIN_VERIFICATION) { 5664 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5665 } 5666 alwaysAskList.add(info); 5667 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5668 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5669 if (DEBUG_DOMAIN_VERIFICATION) { 5670 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5671 } 5672 undefinedList.add(info); 5673 } 5674 } 5675 } 5676 5677 // We'll want to include browser possibilities in a few cases 5678 boolean includeBrowser = false; 5679 5680 // First try to add the "always" resolution(s) for the current user, if any 5681 if (alwaysList.size() > 0) { 5682 result.addAll(alwaysList); 5683 } else { 5684 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5685 result.addAll(undefinedList); 5686 // Maybe add one for the other profile. 5687 if (xpDomainInfo != null && ( 5688 xpDomainInfo.bestDomainVerificationStatus 5689 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5690 result.add(xpDomainInfo.resolveInfo); 5691 } 5692 includeBrowser = true; 5693 } 5694 5695 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5696 // If there were 'always' entries their preferred order has been set, so we also 5697 // back that off to make the alternatives equivalent 5698 if (alwaysAskList.size() > 0) { 5699 for (ResolveInfo i : result) { 5700 i.preferredOrder = 0; 5701 } 5702 result.addAll(alwaysAskList); 5703 includeBrowser = true; 5704 } 5705 5706 if (includeBrowser) { 5707 // Also add browsers (all of them or only the default one) 5708 if (DEBUG_DOMAIN_VERIFICATION) { 5709 Slog.v(TAG, " ...including browsers in candidate set"); 5710 } 5711 if ((matchFlags & MATCH_ALL) != 0) { 5712 result.addAll(matchAllList); 5713 } else { 5714 // Browser/generic handling case. If there's a default browser, go straight 5715 // to that (but only if there is no other higher-priority match). 5716 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5717 int maxMatchPrio = 0; 5718 ResolveInfo defaultBrowserMatch = null; 5719 final int numCandidates = matchAllList.size(); 5720 for (int n = 0; n < numCandidates; n++) { 5721 ResolveInfo info = matchAllList.get(n); 5722 // track the highest overall match priority... 5723 if (info.priority > maxMatchPrio) { 5724 maxMatchPrio = info.priority; 5725 } 5726 // ...and the highest-priority default browser match 5727 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5728 if (defaultBrowserMatch == null 5729 || (defaultBrowserMatch.priority < info.priority)) { 5730 if (debug) { 5731 Slog.v(TAG, "Considering default browser match " + info); 5732 } 5733 defaultBrowserMatch = info; 5734 } 5735 } 5736 } 5737 if (defaultBrowserMatch != null 5738 && defaultBrowserMatch.priority >= maxMatchPrio 5739 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5740 { 5741 if (debug) { 5742 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5743 } 5744 result.add(defaultBrowserMatch); 5745 } else { 5746 result.addAll(matchAllList); 5747 } 5748 } 5749 5750 // If there is nothing selected, add all candidates and remove the ones that the user 5751 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5752 if (result.size() == 0) { 5753 result.addAll(candidates); 5754 result.removeAll(neverList); 5755 } 5756 } 5757 } 5758 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5759 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5760 result.size()); 5761 for (ResolveInfo info : result) { 5762 Slog.v(TAG, " + " + info.activityInfo); 5763 } 5764 } 5765 return result; 5766 } 5767 5768 // Returns a packed value as a long: 5769 // 5770 // high 'int'-sized word: link status: undefined/ask/never/always. 5771 // low 'int'-sized word: relative priority among 'always' results. 5772 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5773 long result = ps.getDomainVerificationStatusForUser(userId); 5774 // if none available, get the master status 5775 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5776 if (ps.getIntentFilterVerificationInfo() != null) { 5777 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5778 } 5779 } 5780 return result; 5781 } 5782 5783 private ResolveInfo querySkipCurrentProfileIntents( 5784 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5785 int flags, int sourceUserId) { 5786 if (matchingFilters != null) { 5787 int size = matchingFilters.size(); 5788 for (int i = 0; i < size; i ++) { 5789 CrossProfileIntentFilter filter = matchingFilters.get(i); 5790 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5791 // Checking if there are activities in the target user that can handle the 5792 // intent. 5793 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5794 resolvedType, flags, sourceUserId); 5795 if (resolveInfo != null) { 5796 return resolveInfo; 5797 } 5798 } 5799 } 5800 } 5801 return null; 5802 } 5803 5804 // Return matching ResolveInfo in target user if any. 5805 private ResolveInfo queryCrossProfileIntents( 5806 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5807 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5808 if (matchingFilters != null) { 5809 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5810 // match the same intent. For performance reasons, it is better not to 5811 // run queryIntent twice for the same userId 5812 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5813 int size = matchingFilters.size(); 5814 for (int i = 0; i < size; i++) { 5815 CrossProfileIntentFilter filter = matchingFilters.get(i); 5816 int targetUserId = filter.getTargetUserId(); 5817 boolean skipCurrentProfile = 5818 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5819 boolean skipCurrentProfileIfNoMatchFound = 5820 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5821 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5822 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5823 // Checking if there are activities in the target user that can handle the 5824 // intent. 5825 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5826 resolvedType, flags, sourceUserId); 5827 if (resolveInfo != null) return resolveInfo; 5828 alreadyTriedUserIds.put(targetUserId, true); 5829 } 5830 } 5831 } 5832 return null; 5833 } 5834 5835 /** 5836 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5837 * will forward the intent to the filter's target user. 5838 * Otherwise, returns null. 5839 */ 5840 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5841 String resolvedType, int flags, int sourceUserId) { 5842 int targetUserId = filter.getTargetUserId(); 5843 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5844 resolvedType, flags, targetUserId); 5845 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5846 // If all the matches in the target profile are suspended, return null. 5847 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5848 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5849 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5850 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5851 targetUserId); 5852 } 5853 } 5854 } 5855 return null; 5856 } 5857 5858 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5859 int sourceUserId, int targetUserId) { 5860 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5861 long ident = Binder.clearCallingIdentity(); 5862 boolean targetIsProfile; 5863 try { 5864 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5865 } finally { 5866 Binder.restoreCallingIdentity(ident); 5867 } 5868 String className; 5869 if (targetIsProfile) { 5870 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5871 } else { 5872 className = FORWARD_INTENT_TO_PARENT; 5873 } 5874 ComponentName forwardingActivityComponentName = new ComponentName( 5875 mAndroidApplication.packageName, className); 5876 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5877 sourceUserId); 5878 if (!targetIsProfile) { 5879 forwardingActivityInfo.showUserIcon = targetUserId; 5880 forwardingResolveInfo.noResourceId = true; 5881 } 5882 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5883 forwardingResolveInfo.priority = 0; 5884 forwardingResolveInfo.preferredOrder = 0; 5885 forwardingResolveInfo.match = 0; 5886 forwardingResolveInfo.isDefault = true; 5887 forwardingResolveInfo.filter = filter; 5888 forwardingResolveInfo.targetUserId = targetUserId; 5889 return forwardingResolveInfo; 5890 } 5891 5892 @Override 5893 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5894 Intent[] specifics, String[] specificTypes, Intent intent, 5895 String resolvedType, int flags, int userId) { 5896 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5897 specificTypes, intent, resolvedType, flags, userId)); 5898 } 5899 5900 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5901 Intent[] specifics, String[] specificTypes, Intent intent, 5902 String resolvedType, int flags, int userId) { 5903 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5904 flags = updateFlagsForResolve(flags, userId, intent); 5905 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5906 false /* requireFullPermission */, false /* checkShell */, 5907 "query intent activity options"); 5908 final String resultsAction = intent.getAction(); 5909 5910 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5911 | PackageManager.GET_RESOLVED_FILTER, userId); 5912 5913 if (DEBUG_INTENT_MATCHING) { 5914 Log.v(TAG, "Query " + intent + ": " + results); 5915 } 5916 5917 int specificsPos = 0; 5918 int N; 5919 5920 // todo: note that the algorithm used here is O(N^2). This 5921 // isn't a problem in our current environment, but if we start running 5922 // into situations where we have more than 5 or 10 matches then this 5923 // should probably be changed to something smarter... 5924 5925 // First we go through and resolve each of the specific items 5926 // that were supplied, taking care of removing any corresponding 5927 // duplicate items in the generic resolve list. 5928 if (specifics != null) { 5929 for (int i=0; i<specifics.length; i++) { 5930 final Intent sintent = specifics[i]; 5931 if (sintent == null) { 5932 continue; 5933 } 5934 5935 if (DEBUG_INTENT_MATCHING) { 5936 Log.v(TAG, "Specific #" + i + ": " + sintent); 5937 } 5938 5939 String action = sintent.getAction(); 5940 if (resultsAction != null && resultsAction.equals(action)) { 5941 // If this action was explicitly requested, then don't 5942 // remove things that have it. 5943 action = null; 5944 } 5945 5946 ResolveInfo ri = null; 5947 ActivityInfo ai = null; 5948 5949 ComponentName comp = sintent.getComponent(); 5950 if (comp == null) { 5951 ri = resolveIntent( 5952 sintent, 5953 specificTypes != null ? specificTypes[i] : null, 5954 flags, userId); 5955 if (ri == null) { 5956 continue; 5957 } 5958 if (ri == mResolveInfo) { 5959 // ACK! Must do something better with this. 5960 } 5961 ai = ri.activityInfo; 5962 comp = new ComponentName(ai.applicationInfo.packageName, 5963 ai.name); 5964 } else { 5965 ai = getActivityInfo(comp, flags, userId); 5966 if (ai == null) { 5967 continue; 5968 } 5969 } 5970 5971 // Look for any generic query activities that are duplicates 5972 // of this specific one, and remove them from the results. 5973 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5974 N = results.size(); 5975 int j; 5976 for (j=specificsPos; j<N; j++) { 5977 ResolveInfo sri = results.get(j); 5978 if ((sri.activityInfo.name.equals(comp.getClassName()) 5979 && sri.activityInfo.applicationInfo.packageName.equals( 5980 comp.getPackageName())) 5981 || (action != null && sri.filter.matchAction(action))) { 5982 results.remove(j); 5983 if (DEBUG_INTENT_MATCHING) Log.v( 5984 TAG, "Removing duplicate item from " + j 5985 + " due to specific " + specificsPos); 5986 if (ri == null) { 5987 ri = sri; 5988 } 5989 j--; 5990 N--; 5991 } 5992 } 5993 5994 // Add this specific item to its proper place. 5995 if (ri == null) { 5996 ri = new ResolveInfo(); 5997 ri.activityInfo = ai; 5998 } 5999 results.add(specificsPos, ri); 6000 ri.specificIndex = i; 6001 specificsPos++; 6002 } 6003 } 6004 6005 // Now we go through the remaining generic results and remove any 6006 // duplicate actions that are found here. 6007 N = results.size(); 6008 for (int i=specificsPos; i<N-1; i++) { 6009 final ResolveInfo rii = results.get(i); 6010 if (rii.filter == null) { 6011 continue; 6012 } 6013 6014 // Iterate over all of the actions of this result's intent 6015 // filter... typically this should be just one. 6016 final Iterator<String> it = rii.filter.actionsIterator(); 6017 if (it == null) { 6018 continue; 6019 } 6020 while (it.hasNext()) { 6021 final String action = it.next(); 6022 if (resultsAction != null && resultsAction.equals(action)) { 6023 // If this action was explicitly requested, then don't 6024 // remove things that have it. 6025 continue; 6026 } 6027 for (int j=i+1; j<N; j++) { 6028 final ResolveInfo rij = results.get(j); 6029 if (rij.filter != null && rij.filter.hasAction(action)) { 6030 results.remove(j); 6031 if (DEBUG_INTENT_MATCHING) Log.v( 6032 TAG, "Removing duplicate item from " + j 6033 + " due to action " + action + " at " + i); 6034 j--; 6035 N--; 6036 } 6037 } 6038 } 6039 6040 // If the caller didn't request filter information, drop it now 6041 // so we don't have to marshall/unmarshall it. 6042 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6043 rii.filter = null; 6044 } 6045 } 6046 6047 // Filter out the caller activity if so requested. 6048 if (caller != null) { 6049 N = results.size(); 6050 for (int i=0; i<N; i++) { 6051 ActivityInfo ainfo = results.get(i).activityInfo; 6052 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6053 && caller.getClassName().equals(ainfo.name)) { 6054 results.remove(i); 6055 break; 6056 } 6057 } 6058 } 6059 6060 // If the caller didn't request filter information, 6061 // drop them now so we don't have to 6062 // marshall/unmarshall it. 6063 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6064 N = results.size(); 6065 for (int i=0; i<N; i++) { 6066 results.get(i).filter = null; 6067 } 6068 } 6069 6070 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6071 return results; 6072 } 6073 6074 @Override 6075 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6076 String resolvedType, int flags, int userId) { 6077 return new ParceledListSlice<>( 6078 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6079 } 6080 6081 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6082 String resolvedType, int flags, int userId) { 6083 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6084 flags = updateFlagsForResolve(flags, userId, intent); 6085 ComponentName comp = intent.getComponent(); 6086 if (comp == null) { 6087 if (intent.getSelector() != null) { 6088 intent = intent.getSelector(); 6089 comp = intent.getComponent(); 6090 } 6091 } 6092 if (comp != null) { 6093 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6094 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6095 if (ai != null) { 6096 ResolveInfo ri = new ResolveInfo(); 6097 ri.activityInfo = ai; 6098 list.add(ri); 6099 } 6100 return list; 6101 } 6102 6103 // reader 6104 synchronized (mPackages) { 6105 String pkgName = intent.getPackage(); 6106 if (pkgName == null) { 6107 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6108 } 6109 final PackageParser.Package pkg = mPackages.get(pkgName); 6110 if (pkg != null) { 6111 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6112 userId); 6113 } 6114 return Collections.emptyList(); 6115 } 6116 } 6117 6118 @Override 6119 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6120 if (!sUserManager.exists(userId)) return null; 6121 flags = updateFlagsForResolve(flags, userId, intent); 6122 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6123 if (query != null) { 6124 if (query.size() >= 1) { 6125 // If there is more than one service with the same priority, 6126 // just arbitrarily pick the first one. 6127 return query.get(0); 6128 } 6129 } 6130 return null; 6131 } 6132 6133 @Override 6134 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6135 String resolvedType, int flags, int userId) { 6136 return new ParceledListSlice<>( 6137 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6138 } 6139 6140 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6141 String resolvedType, int flags, int userId) { 6142 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6143 flags = updateFlagsForResolve(flags, userId, intent); 6144 ComponentName comp = intent.getComponent(); 6145 if (comp == null) { 6146 if (intent.getSelector() != null) { 6147 intent = intent.getSelector(); 6148 comp = intent.getComponent(); 6149 } 6150 } 6151 if (comp != null) { 6152 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6153 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6154 if (si != null) { 6155 final ResolveInfo ri = new ResolveInfo(); 6156 ri.serviceInfo = si; 6157 list.add(ri); 6158 } 6159 return list; 6160 } 6161 6162 // reader 6163 synchronized (mPackages) { 6164 String pkgName = intent.getPackage(); 6165 if (pkgName == null) { 6166 return mServices.queryIntent(intent, resolvedType, flags, userId); 6167 } 6168 final PackageParser.Package pkg = mPackages.get(pkgName); 6169 if (pkg != null) { 6170 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6171 userId); 6172 } 6173 return Collections.emptyList(); 6174 } 6175 } 6176 6177 @Override 6178 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6179 String resolvedType, int flags, int userId) { 6180 return new ParceledListSlice<>( 6181 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6182 } 6183 6184 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6185 Intent intent, String resolvedType, int flags, int userId) { 6186 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6187 flags = updateFlagsForResolve(flags, userId, intent); 6188 ComponentName comp = intent.getComponent(); 6189 if (comp == null) { 6190 if (intent.getSelector() != null) { 6191 intent = intent.getSelector(); 6192 comp = intent.getComponent(); 6193 } 6194 } 6195 if (comp != null) { 6196 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6197 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6198 if (pi != null) { 6199 final ResolveInfo ri = new ResolveInfo(); 6200 ri.providerInfo = pi; 6201 list.add(ri); 6202 } 6203 return list; 6204 } 6205 6206 // reader 6207 synchronized (mPackages) { 6208 String pkgName = intent.getPackage(); 6209 if (pkgName == null) { 6210 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6211 } 6212 final PackageParser.Package pkg = mPackages.get(pkgName); 6213 if (pkg != null) { 6214 return mProviders.queryIntentForPackage( 6215 intent, resolvedType, flags, pkg.providers, userId); 6216 } 6217 return Collections.emptyList(); 6218 } 6219 } 6220 6221 @Override 6222 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6223 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6224 flags = updateFlagsForPackage(flags, userId, null); 6225 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6226 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6227 true /* requireFullPermission */, false /* checkShell */, 6228 "get installed packages"); 6229 6230 // writer 6231 synchronized (mPackages) { 6232 ArrayList<PackageInfo> list; 6233 if (listUninstalled) { 6234 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6235 for (PackageSetting ps : mSettings.mPackages.values()) { 6236 final PackageInfo pi; 6237 if (ps.pkg != null) { 6238 pi = generatePackageInfo(ps, flags, userId); 6239 } else { 6240 pi = generatePackageInfo(ps, flags, userId); 6241 } 6242 if (pi != null) { 6243 list.add(pi); 6244 } 6245 } 6246 } else { 6247 list = new ArrayList<PackageInfo>(mPackages.size()); 6248 for (PackageParser.Package p : mPackages.values()) { 6249 final PackageInfo pi = 6250 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6251 if (pi != null) { 6252 list.add(pi); 6253 } 6254 } 6255 } 6256 6257 return new ParceledListSlice<PackageInfo>(list); 6258 } 6259 } 6260 6261 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6262 String[] permissions, boolean[] tmp, int flags, int userId) { 6263 int numMatch = 0; 6264 final PermissionsState permissionsState = ps.getPermissionsState(); 6265 for (int i=0; i<permissions.length; i++) { 6266 final String permission = permissions[i]; 6267 if (permissionsState.hasPermission(permission, userId)) { 6268 tmp[i] = true; 6269 numMatch++; 6270 } else { 6271 tmp[i] = false; 6272 } 6273 } 6274 if (numMatch == 0) { 6275 return; 6276 } 6277 final PackageInfo pi; 6278 if (ps.pkg != null) { 6279 pi = generatePackageInfo(ps, flags, userId); 6280 } else { 6281 pi = generatePackageInfo(ps, flags, userId); 6282 } 6283 // The above might return null in cases of uninstalled apps or install-state 6284 // skew across users/profiles. 6285 if (pi != null) { 6286 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6287 if (numMatch == permissions.length) { 6288 pi.requestedPermissions = permissions; 6289 } else { 6290 pi.requestedPermissions = new String[numMatch]; 6291 numMatch = 0; 6292 for (int i=0; i<permissions.length; i++) { 6293 if (tmp[i]) { 6294 pi.requestedPermissions[numMatch] = permissions[i]; 6295 numMatch++; 6296 } 6297 } 6298 } 6299 } 6300 list.add(pi); 6301 } 6302 } 6303 6304 @Override 6305 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6306 String[] permissions, int flags, int userId) { 6307 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6308 flags = updateFlagsForPackage(flags, userId, permissions); 6309 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6310 6311 // writer 6312 synchronized (mPackages) { 6313 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6314 boolean[] tmpBools = new boolean[permissions.length]; 6315 if (listUninstalled) { 6316 for (PackageSetting ps : mSettings.mPackages.values()) { 6317 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6318 } 6319 } else { 6320 for (PackageParser.Package pkg : mPackages.values()) { 6321 PackageSetting ps = (PackageSetting)pkg.mExtras; 6322 if (ps != null) { 6323 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6324 userId); 6325 } 6326 } 6327 } 6328 6329 return new ParceledListSlice<PackageInfo>(list); 6330 } 6331 } 6332 6333 @Override 6334 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6335 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6336 flags = updateFlagsForApplication(flags, userId, null); 6337 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6338 6339 // writer 6340 synchronized (mPackages) { 6341 ArrayList<ApplicationInfo> list; 6342 if (listUninstalled) { 6343 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6344 for (PackageSetting ps : mSettings.mPackages.values()) { 6345 ApplicationInfo ai; 6346 if (ps.pkg != null) { 6347 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6348 ps.readUserState(userId), userId); 6349 } else { 6350 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6351 } 6352 if (ai != null) { 6353 list.add(ai); 6354 } 6355 } 6356 } else { 6357 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6358 for (PackageParser.Package p : mPackages.values()) { 6359 if (p.mExtras != null) { 6360 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6361 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6362 if (ai != null) { 6363 list.add(ai); 6364 } 6365 } 6366 } 6367 } 6368 6369 return new ParceledListSlice<ApplicationInfo>(list); 6370 } 6371 } 6372 6373 @Override 6374 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6375 if (DISABLE_EPHEMERAL_APPS) { 6376 return null; 6377 } 6378 6379 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6380 "getEphemeralApplications"); 6381 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6382 true /* requireFullPermission */, false /* checkShell */, 6383 "getEphemeralApplications"); 6384 synchronized (mPackages) { 6385 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6386 .getEphemeralApplicationsLPw(userId); 6387 if (ephemeralApps != null) { 6388 return new ParceledListSlice<>(ephemeralApps); 6389 } 6390 } 6391 return null; 6392 } 6393 6394 @Override 6395 public boolean isEphemeralApplication(String packageName, int userId) { 6396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6397 true /* requireFullPermission */, false /* checkShell */, 6398 "isEphemeral"); 6399 if (DISABLE_EPHEMERAL_APPS) { 6400 return false; 6401 } 6402 6403 if (!isCallerSameApp(packageName)) { 6404 return false; 6405 } 6406 synchronized (mPackages) { 6407 PackageParser.Package pkg = mPackages.get(packageName); 6408 if (pkg != null) { 6409 return pkg.applicationInfo.isEphemeralApp(); 6410 } 6411 } 6412 return false; 6413 } 6414 6415 @Override 6416 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6417 if (DISABLE_EPHEMERAL_APPS) { 6418 return null; 6419 } 6420 6421 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6422 true /* requireFullPermission */, false /* checkShell */, 6423 "getCookie"); 6424 if (!isCallerSameApp(packageName)) { 6425 return null; 6426 } 6427 synchronized (mPackages) { 6428 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6429 packageName, userId); 6430 } 6431 } 6432 6433 @Override 6434 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6435 if (DISABLE_EPHEMERAL_APPS) { 6436 return true; 6437 } 6438 6439 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6440 true /* requireFullPermission */, true /* checkShell */, 6441 "setCookie"); 6442 if (!isCallerSameApp(packageName)) { 6443 return false; 6444 } 6445 synchronized (mPackages) { 6446 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6447 packageName, cookie, userId); 6448 } 6449 } 6450 6451 @Override 6452 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6453 if (DISABLE_EPHEMERAL_APPS) { 6454 return null; 6455 } 6456 6457 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6458 "getEphemeralApplicationIcon"); 6459 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6460 true /* requireFullPermission */, false /* checkShell */, 6461 "getEphemeralApplicationIcon"); 6462 synchronized (mPackages) { 6463 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6464 packageName, userId); 6465 } 6466 } 6467 6468 private boolean isCallerSameApp(String packageName) { 6469 PackageParser.Package pkg = mPackages.get(packageName); 6470 return pkg != null 6471 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6472 } 6473 6474 @Override 6475 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6476 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6477 } 6478 6479 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6480 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6481 6482 // reader 6483 synchronized (mPackages) { 6484 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6485 final int userId = UserHandle.getCallingUserId(); 6486 while (i.hasNext()) { 6487 final PackageParser.Package p = i.next(); 6488 if (p.applicationInfo == null) continue; 6489 6490 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6491 && !p.applicationInfo.isDirectBootAware(); 6492 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6493 && p.applicationInfo.isDirectBootAware(); 6494 6495 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6496 && (!mSafeMode || isSystemApp(p)) 6497 && (matchesUnaware || matchesAware)) { 6498 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6499 if (ps != null) { 6500 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6501 ps.readUserState(userId), userId); 6502 if (ai != null) { 6503 finalList.add(ai); 6504 } 6505 } 6506 } 6507 } 6508 } 6509 6510 return finalList; 6511 } 6512 6513 @Override 6514 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6515 if (!sUserManager.exists(userId)) return null; 6516 flags = updateFlagsForComponent(flags, userId, name); 6517 // reader 6518 synchronized (mPackages) { 6519 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6520 PackageSetting ps = provider != null 6521 ? mSettings.mPackages.get(provider.owner.packageName) 6522 : null; 6523 return ps != null 6524 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6525 ? PackageParser.generateProviderInfo(provider, flags, 6526 ps.readUserState(userId), userId) 6527 : null; 6528 } 6529 } 6530 6531 /** 6532 * @deprecated 6533 */ 6534 @Deprecated 6535 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6536 // reader 6537 synchronized (mPackages) { 6538 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6539 .entrySet().iterator(); 6540 final int userId = UserHandle.getCallingUserId(); 6541 while (i.hasNext()) { 6542 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6543 PackageParser.Provider p = entry.getValue(); 6544 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6545 6546 if (ps != null && p.syncable 6547 && (!mSafeMode || (p.info.applicationInfo.flags 6548 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6549 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6550 ps.readUserState(userId), userId); 6551 if (info != null) { 6552 outNames.add(entry.getKey()); 6553 outInfo.add(info); 6554 } 6555 } 6556 } 6557 } 6558 } 6559 6560 @Override 6561 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6562 int uid, int flags) { 6563 final int userId = processName != null ? UserHandle.getUserId(uid) 6564 : UserHandle.getCallingUserId(); 6565 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6566 flags = updateFlagsForComponent(flags, userId, processName); 6567 6568 ArrayList<ProviderInfo> finalList = null; 6569 // reader 6570 synchronized (mPackages) { 6571 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6572 while (i.hasNext()) { 6573 final PackageParser.Provider p = i.next(); 6574 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6575 if (ps != null && p.info.authority != null 6576 && (processName == null 6577 || (p.info.processName.equals(processName) 6578 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6579 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6580 if (finalList == null) { 6581 finalList = new ArrayList<ProviderInfo>(3); 6582 } 6583 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6584 ps.readUserState(userId), userId); 6585 if (info != null) { 6586 finalList.add(info); 6587 } 6588 } 6589 } 6590 } 6591 6592 if (finalList != null) { 6593 Collections.sort(finalList, mProviderInitOrderSorter); 6594 return new ParceledListSlice<ProviderInfo>(finalList); 6595 } 6596 6597 return ParceledListSlice.emptyList(); 6598 } 6599 6600 @Override 6601 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6602 // reader 6603 synchronized (mPackages) { 6604 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6605 return PackageParser.generateInstrumentationInfo(i, flags); 6606 } 6607 } 6608 6609 @Override 6610 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6611 String targetPackage, int flags) { 6612 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6613 } 6614 6615 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6616 int flags) { 6617 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6618 6619 // reader 6620 synchronized (mPackages) { 6621 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6622 while (i.hasNext()) { 6623 final PackageParser.Instrumentation p = i.next(); 6624 if (targetPackage == null 6625 || targetPackage.equals(p.info.targetPackage)) { 6626 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6627 flags); 6628 if (ii != null) { 6629 finalList.add(ii); 6630 } 6631 } 6632 } 6633 } 6634 6635 return finalList; 6636 } 6637 6638 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6639 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6640 if (overlays == null) { 6641 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6642 return; 6643 } 6644 for (PackageParser.Package opkg : overlays.values()) { 6645 // Not much to do if idmap fails: we already logged the error 6646 // and we certainly don't want to abort installation of pkg simply 6647 // because an overlay didn't fit properly. For these reasons, 6648 // ignore the return value of createIdmapForPackagePairLI. 6649 createIdmapForPackagePairLI(pkg, opkg); 6650 } 6651 } 6652 6653 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6654 PackageParser.Package opkg) { 6655 if (!opkg.mTrustedOverlay) { 6656 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6657 opkg.baseCodePath + ": overlay not trusted"); 6658 return false; 6659 } 6660 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6661 if (overlaySet == null) { 6662 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6663 opkg.baseCodePath + " but target package has no known overlays"); 6664 return false; 6665 } 6666 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6667 // TODO: generate idmap for split APKs 6668 try { 6669 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6670 } catch (InstallerException e) { 6671 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6672 + opkg.baseCodePath); 6673 return false; 6674 } 6675 PackageParser.Package[] overlayArray = 6676 overlaySet.values().toArray(new PackageParser.Package[0]); 6677 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6678 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6679 return p1.mOverlayPriority - p2.mOverlayPriority; 6680 } 6681 }; 6682 Arrays.sort(overlayArray, cmp); 6683 6684 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6685 int i = 0; 6686 for (PackageParser.Package p : overlayArray) { 6687 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6688 } 6689 return true; 6690 } 6691 6692 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6693 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6694 try { 6695 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6696 } finally { 6697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6698 } 6699 } 6700 6701 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6702 final File[] files = dir.listFiles(); 6703 if (ArrayUtils.isEmpty(files)) { 6704 Log.d(TAG, "No files in app dir " + dir); 6705 return; 6706 } 6707 6708 if (DEBUG_PACKAGE_SCANNING) { 6709 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6710 + " flags=0x" + Integer.toHexString(parseFlags)); 6711 } 6712 6713 for (File file : files) { 6714 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6715 && !PackageInstallerService.isStageName(file.getName()); 6716 if (!isPackage) { 6717 // Ignore entries which are not packages 6718 continue; 6719 } 6720 try { 6721 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6722 scanFlags, currentTime, null); 6723 } catch (PackageManagerException e) { 6724 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6725 6726 // Delete invalid userdata apps 6727 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6728 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6729 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6730 removeCodePathLI(file); 6731 } 6732 } 6733 } 6734 } 6735 6736 private static File getSettingsProblemFile() { 6737 File dataDir = Environment.getDataDirectory(); 6738 File systemDir = new File(dataDir, "system"); 6739 File fname = new File(systemDir, "uiderrors.txt"); 6740 return fname; 6741 } 6742 6743 static void reportSettingsProblem(int priority, String msg) { 6744 logCriticalInfo(priority, msg); 6745 } 6746 6747 static void logCriticalInfo(int priority, String msg) { 6748 Slog.println(priority, TAG, msg); 6749 EventLogTags.writePmCriticalInfo(msg); 6750 try { 6751 File fname = getSettingsProblemFile(); 6752 FileOutputStream out = new FileOutputStream(fname, true); 6753 PrintWriter pw = new FastPrintWriter(out); 6754 SimpleDateFormat formatter = new SimpleDateFormat(); 6755 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6756 pw.println(dateString + ": " + msg); 6757 pw.close(); 6758 FileUtils.setPermissions( 6759 fname.toString(), 6760 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6761 -1, -1); 6762 } catch (java.io.IOException e) { 6763 } 6764 } 6765 6766 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6767 final int policyFlags) throws PackageManagerException { 6768 if (ps != null 6769 && ps.codePath.equals(srcFile) 6770 && ps.timeStamp == srcFile.lastModified() 6771 && !isCompatSignatureUpdateNeeded(pkg) 6772 && !isRecoverSignatureUpdateNeeded(pkg)) { 6773 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6774 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6775 ArraySet<PublicKey> signingKs; 6776 synchronized (mPackages) { 6777 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6778 } 6779 if (ps.signatures.mSignatures != null 6780 && ps.signatures.mSignatures.length != 0 6781 && signingKs != null) { 6782 // Optimization: reuse the existing cached certificates 6783 // if the package appears to be unchanged. 6784 pkg.mSignatures = ps.signatures.mSignatures; 6785 pkg.mSigningKeys = signingKs; 6786 return; 6787 } 6788 6789 Slog.w(TAG, "PackageSetting for " + ps.name 6790 + " is missing signatures. Collecting certs again to recover them."); 6791 } else { 6792 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6793 } 6794 6795 try { 6796 PackageParser.collectCertificates(pkg, policyFlags); 6797 } catch (PackageParserException e) { 6798 throw PackageManagerException.from(e); 6799 } 6800 } 6801 6802 /** 6803 * Traces a package scan. 6804 * @see #scanPackageLI(File, int, int, long, UserHandle) 6805 */ 6806 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6807 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6809 try { 6810 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6811 } finally { 6812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6813 } 6814 } 6815 6816 /** 6817 * Scans a package and returns the newly parsed package. 6818 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6819 */ 6820 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6821 long currentTime, UserHandle user) throws PackageManagerException { 6822 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6823 PackageParser pp = new PackageParser(); 6824 pp.setSeparateProcesses(mSeparateProcesses); 6825 pp.setOnlyCoreApps(mOnlyCore); 6826 pp.setDisplayMetrics(mMetrics); 6827 6828 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6829 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6830 } 6831 6832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6833 final PackageParser.Package pkg; 6834 try { 6835 pkg = pp.parsePackage(scanFile, parseFlags); 6836 } catch (PackageParserException e) { 6837 throw PackageManagerException.from(e); 6838 } finally { 6839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6840 } 6841 6842 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6843 } 6844 6845 /** 6846 * Scans a package and returns the newly parsed package. 6847 * @throws PackageManagerException on a parse error. 6848 */ 6849 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6850 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6851 throws PackageManagerException { 6852 // If the package has children and this is the first dive in the function 6853 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6854 // packages (parent and children) would be successfully scanned before the 6855 // actual scan since scanning mutates internal state and we want to atomically 6856 // install the package and its children. 6857 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6858 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6859 scanFlags |= SCAN_CHECK_ONLY; 6860 } 6861 } else { 6862 scanFlags &= ~SCAN_CHECK_ONLY; 6863 } 6864 6865 // Scan the parent 6866 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6867 scanFlags, currentTime, user); 6868 6869 // Scan the children 6870 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6871 for (int i = 0; i < childCount; i++) { 6872 PackageParser.Package childPackage = pkg.childPackages.get(i); 6873 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6874 currentTime, user); 6875 } 6876 6877 6878 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6879 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6880 } 6881 6882 return scannedPkg; 6883 } 6884 6885 /** 6886 * Scans a package and returns the newly parsed package. 6887 * @throws PackageManagerException on a parse error. 6888 */ 6889 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6890 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6891 throws PackageManagerException { 6892 PackageSetting ps = null; 6893 PackageSetting updatedPkg; 6894 // reader 6895 synchronized (mPackages) { 6896 // Look to see if we already know about this package. 6897 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6898 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6899 // This package has been renamed to its original name. Let's 6900 // use that. 6901 ps = mSettings.peekPackageLPr(oldName); 6902 } 6903 // If there was no original package, see one for the real package name. 6904 if (ps == null) { 6905 ps = mSettings.peekPackageLPr(pkg.packageName); 6906 } 6907 // Check to see if this package could be hiding/updating a system 6908 // package. Must look for it either under the original or real 6909 // package name depending on our state. 6910 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6911 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6912 6913 // If this is a package we don't know about on the system partition, we 6914 // may need to remove disabled child packages on the system partition 6915 // or may need to not add child packages if the parent apk is updated 6916 // on the data partition and no longer defines this child package. 6917 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6918 // If this is a parent package for an updated system app and this system 6919 // app got an OTA update which no longer defines some of the child packages 6920 // we have to prune them from the disabled system packages. 6921 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6922 if (disabledPs != null) { 6923 final int scannedChildCount = (pkg.childPackages != null) 6924 ? pkg.childPackages.size() : 0; 6925 final int disabledChildCount = disabledPs.childPackageNames != null 6926 ? disabledPs.childPackageNames.size() : 0; 6927 for (int i = 0; i < disabledChildCount; i++) { 6928 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6929 boolean disabledPackageAvailable = false; 6930 for (int j = 0; j < scannedChildCount; j++) { 6931 PackageParser.Package childPkg = pkg.childPackages.get(j); 6932 if (childPkg.packageName.equals(disabledChildPackageName)) { 6933 disabledPackageAvailable = true; 6934 break; 6935 } 6936 } 6937 if (!disabledPackageAvailable) { 6938 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6939 } 6940 } 6941 } 6942 } 6943 } 6944 6945 boolean updatedPkgBetter = false; 6946 // First check if this is a system package that may involve an update 6947 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6948 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6949 // it needs to drop FLAG_PRIVILEGED. 6950 if (locationIsPrivileged(scanFile)) { 6951 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6952 } else { 6953 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6954 } 6955 6956 if (ps != null && !ps.codePath.equals(scanFile)) { 6957 // The path has changed from what was last scanned... check the 6958 // version of the new path against what we have stored to determine 6959 // what to do. 6960 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6961 if (pkg.mVersionCode <= ps.versionCode) { 6962 // The system package has been updated and the code path does not match 6963 // Ignore entry. Skip it. 6964 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6965 + " ignored: updated version " + ps.versionCode 6966 + " better than this " + pkg.mVersionCode); 6967 if (!updatedPkg.codePath.equals(scanFile)) { 6968 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6969 + ps.name + " changing from " + updatedPkg.codePathString 6970 + " to " + scanFile); 6971 updatedPkg.codePath = scanFile; 6972 updatedPkg.codePathString = scanFile.toString(); 6973 updatedPkg.resourcePath = scanFile; 6974 updatedPkg.resourcePathString = scanFile.toString(); 6975 } 6976 updatedPkg.pkg = pkg; 6977 updatedPkg.versionCode = pkg.mVersionCode; 6978 6979 // Update the disabled system child packages to point to the package too. 6980 final int childCount = updatedPkg.childPackageNames != null 6981 ? updatedPkg.childPackageNames.size() : 0; 6982 for (int i = 0; i < childCount; i++) { 6983 String childPackageName = updatedPkg.childPackageNames.get(i); 6984 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6985 childPackageName); 6986 if (updatedChildPkg != null) { 6987 updatedChildPkg.pkg = pkg; 6988 updatedChildPkg.versionCode = pkg.mVersionCode; 6989 } 6990 } 6991 6992 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6993 + scanFile + " ignored: updated version " + ps.versionCode 6994 + " better than this " + pkg.mVersionCode); 6995 } else { 6996 // The current app on the system partition is better than 6997 // what we have updated to on the data partition; switch 6998 // back to the system partition version. 6999 // At this point, its safely assumed that package installation for 7000 // apps in system partition will go through. If not there won't be a working 7001 // version of the app 7002 // writer 7003 synchronized (mPackages) { 7004 // Just remove the loaded entries from package lists. 7005 mPackages.remove(ps.name); 7006 } 7007 7008 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7009 + " reverting from " + ps.codePathString 7010 + ": new version " + pkg.mVersionCode 7011 + " better than installed " + ps.versionCode); 7012 7013 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7014 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7015 synchronized (mInstallLock) { 7016 args.cleanUpResourcesLI(); 7017 } 7018 synchronized (mPackages) { 7019 mSettings.enableSystemPackageLPw(ps.name); 7020 } 7021 updatedPkgBetter = true; 7022 } 7023 } 7024 } 7025 7026 if (updatedPkg != null) { 7027 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7028 // initially 7029 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7030 7031 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7032 // flag set initially 7033 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7034 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7035 } 7036 } 7037 7038 // Verify certificates against what was last scanned 7039 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7040 7041 /* 7042 * A new system app appeared, but we already had a non-system one of the 7043 * same name installed earlier. 7044 */ 7045 boolean shouldHideSystemApp = false; 7046 if (updatedPkg == null && ps != null 7047 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7048 /* 7049 * Check to make sure the signatures match first. If they don't, 7050 * wipe the installed application and its data. 7051 */ 7052 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7053 != PackageManager.SIGNATURE_MATCH) { 7054 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7055 + " signatures don't match existing userdata copy; removing"); 7056 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7057 "scanPackageInternalLI")) { 7058 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7059 } 7060 ps = null; 7061 } else { 7062 /* 7063 * If the newly-added system app is an older version than the 7064 * already installed version, hide it. It will be scanned later 7065 * and re-added like an update. 7066 */ 7067 if (pkg.mVersionCode <= ps.versionCode) { 7068 shouldHideSystemApp = true; 7069 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7070 + " but new version " + pkg.mVersionCode + " better than installed " 7071 + ps.versionCode + "; hiding system"); 7072 } else { 7073 /* 7074 * The newly found system app is a newer version that the 7075 * one previously installed. Simply remove the 7076 * already-installed application and replace it with our own 7077 * while keeping the application data. 7078 */ 7079 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7080 + " reverting from " + ps.codePathString + ": new version " 7081 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7082 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7083 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7084 synchronized (mInstallLock) { 7085 args.cleanUpResourcesLI(); 7086 } 7087 } 7088 } 7089 } 7090 7091 // The apk is forward locked (not public) if its code and resources 7092 // are kept in different files. (except for app in either system or 7093 // vendor path). 7094 // TODO grab this value from PackageSettings 7095 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7096 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7097 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7098 } 7099 } 7100 7101 // TODO: extend to support forward-locked splits 7102 String resourcePath = null; 7103 String baseResourcePath = null; 7104 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7105 if (ps != null && ps.resourcePathString != null) { 7106 resourcePath = ps.resourcePathString; 7107 baseResourcePath = ps.resourcePathString; 7108 } else { 7109 // Should not happen at all. Just log an error. 7110 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7111 } 7112 } else { 7113 resourcePath = pkg.codePath; 7114 baseResourcePath = pkg.baseCodePath; 7115 } 7116 7117 // Set application objects path explicitly. 7118 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7119 pkg.setApplicationInfoCodePath(pkg.codePath); 7120 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7121 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7122 pkg.setApplicationInfoResourcePath(resourcePath); 7123 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7124 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7125 7126 // Note that we invoke the following method only if we are about to unpack an application 7127 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7128 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7129 7130 /* 7131 * If the system app should be overridden by a previously installed 7132 * data, hide the system app now and let the /data/app scan pick it up 7133 * again. 7134 */ 7135 if (shouldHideSystemApp) { 7136 synchronized (mPackages) { 7137 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7138 } 7139 } 7140 7141 return scannedPkg; 7142 } 7143 7144 private static String fixProcessName(String defProcessName, 7145 String processName, int uid) { 7146 if (processName == null) { 7147 return defProcessName; 7148 } 7149 return processName; 7150 } 7151 7152 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7153 throws PackageManagerException { 7154 if (pkgSetting.signatures.mSignatures != null) { 7155 // Already existing package. Make sure signatures match 7156 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7157 == PackageManager.SIGNATURE_MATCH; 7158 if (!match) { 7159 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7160 == PackageManager.SIGNATURE_MATCH; 7161 } 7162 if (!match) { 7163 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7164 == PackageManager.SIGNATURE_MATCH; 7165 } 7166 if (!match) { 7167 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7168 + pkg.packageName + " signatures do not match the " 7169 + "previously installed version; ignoring!"); 7170 } 7171 } 7172 7173 // Check for shared user signatures 7174 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7175 // Already existing package. Make sure signatures match 7176 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7177 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7178 if (!match) { 7179 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7180 == PackageManager.SIGNATURE_MATCH; 7181 } 7182 if (!match) { 7183 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7184 == PackageManager.SIGNATURE_MATCH; 7185 } 7186 if (!match) { 7187 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7188 "Package " + pkg.packageName 7189 + " has no signatures that match those in shared user " 7190 + pkgSetting.sharedUser.name + "; ignoring!"); 7191 } 7192 } 7193 } 7194 7195 /** 7196 * Enforces that only the system UID or root's UID can call a method exposed 7197 * via Binder. 7198 * 7199 * @param message used as message if SecurityException is thrown 7200 * @throws SecurityException if the caller is not system or root 7201 */ 7202 private static final void enforceSystemOrRoot(String message) { 7203 final int uid = Binder.getCallingUid(); 7204 if (uid != Process.SYSTEM_UID && uid != 0) { 7205 throw new SecurityException(message); 7206 } 7207 } 7208 7209 @Override 7210 public void performFstrimIfNeeded() { 7211 enforceSystemOrRoot("Only the system can request fstrim"); 7212 7213 // Before everything else, see whether we need to fstrim. 7214 try { 7215 IMountService ms = PackageHelper.getMountService(); 7216 if (ms != null) { 7217 final boolean isUpgrade = isUpgrade(); 7218 boolean doTrim = isUpgrade; 7219 if (doTrim) { 7220 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7221 } else { 7222 final long interval = android.provider.Settings.Global.getLong( 7223 mContext.getContentResolver(), 7224 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7225 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7226 if (interval > 0) { 7227 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7228 if (timeSinceLast > interval) { 7229 doTrim = true; 7230 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7231 + "; running immediately"); 7232 } 7233 } 7234 } 7235 if (doTrim) { 7236 if (!isFirstBoot()) { 7237 try { 7238 ActivityManagerNative.getDefault().showBootMessage( 7239 mContext.getResources().getString( 7240 R.string.android_upgrading_fstrim), true); 7241 } catch (RemoteException e) { 7242 } 7243 } 7244 ms.runMaintenance(); 7245 } 7246 } else { 7247 Slog.e(TAG, "Mount service unavailable!"); 7248 } 7249 } catch (RemoteException e) { 7250 // Can't happen; MountService is local 7251 } 7252 } 7253 7254 @Override 7255 public void updatePackagesIfNeeded() { 7256 enforceSystemOrRoot("Only the system can request package update"); 7257 7258 // We need to re-extract after an OTA. 7259 boolean causeUpgrade = isUpgrade(); 7260 7261 // First boot or factory reset. 7262 // Note: we also handle devices that are upgrading to N right now as if it is their 7263 // first boot, as they do not have profile data. 7264 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7265 7266 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7267 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7268 7269 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7270 return; 7271 } 7272 7273 List<PackageParser.Package> pkgs; 7274 synchronized (mPackages) { 7275 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7276 } 7277 7278 final long startTime = System.nanoTime(); 7279 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7280 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7281 7282 final int elapsedTimeSeconds = 7283 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7284 7285 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7286 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7287 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7288 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7289 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7290 } 7291 7292 /** 7293 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7294 * containing statistics about the invocation. The array consists of three elements, 7295 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7296 * and {@code numberOfPackagesFailed}. 7297 */ 7298 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7299 String compilerFilter) { 7300 7301 int numberOfPackagesVisited = 0; 7302 int numberOfPackagesOptimized = 0; 7303 int numberOfPackagesSkipped = 0; 7304 int numberOfPackagesFailed = 0; 7305 final int numberOfPackagesToDexopt = pkgs.size(); 7306 7307 for (PackageParser.Package pkg : pkgs) { 7308 numberOfPackagesVisited++; 7309 7310 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7311 if (DEBUG_DEXOPT) { 7312 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7313 } 7314 numberOfPackagesSkipped++; 7315 continue; 7316 } 7317 7318 if (DEBUG_DEXOPT) { 7319 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7320 numberOfPackagesToDexopt + ": " + pkg.packageName); 7321 } 7322 7323 if (showDialog) { 7324 try { 7325 ActivityManagerNative.getDefault().showBootMessage( 7326 mContext.getResources().getString(R.string.android_upgrading_apk, 7327 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7328 } catch (RemoteException e) { 7329 } 7330 } 7331 7332 // checkProfiles is false to avoid merging profiles during boot which 7333 // might interfere with background compilation (b/28612421). 7334 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7335 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7336 // trade-off worth doing to save boot time work. 7337 int dexOptStatus = performDexOptTraced(pkg.packageName, 7338 false /* checkProfiles */, 7339 compilerFilter, 7340 false /* force */); 7341 switch (dexOptStatus) { 7342 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7343 numberOfPackagesOptimized++; 7344 break; 7345 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7346 numberOfPackagesSkipped++; 7347 break; 7348 case PackageDexOptimizer.DEX_OPT_FAILED: 7349 numberOfPackagesFailed++; 7350 break; 7351 default: 7352 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7353 break; 7354 } 7355 } 7356 7357 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7358 numberOfPackagesFailed }; 7359 } 7360 7361 @Override 7362 public void notifyPackageUse(String packageName, int reason) { 7363 synchronized (mPackages) { 7364 PackageParser.Package p = mPackages.get(packageName); 7365 if (p == null) { 7366 return; 7367 } 7368 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7369 } 7370 } 7371 7372 // TODO: this is not used nor needed. Delete it. 7373 @Override 7374 public boolean performDexOptIfNeeded(String packageName) { 7375 int dexOptStatus = performDexOptTraced(packageName, 7376 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7377 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7378 } 7379 7380 @Override 7381 public boolean performDexOpt(String packageName, 7382 boolean checkProfiles, int compileReason, boolean force) { 7383 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7384 getCompilerFilterForReason(compileReason), force); 7385 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7386 } 7387 7388 @Override 7389 public boolean performDexOptMode(String packageName, 7390 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7391 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7392 targetCompilerFilter, force); 7393 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7394 } 7395 7396 private int performDexOptTraced(String packageName, 7397 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7398 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7399 try { 7400 return performDexOptInternal(packageName, checkProfiles, 7401 targetCompilerFilter, force); 7402 } finally { 7403 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7404 } 7405 } 7406 7407 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7408 // if the package can now be considered up to date for the given filter. 7409 private int performDexOptInternal(String packageName, 7410 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7411 PackageParser.Package p; 7412 synchronized (mPackages) { 7413 p = mPackages.get(packageName); 7414 if (p == null) { 7415 // Package could not be found. Report failure. 7416 return PackageDexOptimizer.DEX_OPT_FAILED; 7417 } 7418 mPackageUsage.write(false); 7419 } 7420 long callingId = Binder.clearCallingIdentity(); 7421 try { 7422 synchronized (mInstallLock) { 7423 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7424 targetCompilerFilter, force); 7425 } 7426 } finally { 7427 Binder.restoreCallingIdentity(callingId); 7428 } 7429 } 7430 7431 public ArraySet<String> getOptimizablePackages() { 7432 ArraySet<String> pkgs = new ArraySet<String>(); 7433 synchronized (mPackages) { 7434 for (PackageParser.Package p : mPackages.values()) { 7435 if (PackageDexOptimizer.canOptimizePackage(p)) { 7436 pkgs.add(p.packageName); 7437 } 7438 } 7439 } 7440 return pkgs; 7441 } 7442 7443 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7444 boolean checkProfiles, String targetCompilerFilter, 7445 boolean force) { 7446 // Select the dex optimizer based on the force parameter. 7447 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7448 // allocate an object here. 7449 PackageDexOptimizer pdo = force 7450 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7451 : mPackageDexOptimizer; 7452 7453 // Optimize all dependencies first. Note: we ignore the return value and march on 7454 // on errors. 7455 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7456 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7457 if (!deps.isEmpty()) { 7458 for (PackageParser.Package depPackage : deps) { 7459 // TODO: Analyze and investigate if we (should) profile libraries. 7460 // Currently this will do a full compilation of the library by default. 7461 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7462 false /* checkProfiles */, 7463 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7464 } 7465 } 7466 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7467 targetCompilerFilter); 7468 } 7469 7470 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7471 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7472 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7473 Set<String> collectedNames = new HashSet<>(); 7474 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7475 7476 retValue.remove(p); 7477 7478 return retValue; 7479 } else { 7480 return Collections.emptyList(); 7481 } 7482 } 7483 7484 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7485 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7486 if (!collectedNames.contains(p.packageName)) { 7487 collectedNames.add(p.packageName); 7488 collected.add(p); 7489 7490 if (p.usesLibraries != null) { 7491 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7492 } 7493 if (p.usesOptionalLibraries != null) { 7494 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7495 collectedNames); 7496 } 7497 } 7498 } 7499 7500 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7501 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7502 for (String libName : libs) { 7503 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7504 if (libPkg != null) { 7505 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7506 } 7507 } 7508 } 7509 7510 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7511 synchronized (mPackages) { 7512 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7513 if (lib != null && lib.apk != null) { 7514 return mPackages.get(lib.apk); 7515 } 7516 } 7517 return null; 7518 } 7519 7520 public void shutdown() { 7521 mPackageUsage.write(true); 7522 } 7523 7524 @Override 7525 public void dumpProfiles(String packageName) { 7526 PackageParser.Package pkg; 7527 synchronized (mPackages) { 7528 pkg = mPackages.get(packageName); 7529 if (pkg == null) { 7530 throw new IllegalArgumentException("Unknown package: " + packageName); 7531 } 7532 } 7533 /* Only the shell, root, or the app user should be able to dump profiles. */ 7534 int callingUid = Binder.getCallingUid(); 7535 if (callingUid != Process.SHELL_UID && 7536 callingUid != Process.ROOT_UID && 7537 callingUid != pkg.applicationInfo.uid) { 7538 throw new SecurityException("dumpProfiles"); 7539 } 7540 7541 synchronized (mInstallLock) { 7542 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7543 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7544 try { 7545 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7546 String gid = Integer.toString(sharedGid); 7547 String codePaths = TextUtils.join(";", allCodePaths); 7548 mInstaller.dumpProfiles(gid, packageName, codePaths); 7549 } catch (InstallerException e) { 7550 Slog.w(TAG, "Failed to dump profiles", e); 7551 } 7552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7553 } 7554 } 7555 7556 @Override 7557 public void forceDexOpt(String packageName) { 7558 enforceSystemOrRoot("forceDexOpt"); 7559 7560 PackageParser.Package pkg; 7561 synchronized (mPackages) { 7562 pkg = mPackages.get(packageName); 7563 if (pkg == null) { 7564 throw new IllegalArgumentException("Unknown package: " + packageName); 7565 } 7566 } 7567 7568 synchronized (mInstallLock) { 7569 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7570 7571 // Whoever is calling forceDexOpt wants a fully compiled package. 7572 // Don't use profiles since that may cause compilation to be skipped. 7573 final int res = performDexOptInternalWithDependenciesLI(pkg, 7574 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7575 true /* force */); 7576 7577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7578 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7579 throw new IllegalStateException("Failed to dexopt: " + res); 7580 } 7581 } 7582 } 7583 7584 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7585 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7586 Slog.w(TAG, "Unable to update from " + oldPkg.name 7587 + " to " + newPkg.packageName 7588 + ": old package not in system partition"); 7589 return false; 7590 } else if (mPackages.get(oldPkg.name) != null) { 7591 Slog.w(TAG, "Unable to update from " + oldPkg.name 7592 + " to " + newPkg.packageName 7593 + ": old package still exists"); 7594 return false; 7595 } 7596 return true; 7597 } 7598 7599 void removeCodePathLI(File codePath) { 7600 if (codePath.isDirectory()) { 7601 try { 7602 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7603 } catch (InstallerException e) { 7604 Slog.w(TAG, "Failed to remove code path", e); 7605 } 7606 } else { 7607 codePath.delete(); 7608 } 7609 } 7610 7611 private int[] resolveUserIds(int userId) { 7612 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7613 } 7614 7615 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7616 if (pkg == null) { 7617 Slog.wtf(TAG, "Package was null!", new Throwable()); 7618 return; 7619 } 7620 clearAppDataLeafLIF(pkg, userId, flags); 7621 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7622 for (int i = 0; i < childCount; i++) { 7623 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7624 } 7625 } 7626 7627 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7628 final PackageSetting ps; 7629 synchronized (mPackages) { 7630 ps = mSettings.mPackages.get(pkg.packageName); 7631 } 7632 for (int realUserId : resolveUserIds(userId)) { 7633 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7634 try { 7635 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7636 ceDataInode); 7637 } catch (InstallerException e) { 7638 Slog.w(TAG, String.valueOf(e)); 7639 } 7640 } 7641 } 7642 7643 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7644 if (pkg == null) { 7645 Slog.wtf(TAG, "Package was null!", new Throwable()); 7646 return; 7647 } 7648 destroyAppDataLeafLIF(pkg, userId, flags); 7649 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7650 for (int i = 0; i < childCount; i++) { 7651 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7652 } 7653 } 7654 7655 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7656 final PackageSetting ps; 7657 synchronized (mPackages) { 7658 ps = mSettings.mPackages.get(pkg.packageName); 7659 } 7660 for (int realUserId : resolveUserIds(userId)) { 7661 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7662 try { 7663 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7664 ceDataInode); 7665 } catch (InstallerException e) { 7666 Slog.w(TAG, String.valueOf(e)); 7667 } 7668 } 7669 } 7670 7671 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7672 if (pkg == null) { 7673 Slog.wtf(TAG, "Package was null!", new Throwable()); 7674 return; 7675 } 7676 destroyAppProfilesLeafLIF(pkg); 7677 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7678 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7679 for (int i = 0; i < childCount; i++) { 7680 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7681 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7682 true /* removeBaseMarker */); 7683 } 7684 } 7685 7686 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7687 boolean removeBaseMarker) { 7688 if (pkg.isForwardLocked()) { 7689 return; 7690 } 7691 7692 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7693 try { 7694 path = PackageManagerServiceUtils.realpath(new File(path)); 7695 } catch (IOException e) { 7696 // TODO: Should we return early here ? 7697 Slog.w(TAG, "Failed to get canonical path", e); 7698 continue; 7699 } 7700 7701 final String useMarker = path.replace('/', '@'); 7702 for (int realUserId : resolveUserIds(userId)) { 7703 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7704 if (removeBaseMarker) { 7705 File foreignUseMark = new File(profileDir, useMarker); 7706 if (foreignUseMark.exists()) { 7707 if (!foreignUseMark.delete()) { 7708 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7709 + pkg.packageName); 7710 } 7711 } 7712 } 7713 7714 File[] markers = profileDir.listFiles(); 7715 if (markers != null) { 7716 final String searchString = "@" + pkg.packageName + "@"; 7717 // We also delete all markers that contain the package name we're 7718 // uninstalling. These are associated with secondary dex-files belonging 7719 // to the package. Reconstructing the path of these dex files is messy 7720 // in general. 7721 for (File marker : markers) { 7722 if (marker.getName().indexOf(searchString) > 0) { 7723 if (!marker.delete()) { 7724 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7725 + pkg.packageName); 7726 } 7727 } 7728 } 7729 } 7730 } 7731 } 7732 } 7733 7734 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7735 try { 7736 mInstaller.destroyAppProfiles(pkg.packageName); 7737 } catch (InstallerException e) { 7738 Slog.w(TAG, String.valueOf(e)); 7739 } 7740 } 7741 7742 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7743 if (pkg == null) { 7744 Slog.wtf(TAG, "Package was null!", new Throwable()); 7745 return; 7746 } 7747 clearAppProfilesLeafLIF(pkg); 7748 // We don't remove the base foreign use marker when clearing profiles because 7749 // we will rename it when the app is updated. Unlike the actual profile contents, 7750 // the foreign use marker is good across installs. 7751 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7752 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7753 for (int i = 0; i < childCount; i++) { 7754 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7755 } 7756 } 7757 7758 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7759 try { 7760 mInstaller.clearAppProfiles(pkg.packageName); 7761 } catch (InstallerException e) { 7762 Slog.w(TAG, String.valueOf(e)); 7763 } 7764 } 7765 7766 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7767 long lastUpdateTime) { 7768 // Set parent install/update time 7769 PackageSetting ps = (PackageSetting) pkg.mExtras; 7770 if (ps != null) { 7771 ps.firstInstallTime = firstInstallTime; 7772 ps.lastUpdateTime = lastUpdateTime; 7773 } 7774 // Set children install/update time 7775 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7776 for (int i = 0; i < childCount; i++) { 7777 PackageParser.Package childPkg = pkg.childPackages.get(i); 7778 ps = (PackageSetting) childPkg.mExtras; 7779 if (ps != null) { 7780 ps.firstInstallTime = firstInstallTime; 7781 ps.lastUpdateTime = lastUpdateTime; 7782 } 7783 } 7784 } 7785 7786 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7787 PackageParser.Package changingLib) { 7788 if (file.path != null) { 7789 usesLibraryFiles.add(file.path); 7790 return; 7791 } 7792 PackageParser.Package p = mPackages.get(file.apk); 7793 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7794 // If we are doing this while in the middle of updating a library apk, 7795 // then we need to make sure to use that new apk for determining the 7796 // dependencies here. (We haven't yet finished committing the new apk 7797 // to the package manager state.) 7798 if (p == null || p.packageName.equals(changingLib.packageName)) { 7799 p = changingLib; 7800 } 7801 } 7802 if (p != null) { 7803 usesLibraryFiles.addAll(p.getAllCodePaths()); 7804 } 7805 } 7806 7807 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7808 PackageParser.Package changingLib) throws PackageManagerException { 7809 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7810 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7811 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7812 for (int i=0; i<N; i++) { 7813 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7814 if (file == null) { 7815 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7816 "Package " + pkg.packageName + " requires unavailable shared library " 7817 + pkg.usesLibraries.get(i) + "; failing!"); 7818 } 7819 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7820 } 7821 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7822 for (int i=0; i<N; i++) { 7823 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7824 if (file == null) { 7825 Slog.w(TAG, "Package " + pkg.packageName 7826 + " desires unavailable shared library " 7827 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7828 } else { 7829 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7830 } 7831 } 7832 N = usesLibraryFiles.size(); 7833 if (N > 0) { 7834 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7835 } else { 7836 pkg.usesLibraryFiles = null; 7837 } 7838 } 7839 } 7840 7841 private static boolean hasString(List<String> list, List<String> which) { 7842 if (list == null) { 7843 return false; 7844 } 7845 for (int i=list.size()-1; i>=0; i--) { 7846 for (int j=which.size()-1; j>=0; j--) { 7847 if (which.get(j).equals(list.get(i))) { 7848 return true; 7849 } 7850 } 7851 } 7852 return false; 7853 } 7854 7855 private void updateAllSharedLibrariesLPw() { 7856 for (PackageParser.Package pkg : mPackages.values()) { 7857 try { 7858 updateSharedLibrariesLPw(pkg, null); 7859 } catch (PackageManagerException e) { 7860 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7861 } 7862 } 7863 } 7864 7865 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7866 PackageParser.Package changingPkg) { 7867 ArrayList<PackageParser.Package> res = null; 7868 for (PackageParser.Package pkg : mPackages.values()) { 7869 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7870 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7871 if (res == null) { 7872 res = new ArrayList<PackageParser.Package>(); 7873 } 7874 res.add(pkg); 7875 try { 7876 updateSharedLibrariesLPw(pkg, changingPkg); 7877 } catch (PackageManagerException e) { 7878 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7879 } 7880 } 7881 } 7882 return res; 7883 } 7884 7885 /** 7886 * Derive the value of the {@code cpuAbiOverride} based on the provided 7887 * value and an optional stored value from the package settings. 7888 */ 7889 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7890 String cpuAbiOverride = null; 7891 7892 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7893 cpuAbiOverride = null; 7894 } else if (abiOverride != null) { 7895 cpuAbiOverride = abiOverride; 7896 } else if (settings != null) { 7897 cpuAbiOverride = settings.cpuAbiOverrideString; 7898 } 7899 7900 return cpuAbiOverride; 7901 } 7902 7903 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7904 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7905 throws PackageManagerException { 7906 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7907 // If the package has children and this is the first dive in the function 7908 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7909 // whether all packages (parent and children) would be successfully scanned 7910 // before the actual scan since scanning mutates internal state and we want 7911 // to atomically install the package and its children. 7912 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7913 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7914 scanFlags |= SCAN_CHECK_ONLY; 7915 } 7916 } else { 7917 scanFlags &= ~SCAN_CHECK_ONLY; 7918 } 7919 7920 final PackageParser.Package scannedPkg; 7921 try { 7922 // Scan the parent 7923 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7924 // Scan the children 7925 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7926 for (int i = 0; i < childCount; i++) { 7927 PackageParser.Package childPkg = pkg.childPackages.get(i); 7928 scanPackageLI(childPkg, policyFlags, 7929 scanFlags, currentTime, user); 7930 } 7931 } finally { 7932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7933 } 7934 7935 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7936 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7937 } 7938 7939 return scannedPkg; 7940 } 7941 7942 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7943 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7944 boolean success = false; 7945 try { 7946 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7947 currentTime, user); 7948 success = true; 7949 return res; 7950 } finally { 7951 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7952 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7953 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7954 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7955 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7956 } 7957 } 7958 } 7959 7960 /** 7961 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7962 */ 7963 private static boolean apkHasCode(String fileName) { 7964 StrictJarFile jarFile = null; 7965 try { 7966 jarFile = new StrictJarFile(fileName, 7967 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7968 return jarFile.findEntry("classes.dex") != null; 7969 } catch (IOException ignore) { 7970 } finally { 7971 try { 7972 jarFile.close(); 7973 } catch (IOException ignore) {} 7974 } 7975 return false; 7976 } 7977 7978 /** 7979 * Enforces code policy for the package. This ensures that if an APK has 7980 * declared hasCode="true" in its manifest that the APK actually contains 7981 * code. 7982 * 7983 * @throws PackageManagerException If bytecode could not be found when it should exist 7984 */ 7985 private static void enforceCodePolicy(PackageParser.Package pkg) 7986 throws PackageManagerException { 7987 final boolean shouldHaveCode = 7988 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7989 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7990 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7991 "Package " + pkg.baseCodePath + " code is missing"); 7992 } 7993 7994 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7995 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7996 final boolean splitShouldHaveCode = 7997 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7998 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7999 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8000 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8001 } 8002 } 8003 } 8004 } 8005 8006 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8007 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8008 throws PackageManagerException { 8009 final File scanFile = new File(pkg.codePath); 8010 if (pkg.applicationInfo.getCodePath() == null || 8011 pkg.applicationInfo.getResourcePath() == null) { 8012 // Bail out. The resource and code paths haven't been set. 8013 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8014 "Code and resource paths haven't been set correctly"); 8015 } 8016 8017 // Apply policy 8018 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8019 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8020 if (pkg.applicationInfo.isDirectBootAware()) { 8021 // we're direct boot aware; set for all components 8022 for (PackageParser.Service s : pkg.services) { 8023 s.info.encryptionAware = s.info.directBootAware = true; 8024 } 8025 for (PackageParser.Provider p : pkg.providers) { 8026 p.info.encryptionAware = p.info.directBootAware = true; 8027 } 8028 for (PackageParser.Activity a : pkg.activities) { 8029 a.info.encryptionAware = a.info.directBootAware = true; 8030 } 8031 for (PackageParser.Activity r : pkg.receivers) { 8032 r.info.encryptionAware = r.info.directBootAware = true; 8033 } 8034 } 8035 } else { 8036 // Only allow system apps to be flagged as core apps. 8037 pkg.coreApp = false; 8038 // clear flags not applicable to regular apps 8039 pkg.applicationInfo.privateFlags &= 8040 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8041 pkg.applicationInfo.privateFlags &= 8042 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8043 } 8044 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8045 8046 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8047 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8048 } 8049 8050 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8051 enforceCodePolicy(pkg); 8052 } 8053 8054 if (mCustomResolverComponentName != null && 8055 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8056 setUpCustomResolverActivity(pkg); 8057 } 8058 8059 if (pkg.packageName.equals("android")) { 8060 synchronized (mPackages) { 8061 if (mAndroidApplication != null) { 8062 Slog.w(TAG, "*************************************************"); 8063 Slog.w(TAG, "Core android package being redefined. Skipping."); 8064 Slog.w(TAG, " file=" + scanFile); 8065 Slog.w(TAG, "*************************************************"); 8066 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8067 "Core android package being redefined. Skipping."); 8068 } 8069 8070 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8071 // Set up information for our fall-back user intent resolution activity. 8072 mPlatformPackage = pkg; 8073 pkg.mVersionCode = mSdkVersion; 8074 mAndroidApplication = pkg.applicationInfo; 8075 8076 if (!mResolverReplaced) { 8077 mResolveActivity.applicationInfo = mAndroidApplication; 8078 mResolveActivity.name = ResolverActivity.class.getName(); 8079 mResolveActivity.packageName = mAndroidApplication.packageName; 8080 mResolveActivity.processName = "system:ui"; 8081 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8082 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8083 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8084 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8085 mResolveActivity.exported = true; 8086 mResolveActivity.enabled = true; 8087 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8088 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8089 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8090 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8091 | ActivityInfo.CONFIG_ORIENTATION 8092 | ActivityInfo.CONFIG_KEYBOARD 8093 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8094 mResolveInfo.activityInfo = mResolveActivity; 8095 mResolveInfo.priority = 0; 8096 mResolveInfo.preferredOrder = 0; 8097 mResolveInfo.match = 0; 8098 mResolveComponentName = new ComponentName( 8099 mAndroidApplication.packageName, mResolveActivity.name); 8100 } 8101 } 8102 } 8103 } 8104 8105 if (DEBUG_PACKAGE_SCANNING) { 8106 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8107 Log.d(TAG, "Scanning package " + pkg.packageName); 8108 } 8109 8110 synchronized (mPackages) { 8111 if (mPackages.containsKey(pkg.packageName) 8112 || mSharedLibraries.containsKey(pkg.packageName)) { 8113 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8114 "Application package " + pkg.packageName 8115 + " already installed. Skipping duplicate."); 8116 } 8117 8118 // If we're only installing presumed-existing packages, require that the 8119 // scanned APK is both already known and at the path previously established 8120 // for it. Previously unknown packages we pick up normally, but if we have an 8121 // a priori expectation about this package's install presence, enforce it. 8122 // With a singular exception for new system packages. When an OTA contains 8123 // a new system package, we allow the codepath to change from a system location 8124 // to the user-installed location. If we don't allow this change, any newer, 8125 // user-installed version of the application will be ignored. 8126 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8127 if (mExpectingBetter.containsKey(pkg.packageName)) { 8128 logCriticalInfo(Log.WARN, 8129 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8130 } else { 8131 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8132 if (known != null) { 8133 if (DEBUG_PACKAGE_SCANNING) { 8134 Log.d(TAG, "Examining " + pkg.codePath 8135 + " and requiring known paths " + known.codePathString 8136 + " & " + known.resourcePathString); 8137 } 8138 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8139 || !pkg.applicationInfo.getResourcePath().equals( 8140 known.resourcePathString)) { 8141 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8142 "Application package " + pkg.packageName 8143 + " found at " + pkg.applicationInfo.getCodePath() 8144 + " but expected at " + known.codePathString 8145 + "; ignoring."); 8146 } 8147 } 8148 } 8149 } 8150 } 8151 8152 // Initialize package source and resource directories 8153 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8154 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8155 8156 SharedUserSetting suid = null; 8157 PackageSetting pkgSetting = null; 8158 8159 if (!isSystemApp(pkg)) { 8160 // Only system apps can use these features. 8161 pkg.mOriginalPackages = null; 8162 pkg.mRealPackage = null; 8163 pkg.mAdoptPermissions = null; 8164 } 8165 8166 // Getting the package setting may have a side-effect, so if we 8167 // are only checking if scan would succeed, stash a copy of the 8168 // old setting to restore at the end. 8169 PackageSetting nonMutatedPs = null; 8170 8171 // writer 8172 synchronized (mPackages) { 8173 if (pkg.mSharedUserId != null) { 8174 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8175 if (suid == null) { 8176 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8177 "Creating application package " + pkg.packageName 8178 + " for shared user failed"); 8179 } 8180 if (DEBUG_PACKAGE_SCANNING) { 8181 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8182 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8183 + "): packages=" + suid.packages); 8184 } 8185 } 8186 8187 // Check if we are renaming from an original package name. 8188 PackageSetting origPackage = null; 8189 String realName = null; 8190 if (pkg.mOriginalPackages != null) { 8191 // This package may need to be renamed to a previously 8192 // installed name. Let's check on that... 8193 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8194 if (pkg.mOriginalPackages.contains(renamed)) { 8195 // This package had originally been installed as the 8196 // original name, and we have already taken care of 8197 // transitioning to the new one. Just update the new 8198 // one to continue using the old name. 8199 realName = pkg.mRealPackage; 8200 if (!pkg.packageName.equals(renamed)) { 8201 // Callers into this function may have already taken 8202 // care of renaming the package; only do it here if 8203 // it is not already done. 8204 pkg.setPackageName(renamed); 8205 } 8206 8207 } else { 8208 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8209 if ((origPackage = mSettings.peekPackageLPr( 8210 pkg.mOriginalPackages.get(i))) != null) { 8211 // We do have the package already installed under its 8212 // original name... should we use it? 8213 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8214 // New package is not compatible with original. 8215 origPackage = null; 8216 continue; 8217 } else if (origPackage.sharedUser != null) { 8218 // Make sure uid is compatible between packages. 8219 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8220 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8221 + " to " + pkg.packageName + ": old uid " 8222 + origPackage.sharedUser.name 8223 + " differs from " + pkg.mSharedUserId); 8224 origPackage = null; 8225 continue; 8226 } 8227 // TODO: Add case when shared user id is added [b/28144775] 8228 } else { 8229 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8230 + pkg.packageName + " to old name " + origPackage.name); 8231 } 8232 break; 8233 } 8234 } 8235 } 8236 } 8237 8238 if (mTransferedPackages.contains(pkg.packageName)) { 8239 Slog.w(TAG, "Package " + pkg.packageName 8240 + " was transferred to another, but its .apk remains"); 8241 } 8242 8243 // See comments in nonMutatedPs declaration 8244 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8245 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8246 if (foundPs != null) { 8247 nonMutatedPs = new PackageSetting(foundPs); 8248 } 8249 } 8250 8251 // Just create the setting, don't add it yet. For already existing packages 8252 // the PkgSetting exists already and doesn't have to be created. 8253 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8254 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8255 pkg.applicationInfo.primaryCpuAbi, 8256 pkg.applicationInfo.secondaryCpuAbi, 8257 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8258 user, false); 8259 if (pkgSetting == null) { 8260 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8261 "Creating application package " + pkg.packageName + " failed"); 8262 } 8263 8264 if (pkgSetting.origPackage != null) { 8265 // If we are first transitioning from an original package, 8266 // fix up the new package's name now. We need to do this after 8267 // looking up the package under its new name, so getPackageLP 8268 // can take care of fiddling things correctly. 8269 pkg.setPackageName(origPackage.name); 8270 8271 // File a report about this. 8272 String msg = "New package " + pkgSetting.realName 8273 + " renamed to replace old package " + pkgSetting.name; 8274 reportSettingsProblem(Log.WARN, msg); 8275 8276 // Make a note of it. 8277 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8278 mTransferedPackages.add(origPackage.name); 8279 } 8280 8281 // No longer need to retain this. 8282 pkgSetting.origPackage = null; 8283 } 8284 8285 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8286 // Make a note of it. 8287 mTransferedPackages.add(pkg.packageName); 8288 } 8289 8290 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8291 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8292 } 8293 8294 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8295 // Check all shared libraries and map to their actual file path. 8296 // We only do this here for apps not on a system dir, because those 8297 // are the only ones that can fail an install due to this. We 8298 // will take care of the system apps by updating all of their 8299 // library paths after the scan is done. 8300 updateSharedLibrariesLPw(pkg, null); 8301 } 8302 8303 if (mFoundPolicyFile) { 8304 SELinuxMMAC.assignSeinfoValue(pkg); 8305 } 8306 8307 pkg.applicationInfo.uid = pkgSetting.appId; 8308 pkg.mExtras = pkgSetting; 8309 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8310 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8311 // We just determined the app is signed correctly, so bring 8312 // over the latest parsed certs. 8313 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8314 } else { 8315 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8316 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8317 "Package " + pkg.packageName + " upgrade keys do not match the " 8318 + "previously installed version"); 8319 } else { 8320 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8321 String msg = "System package " + pkg.packageName 8322 + " signature changed; retaining data."; 8323 reportSettingsProblem(Log.WARN, msg); 8324 } 8325 } 8326 } else { 8327 try { 8328 verifySignaturesLP(pkgSetting, pkg); 8329 // We just determined the app is signed correctly, so bring 8330 // over the latest parsed certs. 8331 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8332 } catch (PackageManagerException e) { 8333 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8334 throw e; 8335 } 8336 // The signature has changed, but this package is in the system 8337 // image... let's recover! 8338 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8339 // However... if this package is part of a shared user, but it 8340 // doesn't match the signature of the shared user, let's fail. 8341 // What this means is that you can't change the signatures 8342 // associated with an overall shared user, which doesn't seem all 8343 // that unreasonable. 8344 if (pkgSetting.sharedUser != null) { 8345 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8346 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8347 throw new PackageManagerException( 8348 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8349 "Signature mismatch for shared user: " 8350 + pkgSetting.sharedUser); 8351 } 8352 } 8353 // File a report about this. 8354 String msg = "System package " + pkg.packageName 8355 + " signature changed; retaining data."; 8356 reportSettingsProblem(Log.WARN, msg); 8357 } 8358 } 8359 // Verify that this new package doesn't have any content providers 8360 // that conflict with existing packages. Only do this if the 8361 // package isn't already installed, since we don't want to break 8362 // things that are installed. 8363 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8364 final int N = pkg.providers.size(); 8365 int i; 8366 for (i=0; i<N; i++) { 8367 PackageParser.Provider p = pkg.providers.get(i); 8368 if (p.info.authority != null) { 8369 String names[] = p.info.authority.split(";"); 8370 for (int j = 0; j < names.length; j++) { 8371 if (mProvidersByAuthority.containsKey(names[j])) { 8372 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8373 final String otherPackageName = 8374 ((other != null && other.getComponentName() != null) ? 8375 other.getComponentName().getPackageName() : "?"); 8376 throw new PackageManagerException( 8377 INSTALL_FAILED_CONFLICTING_PROVIDER, 8378 "Can't install because provider name " + names[j] 8379 + " (in package " + pkg.applicationInfo.packageName 8380 + ") is already used by " + otherPackageName); 8381 } 8382 } 8383 } 8384 } 8385 } 8386 8387 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8388 // This package wants to adopt ownership of permissions from 8389 // another package. 8390 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8391 final String origName = pkg.mAdoptPermissions.get(i); 8392 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8393 if (orig != null) { 8394 if (verifyPackageUpdateLPr(orig, pkg)) { 8395 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8396 + pkg.packageName); 8397 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8398 } 8399 } 8400 } 8401 } 8402 } 8403 8404 final String pkgName = pkg.packageName; 8405 8406 final long scanFileTime = scanFile.lastModified(); 8407 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8408 pkg.applicationInfo.processName = fixProcessName( 8409 pkg.applicationInfo.packageName, 8410 pkg.applicationInfo.processName, 8411 pkg.applicationInfo.uid); 8412 8413 if (pkg != mPlatformPackage) { 8414 // Get all of our default paths setup 8415 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8416 } 8417 8418 final String path = scanFile.getPath(); 8419 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8420 8421 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8422 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8423 8424 // Some system apps still use directory structure for native libraries 8425 // in which case we might end up not detecting abi solely based on apk 8426 // structure. Try to detect abi based on directory structure. 8427 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8428 pkg.applicationInfo.primaryCpuAbi == null) { 8429 setBundledAppAbisAndRoots(pkg, pkgSetting); 8430 setNativeLibraryPaths(pkg); 8431 } 8432 8433 } else { 8434 if ((scanFlags & SCAN_MOVE) != 0) { 8435 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8436 // but we already have this packages package info in the PackageSetting. We just 8437 // use that and derive the native library path based on the new codepath. 8438 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8439 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8440 } 8441 8442 // Set native library paths again. For moves, the path will be updated based on the 8443 // ABIs we've determined above. For non-moves, the path will be updated based on the 8444 // ABIs we determined during compilation, but the path will depend on the final 8445 // package path (after the rename away from the stage path). 8446 setNativeLibraryPaths(pkg); 8447 } 8448 8449 // This is a special case for the "system" package, where the ABI is 8450 // dictated by the zygote configuration (and init.rc). We should keep track 8451 // of this ABI so that we can deal with "normal" applications that run under 8452 // the same UID correctly. 8453 if (mPlatformPackage == pkg) { 8454 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8455 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8456 } 8457 8458 // If there's a mismatch between the abi-override in the package setting 8459 // and the abiOverride specified for the install. Warn about this because we 8460 // would've already compiled the app without taking the package setting into 8461 // account. 8462 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8463 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8464 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8465 " for package " + pkg.packageName); 8466 } 8467 } 8468 8469 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8470 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8471 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8472 8473 // Copy the derived override back to the parsed package, so that we can 8474 // update the package settings accordingly. 8475 pkg.cpuAbiOverride = cpuAbiOverride; 8476 8477 if (DEBUG_ABI_SELECTION) { 8478 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8479 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8480 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8481 } 8482 8483 // Push the derived path down into PackageSettings so we know what to 8484 // clean up at uninstall time. 8485 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8486 8487 if (DEBUG_ABI_SELECTION) { 8488 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8489 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8490 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8491 } 8492 8493 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8494 // We don't do this here during boot because we can do it all 8495 // at once after scanning all existing packages. 8496 // 8497 // We also do this *before* we perform dexopt on this package, so that 8498 // we can avoid redundant dexopts, and also to make sure we've got the 8499 // code and package path correct. 8500 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8501 pkg, true /* boot complete */); 8502 } 8503 8504 if (mFactoryTest && pkg.requestedPermissions.contains( 8505 android.Manifest.permission.FACTORY_TEST)) { 8506 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8507 } 8508 8509 ArrayList<PackageParser.Package> clientLibPkgs = null; 8510 8511 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8512 if (nonMutatedPs != null) { 8513 synchronized (mPackages) { 8514 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8515 } 8516 } 8517 return pkg; 8518 } 8519 8520 // Only privileged apps and updated privileged apps can add child packages. 8521 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8522 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8523 throw new PackageManagerException("Only privileged apps and updated " 8524 + "privileged apps can add child packages. Ignoring package " 8525 + pkg.packageName); 8526 } 8527 final int childCount = pkg.childPackages.size(); 8528 for (int i = 0; i < childCount; i++) { 8529 PackageParser.Package childPkg = pkg.childPackages.get(i); 8530 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8531 childPkg.packageName)) { 8532 throw new PackageManagerException("Cannot override a child package of " 8533 + "another disabled system app. Ignoring package " + pkg.packageName); 8534 } 8535 } 8536 } 8537 8538 // writer 8539 synchronized (mPackages) { 8540 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8541 // Only system apps can add new shared libraries. 8542 if (pkg.libraryNames != null) { 8543 for (int i=0; i<pkg.libraryNames.size(); i++) { 8544 String name = pkg.libraryNames.get(i); 8545 boolean allowed = false; 8546 if (pkg.isUpdatedSystemApp()) { 8547 // New library entries can only be added through the 8548 // system image. This is important to get rid of a lot 8549 // of nasty edge cases: for example if we allowed a non- 8550 // system update of the app to add a library, then uninstalling 8551 // the update would make the library go away, and assumptions 8552 // we made such as through app install filtering would now 8553 // have allowed apps on the device which aren't compatible 8554 // with it. Better to just have the restriction here, be 8555 // conservative, and create many fewer cases that can negatively 8556 // impact the user experience. 8557 final PackageSetting sysPs = mSettings 8558 .getDisabledSystemPkgLPr(pkg.packageName); 8559 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8560 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8561 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8562 allowed = true; 8563 break; 8564 } 8565 } 8566 } 8567 } else { 8568 allowed = true; 8569 } 8570 if (allowed) { 8571 if (!mSharedLibraries.containsKey(name)) { 8572 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8573 } else if (!name.equals(pkg.packageName)) { 8574 Slog.w(TAG, "Package " + pkg.packageName + " library " 8575 + name + " already exists; skipping"); 8576 } 8577 } else { 8578 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8579 + name + " that is not declared on system image; skipping"); 8580 } 8581 } 8582 if ((scanFlags & SCAN_BOOTING) == 0) { 8583 // If we are not booting, we need to update any applications 8584 // that are clients of our shared library. If we are booting, 8585 // this will all be done once the scan is complete. 8586 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8587 } 8588 } 8589 } 8590 } 8591 8592 if ((scanFlags & SCAN_BOOTING) != 0) { 8593 // No apps can run during boot scan, so they don't need to be frozen 8594 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8595 // Caller asked to not kill app, so it's probably not frozen 8596 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8597 // Caller asked us to ignore frozen check for some reason; they 8598 // probably didn't know the package name 8599 } else { 8600 // We're doing major surgery on this package, so it better be frozen 8601 // right now to keep it from launching 8602 checkPackageFrozen(pkgName); 8603 } 8604 8605 // Also need to kill any apps that are dependent on the library. 8606 if (clientLibPkgs != null) { 8607 for (int i=0; i<clientLibPkgs.size(); i++) { 8608 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8609 killApplication(clientPkg.applicationInfo.packageName, 8610 clientPkg.applicationInfo.uid, "update lib"); 8611 } 8612 } 8613 8614 // Make sure we're not adding any bogus keyset info 8615 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8616 ksms.assertScannedPackageValid(pkg); 8617 8618 // writer 8619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8620 8621 boolean createIdmapFailed = false; 8622 synchronized (mPackages) { 8623 // We don't expect installation to fail beyond this point 8624 8625 if (pkgSetting.pkg != null) { 8626 // Note that |user| might be null during the initial boot scan. If a codePath 8627 // for an app has changed during a boot scan, it's due to an app update that's 8628 // part of the system partition and marker changes must be applied to all users. 8629 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8630 (user != null) ? user : UserHandle.ALL); 8631 } 8632 8633 // Add the new setting to mSettings 8634 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8635 // Add the new setting to mPackages 8636 mPackages.put(pkg.applicationInfo.packageName, pkg); 8637 // Make sure we don't accidentally delete its data. 8638 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8639 while (iter.hasNext()) { 8640 PackageCleanItem item = iter.next(); 8641 if (pkgName.equals(item.packageName)) { 8642 iter.remove(); 8643 } 8644 } 8645 8646 // Take care of first install / last update times. 8647 if (currentTime != 0) { 8648 if (pkgSetting.firstInstallTime == 0) { 8649 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8650 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8651 pkgSetting.lastUpdateTime = currentTime; 8652 } 8653 } else if (pkgSetting.firstInstallTime == 0) { 8654 // We need *something*. Take time time stamp of the file. 8655 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8656 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8657 if (scanFileTime != pkgSetting.timeStamp) { 8658 // A package on the system image has changed; consider this 8659 // to be an update. 8660 pkgSetting.lastUpdateTime = scanFileTime; 8661 } 8662 } 8663 8664 // Add the package's KeySets to the global KeySetManagerService 8665 ksms.addScannedPackageLPw(pkg); 8666 8667 int N = pkg.providers.size(); 8668 StringBuilder r = null; 8669 int i; 8670 for (i=0; i<N; i++) { 8671 PackageParser.Provider p = pkg.providers.get(i); 8672 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8673 p.info.processName, pkg.applicationInfo.uid); 8674 mProviders.addProvider(p); 8675 p.syncable = p.info.isSyncable; 8676 if (p.info.authority != null) { 8677 String names[] = p.info.authority.split(";"); 8678 p.info.authority = null; 8679 for (int j = 0; j < names.length; j++) { 8680 if (j == 1 && p.syncable) { 8681 // We only want the first authority for a provider to possibly be 8682 // syncable, so if we already added this provider using a different 8683 // authority clear the syncable flag. We copy the provider before 8684 // changing it because the mProviders object contains a reference 8685 // to a provider that we don't want to change. 8686 // Only do this for the second authority since the resulting provider 8687 // object can be the same for all future authorities for this provider. 8688 p = new PackageParser.Provider(p); 8689 p.syncable = false; 8690 } 8691 if (!mProvidersByAuthority.containsKey(names[j])) { 8692 mProvidersByAuthority.put(names[j], p); 8693 if (p.info.authority == null) { 8694 p.info.authority = names[j]; 8695 } else { 8696 p.info.authority = p.info.authority + ";" + names[j]; 8697 } 8698 if (DEBUG_PACKAGE_SCANNING) { 8699 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8700 Log.d(TAG, "Registered content provider: " + names[j] 8701 + ", className = " + p.info.name + ", isSyncable = " 8702 + p.info.isSyncable); 8703 } 8704 } else { 8705 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8706 Slog.w(TAG, "Skipping provider name " + names[j] + 8707 " (in package " + pkg.applicationInfo.packageName + 8708 "): name already used by " 8709 + ((other != null && other.getComponentName() != null) 8710 ? other.getComponentName().getPackageName() : "?")); 8711 } 8712 } 8713 } 8714 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8715 if (r == null) { 8716 r = new StringBuilder(256); 8717 } else { 8718 r.append(' '); 8719 } 8720 r.append(p.info.name); 8721 } 8722 } 8723 if (r != null) { 8724 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8725 } 8726 8727 N = pkg.services.size(); 8728 r = null; 8729 for (i=0; i<N; i++) { 8730 PackageParser.Service s = pkg.services.get(i); 8731 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8732 s.info.processName, pkg.applicationInfo.uid); 8733 mServices.addService(s); 8734 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8735 if (r == null) { 8736 r = new StringBuilder(256); 8737 } else { 8738 r.append(' '); 8739 } 8740 r.append(s.info.name); 8741 } 8742 } 8743 if (r != null) { 8744 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8745 } 8746 8747 N = pkg.receivers.size(); 8748 r = null; 8749 for (i=0; i<N; i++) { 8750 PackageParser.Activity a = pkg.receivers.get(i); 8751 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8752 a.info.processName, pkg.applicationInfo.uid); 8753 mReceivers.addActivity(a, "receiver"); 8754 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8755 if (r == null) { 8756 r = new StringBuilder(256); 8757 } else { 8758 r.append(' '); 8759 } 8760 r.append(a.info.name); 8761 } 8762 } 8763 if (r != null) { 8764 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8765 } 8766 8767 N = pkg.activities.size(); 8768 r = null; 8769 for (i=0; i<N; i++) { 8770 PackageParser.Activity a = pkg.activities.get(i); 8771 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8772 a.info.processName, pkg.applicationInfo.uid); 8773 mActivities.addActivity(a, "activity"); 8774 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8775 if (r == null) { 8776 r = new StringBuilder(256); 8777 } else { 8778 r.append(' '); 8779 } 8780 r.append(a.info.name); 8781 } 8782 } 8783 if (r != null) { 8784 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8785 } 8786 8787 N = pkg.permissionGroups.size(); 8788 r = null; 8789 for (i=0; i<N; i++) { 8790 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8791 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8792 if (cur == null) { 8793 mPermissionGroups.put(pg.info.name, pg); 8794 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8795 if (r == null) { 8796 r = new StringBuilder(256); 8797 } else { 8798 r.append(' '); 8799 } 8800 r.append(pg.info.name); 8801 } 8802 } else { 8803 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8804 + pg.info.packageName + " ignored: original from " 8805 + cur.info.packageName); 8806 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8807 if (r == null) { 8808 r = new StringBuilder(256); 8809 } else { 8810 r.append(' '); 8811 } 8812 r.append("DUP:"); 8813 r.append(pg.info.name); 8814 } 8815 } 8816 } 8817 if (r != null) { 8818 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8819 } 8820 8821 N = pkg.permissions.size(); 8822 r = null; 8823 for (i=0; i<N; i++) { 8824 PackageParser.Permission p = pkg.permissions.get(i); 8825 8826 // Assume by default that we did not install this permission into the system. 8827 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8828 8829 // Now that permission groups have a special meaning, we ignore permission 8830 // groups for legacy apps to prevent unexpected behavior. In particular, 8831 // permissions for one app being granted to someone just becase they happen 8832 // to be in a group defined by another app (before this had no implications). 8833 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8834 p.group = mPermissionGroups.get(p.info.group); 8835 // Warn for a permission in an unknown group. 8836 if (p.info.group != null && p.group == null) { 8837 Slog.w(TAG, "Permission " + p.info.name + " from package " 8838 + p.info.packageName + " in an unknown group " + p.info.group); 8839 } 8840 } 8841 8842 ArrayMap<String, BasePermission> permissionMap = 8843 p.tree ? mSettings.mPermissionTrees 8844 : mSettings.mPermissions; 8845 BasePermission bp = permissionMap.get(p.info.name); 8846 8847 // Allow system apps to redefine non-system permissions 8848 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8849 final boolean currentOwnerIsSystem = (bp.perm != null 8850 && isSystemApp(bp.perm.owner)); 8851 if (isSystemApp(p.owner)) { 8852 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8853 // It's a built-in permission and no owner, take ownership now 8854 bp.packageSetting = pkgSetting; 8855 bp.perm = p; 8856 bp.uid = pkg.applicationInfo.uid; 8857 bp.sourcePackage = p.info.packageName; 8858 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8859 } else if (!currentOwnerIsSystem) { 8860 String msg = "New decl " + p.owner + " of permission " 8861 + p.info.name + " is system; overriding " + bp.sourcePackage; 8862 reportSettingsProblem(Log.WARN, msg); 8863 bp = null; 8864 } 8865 } 8866 } 8867 8868 if (bp == null) { 8869 bp = new BasePermission(p.info.name, p.info.packageName, 8870 BasePermission.TYPE_NORMAL); 8871 permissionMap.put(p.info.name, bp); 8872 } 8873 8874 if (bp.perm == null) { 8875 if (bp.sourcePackage == null 8876 || bp.sourcePackage.equals(p.info.packageName)) { 8877 BasePermission tree = findPermissionTreeLP(p.info.name); 8878 if (tree == null 8879 || tree.sourcePackage.equals(p.info.packageName)) { 8880 bp.packageSetting = pkgSetting; 8881 bp.perm = p; 8882 bp.uid = pkg.applicationInfo.uid; 8883 bp.sourcePackage = p.info.packageName; 8884 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8885 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8886 if (r == null) { 8887 r = new StringBuilder(256); 8888 } else { 8889 r.append(' '); 8890 } 8891 r.append(p.info.name); 8892 } 8893 } else { 8894 Slog.w(TAG, "Permission " + p.info.name + " from package " 8895 + p.info.packageName + " ignored: base tree " 8896 + tree.name + " is from package " 8897 + tree.sourcePackage); 8898 } 8899 } else { 8900 Slog.w(TAG, "Permission " + p.info.name + " from package " 8901 + p.info.packageName + " ignored: original from " 8902 + bp.sourcePackage); 8903 } 8904 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8905 if (r == null) { 8906 r = new StringBuilder(256); 8907 } else { 8908 r.append(' '); 8909 } 8910 r.append("DUP:"); 8911 r.append(p.info.name); 8912 } 8913 if (bp.perm == p) { 8914 bp.protectionLevel = p.info.protectionLevel; 8915 } 8916 } 8917 8918 if (r != null) { 8919 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8920 } 8921 8922 N = pkg.instrumentation.size(); 8923 r = null; 8924 for (i=0; i<N; i++) { 8925 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8926 a.info.packageName = pkg.applicationInfo.packageName; 8927 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8928 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8929 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8930 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8931 a.info.dataDir = pkg.applicationInfo.dataDir; 8932 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8933 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8934 8935 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8936 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8937 mInstrumentation.put(a.getComponentName(), a); 8938 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8939 if (r == null) { 8940 r = new StringBuilder(256); 8941 } else { 8942 r.append(' '); 8943 } 8944 r.append(a.info.name); 8945 } 8946 } 8947 if (r != null) { 8948 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8949 } 8950 8951 if (pkg.protectedBroadcasts != null) { 8952 N = pkg.protectedBroadcasts.size(); 8953 for (i=0; i<N; i++) { 8954 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8955 } 8956 } 8957 8958 pkgSetting.setTimeStamp(scanFileTime); 8959 8960 // Create idmap files for pairs of (packages, overlay packages). 8961 // Note: "android", ie framework-res.apk, is handled by native layers. 8962 if (pkg.mOverlayTarget != null) { 8963 // This is an overlay package. 8964 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8965 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8966 mOverlays.put(pkg.mOverlayTarget, 8967 new ArrayMap<String, PackageParser.Package>()); 8968 } 8969 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8970 map.put(pkg.packageName, pkg); 8971 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8972 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8973 createIdmapFailed = true; 8974 } 8975 } 8976 } else if (mOverlays.containsKey(pkg.packageName) && 8977 !pkg.packageName.equals("android")) { 8978 // This is a regular package, with one or more known overlay packages. 8979 createIdmapsForPackageLI(pkg); 8980 } 8981 } 8982 8983 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8984 8985 if (createIdmapFailed) { 8986 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8987 "scanPackageLI failed to createIdmap"); 8988 } 8989 return pkg; 8990 } 8991 8992 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8993 PackageParser.Package update, UserHandle user) { 8994 if (existing.applicationInfo == null || update.applicationInfo == null) { 8995 // This isn't due to an app installation. 8996 return; 8997 } 8998 8999 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9000 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9001 9002 // The codePath hasn't changed, so there's nothing for us to do. 9003 if (Objects.equals(oldCodePath, newCodePath)) { 9004 return; 9005 } 9006 9007 File canonicalNewCodePath; 9008 try { 9009 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9010 } catch (IOException e) { 9011 Slog.w(TAG, "Failed to get canonical path.", e); 9012 return; 9013 } 9014 9015 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9016 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9017 // that the last component of the path (i.e, the name) doesn't need canonicalization 9018 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9019 // but may change in the future. Hopefully this function won't exist at that point. 9020 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9021 oldCodePath.getName()); 9022 9023 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9024 // with "@". 9025 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9026 if (!oldMarkerPrefix.endsWith("@")) { 9027 oldMarkerPrefix += "@"; 9028 } 9029 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9030 if (!newMarkerPrefix.endsWith("@")) { 9031 newMarkerPrefix += "@"; 9032 } 9033 9034 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9035 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9036 for (String updatedPath : updatedPaths) { 9037 String updatedPathName = new File(updatedPath).getName(); 9038 markerSuffixes.add(updatedPathName.replace('/', '@')); 9039 } 9040 9041 for (int userId : resolveUserIds(user.getIdentifier())) { 9042 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9043 9044 for (String markerSuffix : markerSuffixes) { 9045 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9046 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9047 if (oldForeignUseMark.exists()) { 9048 try { 9049 Os.rename(oldForeignUseMark.getAbsolutePath(), 9050 newForeignUseMark.getAbsolutePath()); 9051 } catch (ErrnoException e) { 9052 Slog.w(TAG, "Failed to rename foreign use marker", e); 9053 oldForeignUseMark.delete(); 9054 } 9055 } 9056 } 9057 } 9058 } 9059 9060 /** 9061 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9062 * is derived purely on the basis of the contents of {@code scanFile} and 9063 * {@code cpuAbiOverride}. 9064 * 9065 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9066 */ 9067 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9068 String cpuAbiOverride, boolean extractLibs) 9069 throws PackageManagerException { 9070 // TODO: We can probably be smarter about this stuff. For installed apps, 9071 // we can calculate this information at install time once and for all. For 9072 // system apps, we can probably assume that this information doesn't change 9073 // after the first boot scan. As things stand, we do lots of unnecessary work. 9074 9075 // Give ourselves some initial paths; we'll come back for another 9076 // pass once we've determined ABI below. 9077 setNativeLibraryPaths(pkg); 9078 9079 // We would never need to extract libs for forward-locked and external packages, 9080 // since the container service will do it for us. We shouldn't attempt to 9081 // extract libs from system app when it was not updated. 9082 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9083 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9084 extractLibs = false; 9085 } 9086 9087 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9088 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9089 9090 NativeLibraryHelper.Handle handle = null; 9091 try { 9092 handle = NativeLibraryHelper.Handle.create(pkg); 9093 // TODO(multiArch): This can be null for apps that didn't go through the 9094 // usual installation process. We can calculate it again, like we 9095 // do during install time. 9096 // 9097 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9098 // unnecessary. 9099 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9100 9101 // Null out the abis so that they can be recalculated. 9102 pkg.applicationInfo.primaryCpuAbi = null; 9103 pkg.applicationInfo.secondaryCpuAbi = null; 9104 if (isMultiArch(pkg.applicationInfo)) { 9105 // Warn if we've set an abiOverride for multi-lib packages.. 9106 // By definition, we need to copy both 32 and 64 bit libraries for 9107 // such packages. 9108 if (pkg.cpuAbiOverride != null 9109 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9110 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9111 } 9112 9113 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9114 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9115 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9116 if (extractLibs) { 9117 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9118 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9119 useIsaSpecificSubdirs); 9120 } else { 9121 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9122 } 9123 } 9124 9125 maybeThrowExceptionForMultiArchCopy( 9126 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9127 9128 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9129 if (extractLibs) { 9130 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9131 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9132 useIsaSpecificSubdirs); 9133 } else { 9134 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9135 } 9136 } 9137 9138 maybeThrowExceptionForMultiArchCopy( 9139 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9140 9141 if (abi64 >= 0) { 9142 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9143 } 9144 9145 if (abi32 >= 0) { 9146 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9147 if (abi64 >= 0) { 9148 if (pkg.use32bitAbi) { 9149 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9150 pkg.applicationInfo.primaryCpuAbi = abi; 9151 } else { 9152 pkg.applicationInfo.secondaryCpuAbi = abi; 9153 } 9154 } else { 9155 pkg.applicationInfo.primaryCpuAbi = abi; 9156 } 9157 } 9158 9159 } else { 9160 String[] abiList = (cpuAbiOverride != null) ? 9161 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9162 9163 // Enable gross and lame hacks for apps that are built with old 9164 // SDK tools. We must scan their APKs for renderscript bitcode and 9165 // not launch them if it's present. Don't bother checking on devices 9166 // that don't have 64 bit support. 9167 boolean needsRenderScriptOverride = false; 9168 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9169 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9170 abiList = Build.SUPPORTED_32_BIT_ABIS; 9171 needsRenderScriptOverride = true; 9172 } 9173 9174 final int copyRet; 9175 if (extractLibs) { 9176 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9177 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9178 } else { 9179 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9180 } 9181 9182 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9183 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9184 "Error unpackaging native libs for app, errorCode=" + copyRet); 9185 } 9186 9187 if (copyRet >= 0) { 9188 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9189 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9190 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9191 } else if (needsRenderScriptOverride) { 9192 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9193 } 9194 } 9195 } catch (IOException ioe) { 9196 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9197 } finally { 9198 IoUtils.closeQuietly(handle); 9199 } 9200 9201 // Now that we've calculated the ABIs and determined if it's an internal app, 9202 // we will go ahead and populate the nativeLibraryPath. 9203 setNativeLibraryPaths(pkg); 9204 } 9205 9206 /** 9207 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9208 * i.e, so that all packages can be run inside a single process if required. 9209 * 9210 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9211 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9212 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9213 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9214 * updating a package that belongs to a shared user. 9215 * 9216 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9217 * adds unnecessary complexity. 9218 */ 9219 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9220 PackageParser.Package scannedPackage, boolean bootComplete) { 9221 String requiredInstructionSet = null; 9222 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9223 requiredInstructionSet = VMRuntime.getInstructionSet( 9224 scannedPackage.applicationInfo.primaryCpuAbi); 9225 } 9226 9227 PackageSetting requirer = null; 9228 for (PackageSetting ps : packagesForUser) { 9229 // If packagesForUser contains scannedPackage, we skip it. This will happen 9230 // when scannedPackage is an update of an existing package. Without this check, 9231 // we will never be able to change the ABI of any package belonging to a shared 9232 // user, even if it's compatible with other packages. 9233 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9234 if (ps.primaryCpuAbiString == null) { 9235 continue; 9236 } 9237 9238 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9239 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9240 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9241 // this but there's not much we can do. 9242 String errorMessage = "Instruction set mismatch, " 9243 + ((requirer == null) ? "[caller]" : requirer) 9244 + " requires " + requiredInstructionSet + " whereas " + ps 9245 + " requires " + instructionSet; 9246 Slog.w(TAG, errorMessage); 9247 } 9248 9249 if (requiredInstructionSet == null) { 9250 requiredInstructionSet = instructionSet; 9251 requirer = ps; 9252 } 9253 } 9254 } 9255 9256 if (requiredInstructionSet != null) { 9257 String adjustedAbi; 9258 if (requirer != null) { 9259 // requirer != null implies that either scannedPackage was null or that scannedPackage 9260 // did not require an ABI, in which case we have to adjust scannedPackage to match 9261 // the ABI of the set (which is the same as requirer's ABI) 9262 adjustedAbi = requirer.primaryCpuAbiString; 9263 if (scannedPackage != null) { 9264 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9265 } 9266 } else { 9267 // requirer == null implies that we're updating all ABIs in the set to 9268 // match scannedPackage. 9269 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9270 } 9271 9272 for (PackageSetting ps : packagesForUser) { 9273 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9274 if (ps.primaryCpuAbiString != null) { 9275 continue; 9276 } 9277 9278 ps.primaryCpuAbiString = adjustedAbi; 9279 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9280 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9281 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9282 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9283 + " (requirer=" 9284 + (requirer == null ? "null" : requirer.pkg.packageName) 9285 + ", scannedPackage=" 9286 + (scannedPackage != null ? scannedPackage.packageName : "null") 9287 + ")"); 9288 try { 9289 mInstaller.rmdex(ps.codePathString, 9290 getDexCodeInstructionSet(getPreferredInstructionSet())); 9291 } catch (InstallerException ignored) { 9292 } 9293 } 9294 } 9295 } 9296 } 9297 } 9298 9299 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9300 synchronized (mPackages) { 9301 mResolverReplaced = true; 9302 // Set up information for custom user intent resolution activity. 9303 mResolveActivity.applicationInfo = pkg.applicationInfo; 9304 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9305 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9306 mResolveActivity.processName = pkg.applicationInfo.packageName; 9307 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9308 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9309 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9310 mResolveActivity.theme = 0; 9311 mResolveActivity.exported = true; 9312 mResolveActivity.enabled = true; 9313 mResolveInfo.activityInfo = mResolveActivity; 9314 mResolveInfo.priority = 0; 9315 mResolveInfo.preferredOrder = 0; 9316 mResolveInfo.match = 0; 9317 mResolveComponentName = mCustomResolverComponentName; 9318 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9319 mResolveComponentName); 9320 } 9321 } 9322 9323 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9324 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9325 9326 // Set up information for ephemeral installer activity 9327 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9328 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9329 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9330 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9331 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9332 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9333 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9334 mEphemeralInstallerActivity.theme = 0; 9335 mEphemeralInstallerActivity.exported = true; 9336 mEphemeralInstallerActivity.enabled = true; 9337 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9338 mEphemeralInstallerInfo.priority = 0; 9339 mEphemeralInstallerInfo.preferredOrder = 0; 9340 mEphemeralInstallerInfo.match = 0; 9341 9342 if (DEBUG_EPHEMERAL) { 9343 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9344 } 9345 } 9346 9347 private static String calculateBundledApkRoot(final String codePathString) { 9348 final File codePath = new File(codePathString); 9349 final File codeRoot; 9350 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9351 codeRoot = Environment.getRootDirectory(); 9352 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9353 codeRoot = Environment.getOemDirectory(); 9354 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9355 codeRoot = Environment.getVendorDirectory(); 9356 } else { 9357 // Unrecognized code path; take its top real segment as the apk root: 9358 // e.g. /something/app/blah.apk => /something 9359 try { 9360 File f = codePath.getCanonicalFile(); 9361 File parent = f.getParentFile(); // non-null because codePath is a file 9362 File tmp; 9363 while ((tmp = parent.getParentFile()) != null) { 9364 f = parent; 9365 parent = tmp; 9366 } 9367 codeRoot = f; 9368 Slog.w(TAG, "Unrecognized code path " 9369 + codePath + " - using " + codeRoot); 9370 } catch (IOException e) { 9371 // Can't canonicalize the code path -- shenanigans? 9372 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9373 return Environment.getRootDirectory().getPath(); 9374 } 9375 } 9376 return codeRoot.getPath(); 9377 } 9378 9379 /** 9380 * Derive and set the location of native libraries for the given package, 9381 * which varies depending on where and how the package was installed. 9382 */ 9383 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9384 final ApplicationInfo info = pkg.applicationInfo; 9385 final String codePath = pkg.codePath; 9386 final File codeFile = new File(codePath); 9387 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9388 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9389 9390 info.nativeLibraryRootDir = null; 9391 info.nativeLibraryRootRequiresIsa = false; 9392 info.nativeLibraryDir = null; 9393 info.secondaryNativeLibraryDir = null; 9394 9395 if (isApkFile(codeFile)) { 9396 // Monolithic install 9397 if (bundledApp) { 9398 // If "/system/lib64/apkname" exists, assume that is the per-package 9399 // native library directory to use; otherwise use "/system/lib/apkname". 9400 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9401 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9402 getPrimaryInstructionSet(info)); 9403 9404 // This is a bundled system app so choose the path based on the ABI. 9405 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9406 // is just the default path. 9407 final String apkName = deriveCodePathName(codePath); 9408 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9409 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9410 apkName).getAbsolutePath(); 9411 9412 if (info.secondaryCpuAbi != null) { 9413 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9414 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9415 secondaryLibDir, apkName).getAbsolutePath(); 9416 } 9417 } else if (asecApp) { 9418 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9419 .getAbsolutePath(); 9420 } else { 9421 final String apkName = deriveCodePathName(codePath); 9422 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9423 .getAbsolutePath(); 9424 } 9425 9426 info.nativeLibraryRootRequiresIsa = false; 9427 info.nativeLibraryDir = info.nativeLibraryRootDir; 9428 } else { 9429 // Cluster install 9430 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9431 info.nativeLibraryRootRequiresIsa = true; 9432 9433 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9434 getPrimaryInstructionSet(info)).getAbsolutePath(); 9435 9436 if (info.secondaryCpuAbi != null) { 9437 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9438 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9439 } 9440 } 9441 } 9442 9443 /** 9444 * Calculate the abis and roots for a bundled app. These can uniquely 9445 * be determined from the contents of the system partition, i.e whether 9446 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9447 * of this information, and instead assume that the system was built 9448 * sensibly. 9449 */ 9450 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9451 PackageSetting pkgSetting) { 9452 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9453 9454 // If "/system/lib64/apkname" exists, assume that is the per-package 9455 // native library directory to use; otherwise use "/system/lib/apkname". 9456 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9457 setBundledAppAbi(pkg, apkRoot, apkName); 9458 // pkgSetting might be null during rescan following uninstall of updates 9459 // to a bundled app, so accommodate that possibility. The settings in 9460 // that case will be established later from the parsed package. 9461 // 9462 // If the settings aren't null, sync them up with what we've just derived. 9463 // note that apkRoot isn't stored in the package settings. 9464 if (pkgSetting != null) { 9465 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9466 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9467 } 9468 } 9469 9470 /** 9471 * Deduces the ABI of a bundled app and sets the relevant fields on the 9472 * parsed pkg object. 9473 * 9474 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9475 * under which system libraries are installed. 9476 * @param apkName the name of the installed package. 9477 */ 9478 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9479 final File codeFile = new File(pkg.codePath); 9480 9481 final boolean has64BitLibs; 9482 final boolean has32BitLibs; 9483 if (isApkFile(codeFile)) { 9484 // Monolithic install 9485 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9486 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9487 } else { 9488 // Cluster install 9489 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9490 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9491 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9492 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9493 has64BitLibs = (new File(rootDir, isa)).exists(); 9494 } else { 9495 has64BitLibs = false; 9496 } 9497 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9498 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9499 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9500 has32BitLibs = (new File(rootDir, isa)).exists(); 9501 } else { 9502 has32BitLibs = false; 9503 } 9504 } 9505 9506 if (has64BitLibs && !has32BitLibs) { 9507 // The package has 64 bit libs, but not 32 bit libs. Its primary 9508 // ABI should be 64 bit. We can safely assume here that the bundled 9509 // native libraries correspond to the most preferred ABI in the list. 9510 9511 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9512 pkg.applicationInfo.secondaryCpuAbi = null; 9513 } else if (has32BitLibs && !has64BitLibs) { 9514 // The package has 32 bit libs but not 64 bit libs. Its primary 9515 // ABI should be 32 bit. 9516 9517 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9518 pkg.applicationInfo.secondaryCpuAbi = null; 9519 } else if (has32BitLibs && has64BitLibs) { 9520 // The application has both 64 and 32 bit bundled libraries. We check 9521 // here that the app declares multiArch support, and warn if it doesn't. 9522 // 9523 // We will be lenient here and record both ABIs. The primary will be the 9524 // ABI that's higher on the list, i.e, a device that's configured to prefer 9525 // 64 bit apps will see a 64 bit primary ABI, 9526 9527 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9528 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9529 } 9530 9531 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9532 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9533 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9534 } else { 9535 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9536 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9537 } 9538 } else { 9539 pkg.applicationInfo.primaryCpuAbi = null; 9540 pkg.applicationInfo.secondaryCpuAbi = null; 9541 } 9542 } 9543 9544 private void killApplication(String pkgName, int appId, String reason) { 9545 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9546 } 9547 9548 private void killApplication(String pkgName, int appId, int userId, String reason) { 9549 // Request the ActivityManager to kill the process(only for existing packages) 9550 // so that we do not end up in a confused state while the user is still using the older 9551 // version of the application while the new one gets installed. 9552 final long token = Binder.clearCallingIdentity(); 9553 try { 9554 IActivityManager am = ActivityManagerNative.getDefault(); 9555 if (am != null) { 9556 try { 9557 am.killApplication(pkgName, appId, userId, reason); 9558 } catch (RemoteException e) { 9559 } 9560 } 9561 } finally { 9562 Binder.restoreCallingIdentity(token); 9563 } 9564 } 9565 9566 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9567 // Remove the parent package setting 9568 PackageSetting ps = (PackageSetting) pkg.mExtras; 9569 if (ps != null) { 9570 removePackageLI(ps, chatty); 9571 } 9572 // Remove the child package setting 9573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9574 for (int i = 0; i < childCount; i++) { 9575 PackageParser.Package childPkg = pkg.childPackages.get(i); 9576 ps = (PackageSetting) childPkg.mExtras; 9577 if (ps != null) { 9578 removePackageLI(ps, chatty); 9579 } 9580 } 9581 } 9582 9583 void removePackageLI(PackageSetting ps, boolean chatty) { 9584 if (DEBUG_INSTALL) { 9585 if (chatty) 9586 Log.d(TAG, "Removing package " + ps.name); 9587 } 9588 9589 // writer 9590 synchronized (mPackages) { 9591 mPackages.remove(ps.name); 9592 final PackageParser.Package pkg = ps.pkg; 9593 if (pkg != null) { 9594 cleanPackageDataStructuresLILPw(pkg, chatty); 9595 } 9596 } 9597 } 9598 9599 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9600 if (DEBUG_INSTALL) { 9601 if (chatty) 9602 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9603 } 9604 9605 // writer 9606 synchronized (mPackages) { 9607 // Remove the parent package 9608 mPackages.remove(pkg.applicationInfo.packageName); 9609 cleanPackageDataStructuresLILPw(pkg, chatty); 9610 9611 // Remove the child packages 9612 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9613 for (int i = 0; i < childCount; i++) { 9614 PackageParser.Package childPkg = pkg.childPackages.get(i); 9615 mPackages.remove(childPkg.applicationInfo.packageName); 9616 cleanPackageDataStructuresLILPw(childPkg, chatty); 9617 } 9618 } 9619 } 9620 9621 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9622 int N = pkg.providers.size(); 9623 StringBuilder r = null; 9624 int i; 9625 for (i=0; i<N; i++) { 9626 PackageParser.Provider p = pkg.providers.get(i); 9627 mProviders.removeProvider(p); 9628 if (p.info.authority == null) { 9629 9630 /* There was another ContentProvider with this authority when 9631 * this app was installed so this authority is null, 9632 * Ignore it as we don't have to unregister the provider. 9633 */ 9634 continue; 9635 } 9636 String names[] = p.info.authority.split(";"); 9637 for (int j = 0; j < names.length; j++) { 9638 if (mProvidersByAuthority.get(names[j]) == p) { 9639 mProvidersByAuthority.remove(names[j]); 9640 if (DEBUG_REMOVE) { 9641 if (chatty) 9642 Log.d(TAG, "Unregistered content provider: " + names[j] 9643 + ", className = " + p.info.name + ", isSyncable = " 9644 + p.info.isSyncable); 9645 } 9646 } 9647 } 9648 if (DEBUG_REMOVE && chatty) { 9649 if (r == null) { 9650 r = new StringBuilder(256); 9651 } else { 9652 r.append(' '); 9653 } 9654 r.append(p.info.name); 9655 } 9656 } 9657 if (r != null) { 9658 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9659 } 9660 9661 N = pkg.services.size(); 9662 r = null; 9663 for (i=0; i<N; i++) { 9664 PackageParser.Service s = pkg.services.get(i); 9665 mServices.removeService(s); 9666 if (chatty) { 9667 if (r == null) { 9668 r = new StringBuilder(256); 9669 } else { 9670 r.append(' '); 9671 } 9672 r.append(s.info.name); 9673 } 9674 } 9675 if (r != null) { 9676 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9677 } 9678 9679 N = pkg.receivers.size(); 9680 r = null; 9681 for (i=0; i<N; i++) { 9682 PackageParser.Activity a = pkg.receivers.get(i); 9683 mReceivers.removeActivity(a, "receiver"); 9684 if (DEBUG_REMOVE && chatty) { 9685 if (r == null) { 9686 r = new StringBuilder(256); 9687 } else { 9688 r.append(' '); 9689 } 9690 r.append(a.info.name); 9691 } 9692 } 9693 if (r != null) { 9694 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9695 } 9696 9697 N = pkg.activities.size(); 9698 r = null; 9699 for (i=0; i<N; i++) { 9700 PackageParser.Activity a = pkg.activities.get(i); 9701 mActivities.removeActivity(a, "activity"); 9702 if (DEBUG_REMOVE && chatty) { 9703 if (r == null) { 9704 r = new StringBuilder(256); 9705 } else { 9706 r.append(' '); 9707 } 9708 r.append(a.info.name); 9709 } 9710 } 9711 if (r != null) { 9712 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9713 } 9714 9715 N = pkg.permissions.size(); 9716 r = null; 9717 for (i=0; i<N; i++) { 9718 PackageParser.Permission p = pkg.permissions.get(i); 9719 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9720 if (bp == null) { 9721 bp = mSettings.mPermissionTrees.get(p.info.name); 9722 } 9723 if (bp != null && bp.perm == p) { 9724 bp.perm = null; 9725 if (DEBUG_REMOVE && chatty) { 9726 if (r == null) { 9727 r = new StringBuilder(256); 9728 } else { 9729 r.append(' '); 9730 } 9731 r.append(p.info.name); 9732 } 9733 } 9734 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9735 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9736 if (appOpPkgs != null) { 9737 appOpPkgs.remove(pkg.packageName); 9738 } 9739 } 9740 } 9741 if (r != null) { 9742 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9743 } 9744 9745 N = pkg.requestedPermissions.size(); 9746 r = null; 9747 for (i=0; i<N; i++) { 9748 String perm = pkg.requestedPermissions.get(i); 9749 BasePermission bp = mSettings.mPermissions.get(perm); 9750 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9751 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9752 if (appOpPkgs != null) { 9753 appOpPkgs.remove(pkg.packageName); 9754 if (appOpPkgs.isEmpty()) { 9755 mAppOpPermissionPackages.remove(perm); 9756 } 9757 } 9758 } 9759 } 9760 if (r != null) { 9761 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9762 } 9763 9764 N = pkg.instrumentation.size(); 9765 r = null; 9766 for (i=0; i<N; i++) { 9767 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9768 mInstrumentation.remove(a.getComponentName()); 9769 if (DEBUG_REMOVE && chatty) { 9770 if (r == null) { 9771 r = new StringBuilder(256); 9772 } else { 9773 r.append(' '); 9774 } 9775 r.append(a.info.name); 9776 } 9777 } 9778 if (r != null) { 9779 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9780 } 9781 9782 r = null; 9783 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9784 // Only system apps can hold shared libraries. 9785 if (pkg.libraryNames != null) { 9786 for (i=0; i<pkg.libraryNames.size(); i++) { 9787 String name = pkg.libraryNames.get(i); 9788 SharedLibraryEntry cur = mSharedLibraries.get(name); 9789 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9790 mSharedLibraries.remove(name); 9791 if (DEBUG_REMOVE && chatty) { 9792 if (r == null) { 9793 r = new StringBuilder(256); 9794 } else { 9795 r.append(' '); 9796 } 9797 r.append(name); 9798 } 9799 } 9800 } 9801 } 9802 } 9803 if (r != null) { 9804 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9805 } 9806 } 9807 9808 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9809 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9810 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9811 return true; 9812 } 9813 } 9814 return false; 9815 } 9816 9817 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9818 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9819 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9820 9821 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9822 // Update the parent permissions 9823 updatePermissionsLPw(pkg.packageName, pkg, flags); 9824 // Update the child permissions 9825 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9826 for (int i = 0; i < childCount; i++) { 9827 PackageParser.Package childPkg = pkg.childPackages.get(i); 9828 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9829 } 9830 } 9831 9832 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9833 int flags) { 9834 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9835 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9836 } 9837 9838 private void updatePermissionsLPw(String changingPkg, 9839 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9840 // Make sure there are no dangling permission trees. 9841 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9842 while (it.hasNext()) { 9843 final BasePermission bp = it.next(); 9844 if (bp.packageSetting == null) { 9845 // We may not yet have parsed the package, so just see if 9846 // we still know about its settings. 9847 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9848 } 9849 if (bp.packageSetting == null) { 9850 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9851 + " from package " + bp.sourcePackage); 9852 it.remove(); 9853 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9854 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9855 Slog.i(TAG, "Removing old permission tree: " + bp.name 9856 + " from package " + bp.sourcePackage); 9857 flags |= UPDATE_PERMISSIONS_ALL; 9858 it.remove(); 9859 } 9860 } 9861 } 9862 9863 // Make sure all dynamic permissions have been assigned to a package, 9864 // and make sure there are no dangling permissions. 9865 it = mSettings.mPermissions.values().iterator(); 9866 while (it.hasNext()) { 9867 final BasePermission bp = it.next(); 9868 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9869 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9870 + bp.name + " pkg=" + bp.sourcePackage 9871 + " info=" + bp.pendingInfo); 9872 if (bp.packageSetting == null && bp.pendingInfo != null) { 9873 final BasePermission tree = findPermissionTreeLP(bp.name); 9874 if (tree != null && tree.perm != null) { 9875 bp.packageSetting = tree.packageSetting; 9876 bp.perm = new PackageParser.Permission(tree.perm.owner, 9877 new PermissionInfo(bp.pendingInfo)); 9878 bp.perm.info.packageName = tree.perm.info.packageName; 9879 bp.perm.info.name = bp.name; 9880 bp.uid = tree.uid; 9881 } 9882 } 9883 } 9884 if (bp.packageSetting == null) { 9885 // We may not yet have parsed the package, so just see if 9886 // we still know about its settings. 9887 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9888 } 9889 if (bp.packageSetting == null) { 9890 Slog.w(TAG, "Removing dangling permission: " + bp.name 9891 + " from package " + bp.sourcePackage); 9892 it.remove(); 9893 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9894 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9895 Slog.i(TAG, "Removing old permission: " + bp.name 9896 + " from package " + bp.sourcePackage); 9897 flags |= UPDATE_PERMISSIONS_ALL; 9898 it.remove(); 9899 } 9900 } 9901 } 9902 9903 // Now update the permissions for all packages, in particular 9904 // replace the granted permissions of the system packages. 9905 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9906 for (PackageParser.Package pkg : mPackages.values()) { 9907 if (pkg != pkgInfo) { 9908 // Only replace for packages on requested volume 9909 final String volumeUuid = getVolumeUuidForPackage(pkg); 9910 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9911 && Objects.equals(replaceVolumeUuid, volumeUuid); 9912 grantPermissionsLPw(pkg, replace, changingPkg); 9913 } 9914 } 9915 } 9916 9917 if (pkgInfo != null) { 9918 // Only replace for packages on requested volume 9919 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9920 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9921 && Objects.equals(replaceVolumeUuid, volumeUuid); 9922 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9923 } 9924 } 9925 9926 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9927 String packageOfInterest) { 9928 // IMPORTANT: There are two types of permissions: install and runtime. 9929 // Install time permissions are granted when the app is installed to 9930 // all device users and users added in the future. Runtime permissions 9931 // are granted at runtime explicitly to specific users. Normal and signature 9932 // protected permissions are install time permissions. Dangerous permissions 9933 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9934 // otherwise they are runtime permissions. This function does not manage 9935 // runtime permissions except for the case an app targeting Lollipop MR1 9936 // being upgraded to target a newer SDK, in which case dangerous permissions 9937 // are transformed from install time to runtime ones. 9938 9939 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9940 if (ps == null) { 9941 return; 9942 } 9943 9944 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9945 9946 PermissionsState permissionsState = ps.getPermissionsState(); 9947 PermissionsState origPermissions = permissionsState; 9948 9949 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9950 9951 boolean runtimePermissionsRevoked = false; 9952 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9953 9954 boolean changedInstallPermission = false; 9955 9956 if (replace) { 9957 ps.installPermissionsFixed = false; 9958 if (!ps.isSharedUser()) { 9959 origPermissions = new PermissionsState(permissionsState); 9960 permissionsState.reset(); 9961 } else { 9962 // We need to know only about runtime permission changes since the 9963 // calling code always writes the install permissions state but 9964 // the runtime ones are written only if changed. The only cases of 9965 // changed runtime permissions here are promotion of an install to 9966 // runtime and revocation of a runtime from a shared user. 9967 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9968 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9969 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9970 runtimePermissionsRevoked = true; 9971 } 9972 } 9973 } 9974 9975 permissionsState.setGlobalGids(mGlobalGids); 9976 9977 final int N = pkg.requestedPermissions.size(); 9978 for (int i=0; i<N; i++) { 9979 final String name = pkg.requestedPermissions.get(i); 9980 final BasePermission bp = mSettings.mPermissions.get(name); 9981 9982 if (DEBUG_INSTALL) { 9983 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9984 } 9985 9986 if (bp == null || bp.packageSetting == null) { 9987 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9988 Slog.w(TAG, "Unknown permission " + name 9989 + " in package " + pkg.packageName); 9990 } 9991 continue; 9992 } 9993 9994 final String perm = bp.name; 9995 boolean allowedSig = false; 9996 int grant = GRANT_DENIED; 9997 9998 // Keep track of app op permissions. 9999 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10000 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10001 if (pkgs == null) { 10002 pkgs = new ArraySet<>(); 10003 mAppOpPermissionPackages.put(bp.name, pkgs); 10004 } 10005 pkgs.add(pkg.packageName); 10006 } 10007 10008 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10009 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10010 >= Build.VERSION_CODES.M; 10011 switch (level) { 10012 case PermissionInfo.PROTECTION_NORMAL: { 10013 // For all apps normal permissions are install time ones. 10014 grant = GRANT_INSTALL; 10015 } break; 10016 10017 case PermissionInfo.PROTECTION_DANGEROUS: { 10018 // If a permission review is required for legacy apps we represent 10019 // their permissions as always granted runtime ones since we need 10020 // to keep the review required permission flag per user while an 10021 // install permission's state is shared across all users. 10022 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10023 // For legacy apps dangerous permissions are install time ones. 10024 grant = GRANT_INSTALL; 10025 } else if (origPermissions.hasInstallPermission(bp.name)) { 10026 // For legacy apps that became modern, install becomes runtime. 10027 grant = GRANT_UPGRADE; 10028 } else if (mPromoteSystemApps 10029 && isSystemApp(ps) 10030 && mExistingSystemPackages.contains(ps.name)) { 10031 // For legacy system apps, install becomes runtime. 10032 // We cannot check hasInstallPermission() for system apps since those 10033 // permissions were granted implicitly and not persisted pre-M. 10034 grant = GRANT_UPGRADE; 10035 } else { 10036 // For modern apps keep runtime permissions unchanged. 10037 grant = GRANT_RUNTIME; 10038 } 10039 } break; 10040 10041 case PermissionInfo.PROTECTION_SIGNATURE: { 10042 // For all apps signature permissions are install time ones. 10043 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10044 if (allowedSig) { 10045 grant = GRANT_INSTALL; 10046 } 10047 } break; 10048 } 10049 10050 if (DEBUG_INSTALL) { 10051 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10052 } 10053 10054 if (grant != GRANT_DENIED) { 10055 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10056 // If this is an existing, non-system package, then 10057 // we can't add any new permissions to it. 10058 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10059 // Except... if this is a permission that was added 10060 // to the platform (note: need to only do this when 10061 // updating the platform). 10062 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10063 grant = GRANT_DENIED; 10064 } 10065 } 10066 } 10067 10068 switch (grant) { 10069 case GRANT_INSTALL: { 10070 // Revoke this as runtime permission to handle the case of 10071 // a runtime permission being downgraded to an install one. 10072 // Also in permission review mode we keep dangerous permissions 10073 // for legacy apps 10074 for (int userId : UserManagerService.getInstance().getUserIds()) { 10075 if (origPermissions.getRuntimePermissionState( 10076 bp.name, userId) != null) { 10077 // Revoke the runtime permission and clear the flags. 10078 origPermissions.revokeRuntimePermission(bp, userId); 10079 origPermissions.updatePermissionFlags(bp, userId, 10080 PackageManager.MASK_PERMISSION_FLAGS, 0); 10081 // If we revoked a permission permission, we have to write. 10082 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10083 changedRuntimePermissionUserIds, userId); 10084 } 10085 } 10086 // Grant an install permission. 10087 if (permissionsState.grantInstallPermission(bp) != 10088 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10089 changedInstallPermission = true; 10090 } 10091 } break; 10092 10093 case GRANT_RUNTIME: { 10094 // Grant previously granted runtime permissions. 10095 for (int userId : UserManagerService.getInstance().getUserIds()) { 10096 PermissionState permissionState = origPermissions 10097 .getRuntimePermissionState(bp.name, userId); 10098 int flags = permissionState != null 10099 ? permissionState.getFlags() : 0; 10100 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10101 if (permissionsState.grantRuntimePermission(bp, userId) == 10102 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10103 // If we cannot put the permission as it was, we have to write. 10104 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10105 changedRuntimePermissionUserIds, userId); 10106 } 10107 // If the app supports runtime permissions no need for a review. 10108 if (Build.PERMISSIONS_REVIEW_REQUIRED 10109 && appSupportsRuntimePermissions 10110 && (flags & PackageManager 10111 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10112 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10113 // Since we changed the flags, we have to write. 10114 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10115 changedRuntimePermissionUserIds, userId); 10116 } 10117 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10118 && !appSupportsRuntimePermissions) { 10119 // For legacy apps that need a permission review, every new 10120 // runtime permission is granted but it is pending a review. 10121 // We also need to review only platform defined runtime 10122 // permissions as these are the only ones the platform knows 10123 // how to disable the API to simulate revocation as legacy 10124 // apps don't expect to run with revoked permissions. 10125 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10126 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10127 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10128 // We changed the flags, hence have to write. 10129 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10130 changedRuntimePermissionUserIds, userId); 10131 } 10132 } 10133 if (permissionsState.grantRuntimePermission(bp, userId) 10134 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10135 // We changed the permission, hence have to write. 10136 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10137 changedRuntimePermissionUserIds, userId); 10138 } 10139 } 10140 // Propagate the permission flags. 10141 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10142 } 10143 } break; 10144 10145 case GRANT_UPGRADE: { 10146 // Grant runtime permissions for a previously held install permission. 10147 PermissionState permissionState = origPermissions 10148 .getInstallPermissionState(bp.name); 10149 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10150 10151 if (origPermissions.revokeInstallPermission(bp) 10152 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10153 // We will be transferring the permission flags, so clear them. 10154 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10155 PackageManager.MASK_PERMISSION_FLAGS, 0); 10156 changedInstallPermission = true; 10157 } 10158 10159 // If the permission is not to be promoted to runtime we ignore it and 10160 // also its other flags as they are not applicable to install permissions. 10161 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10162 for (int userId : currentUserIds) { 10163 if (permissionsState.grantRuntimePermission(bp, userId) != 10164 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10165 // Transfer the permission flags. 10166 permissionsState.updatePermissionFlags(bp, userId, 10167 flags, flags); 10168 // If we granted the permission, we have to write. 10169 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10170 changedRuntimePermissionUserIds, userId); 10171 } 10172 } 10173 } 10174 } break; 10175 10176 default: { 10177 if (packageOfInterest == null 10178 || packageOfInterest.equals(pkg.packageName)) { 10179 Slog.w(TAG, "Not granting permission " + perm 10180 + " to package " + pkg.packageName 10181 + " because it was previously installed without"); 10182 } 10183 } break; 10184 } 10185 } else { 10186 if (permissionsState.revokeInstallPermission(bp) != 10187 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10188 // Also drop the permission flags. 10189 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10190 PackageManager.MASK_PERMISSION_FLAGS, 0); 10191 changedInstallPermission = true; 10192 Slog.i(TAG, "Un-granting permission " + perm 10193 + " from package " + pkg.packageName 10194 + " (protectionLevel=" + bp.protectionLevel 10195 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10196 + ")"); 10197 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10198 // Don't print warning for app op permissions, since it is fine for them 10199 // not to be granted, there is a UI for the user to decide. 10200 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10201 Slog.w(TAG, "Not granting permission " + perm 10202 + " to package " + pkg.packageName 10203 + " (protectionLevel=" + bp.protectionLevel 10204 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10205 + ")"); 10206 } 10207 } 10208 } 10209 } 10210 10211 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10212 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10213 // This is the first that we have heard about this package, so the 10214 // permissions we have now selected are fixed until explicitly 10215 // changed. 10216 ps.installPermissionsFixed = true; 10217 } 10218 10219 // Persist the runtime permissions state for users with changes. If permissions 10220 // were revoked because no app in the shared user declares them we have to 10221 // write synchronously to avoid losing runtime permissions state. 10222 for (int userId : changedRuntimePermissionUserIds) { 10223 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10224 } 10225 10226 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10227 } 10228 10229 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10230 boolean allowed = false; 10231 final int NP = PackageParser.NEW_PERMISSIONS.length; 10232 for (int ip=0; ip<NP; ip++) { 10233 final PackageParser.NewPermissionInfo npi 10234 = PackageParser.NEW_PERMISSIONS[ip]; 10235 if (npi.name.equals(perm) 10236 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10237 allowed = true; 10238 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10239 + pkg.packageName); 10240 break; 10241 } 10242 } 10243 return allowed; 10244 } 10245 10246 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10247 BasePermission bp, PermissionsState origPermissions) { 10248 boolean allowed; 10249 allowed = (compareSignatures( 10250 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10251 == PackageManager.SIGNATURE_MATCH) 10252 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10253 == PackageManager.SIGNATURE_MATCH); 10254 if (!allowed && (bp.protectionLevel 10255 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10256 if (isSystemApp(pkg)) { 10257 // For updated system applications, a system permission 10258 // is granted only if it had been defined by the original application. 10259 if (pkg.isUpdatedSystemApp()) { 10260 final PackageSetting sysPs = mSettings 10261 .getDisabledSystemPkgLPr(pkg.packageName); 10262 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10263 // If the original was granted this permission, we take 10264 // that grant decision as read and propagate it to the 10265 // update. 10266 if (sysPs.isPrivileged()) { 10267 allowed = true; 10268 } 10269 } else { 10270 // The system apk may have been updated with an older 10271 // version of the one on the data partition, but which 10272 // granted a new system permission that it didn't have 10273 // before. In this case we do want to allow the app to 10274 // now get the new permission if the ancestral apk is 10275 // privileged to get it. 10276 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10277 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10278 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10279 allowed = true; 10280 break; 10281 } 10282 } 10283 } 10284 // Also if a privileged parent package on the system image or any of 10285 // its children requested a privileged permission, the updated child 10286 // packages can also get the permission. 10287 if (pkg.parentPackage != null) { 10288 final PackageSetting disabledSysParentPs = mSettings 10289 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10290 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10291 && disabledSysParentPs.isPrivileged()) { 10292 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10293 allowed = true; 10294 } else if (disabledSysParentPs.pkg.childPackages != null) { 10295 final int count = disabledSysParentPs.pkg.childPackages.size(); 10296 for (int i = 0; i < count; i++) { 10297 PackageParser.Package disabledSysChildPkg = 10298 disabledSysParentPs.pkg.childPackages.get(i); 10299 if (isPackageRequestingPermission(disabledSysChildPkg, 10300 perm)) { 10301 allowed = true; 10302 break; 10303 } 10304 } 10305 } 10306 } 10307 } 10308 } 10309 } else { 10310 allowed = isPrivilegedApp(pkg); 10311 } 10312 } 10313 } 10314 if (!allowed) { 10315 if (!allowed && (bp.protectionLevel 10316 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10317 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10318 // If this was a previously normal/dangerous permission that got moved 10319 // to a system permission as part of the runtime permission redesign, then 10320 // we still want to blindly grant it to old apps. 10321 allowed = true; 10322 } 10323 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10324 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10325 // If this permission is to be granted to the system installer and 10326 // this app is an installer, then it gets the permission. 10327 allowed = true; 10328 } 10329 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10330 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10331 // If this permission is to be granted to the system verifier and 10332 // this app is a verifier, then it gets the permission. 10333 allowed = true; 10334 } 10335 if (!allowed && (bp.protectionLevel 10336 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10337 && isSystemApp(pkg)) { 10338 // Any pre-installed system app is allowed to get this permission. 10339 allowed = true; 10340 } 10341 if (!allowed && (bp.protectionLevel 10342 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10343 // For development permissions, a development permission 10344 // is granted only if it was already granted. 10345 allowed = origPermissions.hasInstallPermission(perm); 10346 } 10347 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10348 && pkg.packageName.equals(mSetupWizardPackage)) { 10349 // If this permission is to be granted to the system setup wizard and 10350 // this app is a setup wizard, then it gets the permission. 10351 allowed = true; 10352 } 10353 } 10354 return allowed; 10355 } 10356 10357 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10358 final int permCount = pkg.requestedPermissions.size(); 10359 for (int j = 0; j < permCount; j++) { 10360 String requestedPermission = pkg.requestedPermissions.get(j); 10361 if (permission.equals(requestedPermission)) { 10362 return true; 10363 } 10364 } 10365 return false; 10366 } 10367 10368 final class ActivityIntentResolver 10369 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10370 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10371 boolean defaultOnly, int userId) { 10372 if (!sUserManager.exists(userId)) return null; 10373 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10374 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10375 } 10376 10377 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10378 int userId) { 10379 if (!sUserManager.exists(userId)) return null; 10380 mFlags = flags; 10381 return super.queryIntent(intent, resolvedType, 10382 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10383 } 10384 10385 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10386 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10387 if (!sUserManager.exists(userId)) return null; 10388 if (packageActivities == null) { 10389 return null; 10390 } 10391 mFlags = flags; 10392 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10393 final int N = packageActivities.size(); 10394 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10395 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10396 10397 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10398 for (int i = 0; i < N; ++i) { 10399 intentFilters = packageActivities.get(i).intents; 10400 if (intentFilters != null && intentFilters.size() > 0) { 10401 PackageParser.ActivityIntentInfo[] array = 10402 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10403 intentFilters.toArray(array); 10404 listCut.add(array); 10405 } 10406 } 10407 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10408 } 10409 10410 /** 10411 * Finds a privileged activity that matches the specified activity names. 10412 */ 10413 private PackageParser.Activity findMatchingActivity( 10414 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10415 for (PackageParser.Activity sysActivity : activityList) { 10416 if (sysActivity.info.name.equals(activityInfo.name)) { 10417 return sysActivity; 10418 } 10419 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10420 return sysActivity; 10421 } 10422 if (sysActivity.info.targetActivity != null) { 10423 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10424 return sysActivity; 10425 } 10426 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10427 return sysActivity; 10428 } 10429 } 10430 } 10431 return null; 10432 } 10433 10434 public class IterGenerator<E> { 10435 public Iterator<E> generate(ActivityIntentInfo info) { 10436 return null; 10437 } 10438 } 10439 10440 public class ActionIterGenerator extends IterGenerator<String> { 10441 @Override 10442 public Iterator<String> generate(ActivityIntentInfo info) { 10443 return info.actionsIterator(); 10444 } 10445 } 10446 10447 public class CategoriesIterGenerator extends IterGenerator<String> { 10448 @Override 10449 public Iterator<String> generate(ActivityIntentInfo info) { 10450 return info.categoriesIterator(); 10451 } 10452 } 10453 10454 public class SchemesIterGenerator extends IterGenerator<String> { 10455 @Override 10456 public Iterator<String> generate(ActivityIntentInfo info) { 10457 return info.schemesIterator(); 10458 } 10459 } 10460 10461 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10462 @Override 10463 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10464 return info.authoritiesIterator(); 10465 } 10466 } 10467 10468 /** 10469 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10470 * MODIFIED. Do not pass in a list that should not be changed. 10471 */ 10472 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10473 IterGenerator<T> generator, Iterator<T> searchIterator) { 10474 // loop through the set of actions; every one must be found in the intent filter 10475 while (searchIterator.hasNext()) { 10476 // we must have at least one filter in the list to consider a match 10477 if (intentList.size() == 0) { 10478 break; 10479 } 10480 10481 final T searchAction = searchIterator.next(); 10482 10483 // loop through the set of intent filters 10484 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10485 while (intentIter.hasNext()) { 10486 final ActivityIntentInfo intentInfo = intentIter.next(); 10487 boolean selectionFound = false; 10488 10489 // loop through the intent filter's selection criteria; at least one 10490 // of them must match the searched criteria 10491 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10492 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10493 final T intentSelection = intentSelectionIter.next(); 10494 if (intentSelection != null && intentSelection.equals(searchAction)) { 10495 selectionFound = true; 10496 break; 10497 } 10498 } 10499 10500 // the selection criteria wasn't found in this filter's set; this filter 10501 // is not a potential match 10502 if (!selectionFound) { 10503 intentIter.remove(); 10504 } 10505 } 10506 } 10507 } 10508 10509 private boolean isProtectedAction(ActivityIntentInfo filter) { 10510 final Iterator<String> actionsIter = filter.actionsIterator(); 10511 while (actionsIter != null && actionsIter.hasNext()) { 10512 final String filterAction = actionsIter.next(); 10513 if (PROTECTED_ACTIONS.contains(filterAction)) { 10514 return true; 10515 } 10516 } 10517 return false; 10518 } 10519 10520 /** 10521 * Adjusts the priority of the given intent filter according to policy. 10522 * <p> 10523 * <ul> 10524 * <li>The priority for non privileged applications is capped to '0'</li> 10525 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10526 * <li>The priority for unbundled updates to privileged applications is capped to the 10527 * priority defined on the system partition</li> 10528 * </ul> 10529 * <p> 10530 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10531 * allowed to obtain any priority on any action. 10532 */ 10533 private void adjustPriority( 10534 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10535 // nothing to do; priority is fine as-is 10536 if (intent.getPriority() <= 0) { 10537 return; 10538 } 10539 10540 final ActivityInfo activityInfo = intent.activity.info; 10541 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10542 10543 final boolean privilegedApp = 10544 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10545 if (!privilegedApp) { 10546 // non-privileged applications can never define a priority >0 10547 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10548 + " package: " + applicationInfo.packageName 10549 + " activity: " + intent.activity.className 10550 + " origPrio: " + intent.getPriority()); 10551 intent.setPriority(0); 10552 return; 10553 } 10554 10555 if (systemActivities == null) { 10556 // the system package is not disabled; we're parsing the system partition 10557 if (isProtectedAction(intent)) { 10558 if (mDeferProtectedFilters) { 10559 // We can't deal with these just yet. No component should ever obtain a 10560 // >0 priority for a protected actions, with ONE exception -- the setup 10561 // wizard. The setup wizard, however, cannot be known until we're able to 10562 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10563 // until all intent filters have been processed. Chicken, meet egg. 10564 // Let the filter temporarily have a high priority and rectify the 10565 // priorities after all system packages have been scanned. 10566 mProtectedFilters.add(intent); 10567 if (DEBUG_FILTERS) { 10568 Slog.i(TAG, "Protected action; save for later;" 10569 + " package: " + applicationInfo.packageName 10570 + " activity: " + intent.activity.className 10571 + " origPrio: " + intent.getPriority()); 10572 } 10573 return; 10574 } else { 10575 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10576 Slog.i(TAG, "No setup wizard;" 10577 + " All protected intents capped to priority 0"); 10578 } 10579 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10580 if (DEBUG_FILTERS) { 10581 Slog.i(TAG, "Found setup wizard;" 10582 + " allow priority " + intent.getPriority() + ";" 10583 + " package: " + intent.activity.info.packageName 10584 + " activity: " + intent.activity.className 10585 + " priority: " + intent.getPriority()); 10586 } 10587 // setup wizard gets whatever it wants 10588 return; 10589 } 10590 Slog.w(TAG, "Protected action; cap priority to 0;" 10591 + " package: " + intent.activity.info.packageName 10592 + " activity: " + intent.activity.className 10593 + " origPrio: " + intent.getPriority()); 10594 intent.setPriority(0); 10595 return; 10596 } 10597 } 10598 // privileged apps on the system image get whatever priority they request 10599 return; 10600 } 10601 10602 // privileged app unbundled update ... try to find the same activity 10603 final PackageParser.Activity foundActivity = 10604 findMatchingActivity(systemActivities, activityInfo); 10605 if (foundActivity == null) { 10606 // this is a new activity; it cannot obtain >0 priority 10607 if (DEBUG_FILTERS) { 10608 Slog.i(TAG, "New activity; cap priority to 0;" 10609 + " package: " + applicationInfo.packageName 10610 + " activity: " + intent.activity.className 10611 + " origPrio: " + intent.getPriority()); 10612 } 10613 intent.setPriority(0); 10614 return; 10615 } 10616 10617 // found activity, now check for filter equivalence 10618 10619 // a shallow copy is enough; we modify the list, not its contents 10620 final List<ActivityIntentInfo> intentListCopy = 10621 new ArrayList<>(foundActivity.intents); 10622 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10623 10624 // find matching action subsets 10625 final Iterator<String> actionsIterator = intent.actionsIterator(); 10626 if (actionsIterator != null) { 10627 getIntentListSubset( 10628 intentListCopy, new ActionIterGenerator(), actionsIterator); 10629 if (intentListCopy.size() == 0) { 10630 // no more intents to match; we're not equivalent 10631 if (DEBUG_FILTERS) { 10632 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10633 + " package: " + applicationInfo.packageName 10634 + " activity: " + intent.activity.className 10635 + " origPrio: " + intent.getPriority()); 10636 } 10637 intent.setPriority(0); 10638 return; 10639 } 10640 } 10641 10642 // find matching category subsets 10643 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10644 if (categoriesIterator != null) { 10645 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10646 categoriesIterator); 10647 if (intentListCopy.size() == 0) { 10648 // no more intents to match; we're not equivalent 10649 if (DEBUG_FILTERS) { 10650 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10651 + " package: " + applicationInfo.packageName 10652 + " activity: " + intent.activity.className 10653 + " origPrio: " + intent.getPriority()); 10654 } 10655 intent.setPriority(0); 10656 return; 10657 } 10658 } 10659 10660 // find matching schemes subsets 10661 final Iterator<String> schemesIterator = intent.schemesIterator(); 10662 if (schemesIterator != null) { 10663 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10664 schemesIterator); 10665 if (intentListCopy.size() == 0) { 10666 // no more intents to match; we're not equivalent 10667 if (DEBUG_FILTERS) { 10668 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10669 + " package: " + applicationInfo.packageName 10670 + " activity: " + intent.activity.className 10671 + " origPrio: " + intent.getPriority()); 10672 } 10673 intent.setPriority(0); 10674 return; 10675 } 10676 } 10677 10678 // find matching authorities subsets 10679 final Iterator<IntentFilter.AuthorityEntry> 10680 authoritiesIterator = intent.authoritiesIterator(); 10681 if (authoritiesIterator != null) { 10682 getIntentListSubset(intentListCopy, 10683 new AuthoritiesIterGenerator(), 10684 authoritiesIterator); 10685 if (intentListCopy.size() == 0) { 10686 // no more intents to match; we're not equivalent 10687 if (DEBUG_FILTERS) { 10688 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10689 + " package: " + applicationInfo.packageName 10690 + " activity: " + intent.activity.className 10691 + " origPrio: " + intent.getPriority()); 10692 } 10693 intent.setPriority(0); 10694 return; 10695 } 10696 } 10697 10698 // we found matching filter(s); app gets the max priority of all intents 10699 int cappedPriority = 0; 10700 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10701 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10702 } 10703 if (intent.getPriority() > cappedPriority) { 10704 if (DEBUG_FILTERS) { 10705 Slog.i(TAG, "Found matching filter(s);" 10706 + " cap priority to " + cappedPriority + ";" 10707 + " package: " + applicationInfo.packageName 10708 + " activity: " + intent.activity.className 10709 + " origPrio: " + intent.getPriority()); 10710 } 10711 intent.setPriority(cappedPriority); 10712 return; 10713 } 10714 // all this for nothing; the requested priority was <= what was on the system 10715 } 10716 10717 public final void addActivity(PackageParser.Activity a, String type) { 10718 mActivities.put(a.getComponentName(), a); 10719 if (DEBUG_SHOW_INFO) 10720 Log.v( 10721 TAG, " " + type + " " + 10722 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10723 if (DEBUG_SHOW_INFO) 10724 Log.v(TAG, " Class=" + a.info.name); 10725 final int NI = a.intents.size(); 10726 for (int j=0; j<NI; j++) { 10727 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10728 if ("activity".equals(type)) { 10729 final PackageSetting ps = 10730 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10731 final List<PackageParser.Activity> systemActivities = 10732 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10733 adjustPriority(systemActivities, intent); 10734 } 10735 if (DEBUG_SHOW_INFO) { 10736 Log.v(TAG, " IntentFilter:"); 10737 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10738 } 10739 if (!intent.debugCheck()) { 10740 Log.w(TAG, "==> For Activity " + a.info.name); 10741 } 10742 addFilter(intent); 10743 } 10744 } 10745 10746 public final void removeActivity(PackageParser.Activity a, String type) { 10747 mActivities.remove(a.getComponentName()); 10748 if (DEBUG_SHOW_INFO) { 10749 Log.v(TAG, " " + type + " " 10750 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10751 : a.info.name) + ":"); 10752 Log.v(TAG, " Class=" + a.info.name); 10753 } 10754 final int NI = a.intents.size(); 10755 for (int j=0; j<NI; j++) { 10756 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10757 if (DEBUG_SHOW_INFO) { 10758 Log.v(TAG, " IntentFilter:"); 10759 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10760 } 10761 removeFilter(intent); 10762 } 10763 } 10764 10765 @Override 10766 protected boolean allowFilterResult( 10767 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10768 ActivityInfo filterAi = filter.activity.info; 10769 for (int i=dest.size()-1; i>=0; i--) { 10770 ActivityInfo destAi = dest.get(i).activityInfo; 10771 if (destAi.name == filterAi.name 10772 && destAi.packageName == filterAi.packageName) { 10773 return false; 10774 } 10775 } 10776 return true; 10777 } 10778 10779 @Override 10780 protected ActivityIntentInfo[] newArray(int size) { 10781 return new ActivityIntentInfo[size]; 10782 } 10783 10784 @Override 10785 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10786 if (!sUserManager.exists(userId)) return true; 10787 PackageParser.Package p = filter.activity.owner; 10788 if (p != null) { 10789 PackageSetting ps = (PackageSetting)p.mExtras; 10790 if (ps != null) { 10791 // System apps are never considered stopped for purposes of 10792 // filtering, because there may be no way for the user to 10793 // actually re-launch them. 10794 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10795 && ps.getStopped(userId); 10796 } 10797 } 10798 return false; 10799 } 10800 10801 @Override 10802 protected boolean isPackageForFilter(String packageName, 10803 PackageParser.ActivityIntentInfo info) { 10804 return packageName.equals(info.activity.owner.packageName); 10805 } 10806 10807 @Override 10808 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10809 int match, int userId) { 10810 if (!sUserManager.exists(userId)) return null; 10811 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10812 return null; 10813 } 10814 final PackageParser.Activity activity = info.activity; 10815 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10816 if (ps == null) { 10817 return null; 10818 } 10819 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10820 ps.readUserState(userId), userId); 10821 if (ai == null) { 10822 return null; 10823 } 10824 final ResolveInfo res = new ResolveInfo(); 10825 res.activityInfo = ai; 10826 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10827 res.filter = info; 10828 } 10829 if (info != null) { 10830 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10831 } 10832 res.priority = info.getPriority(); 10833 res.preferredOrder = activity.owner.mPreferredOrder; 10834 //System.out.println("Result: " + res.activityInfo.className + 10835 // " = " + res.priority); 10836 res.match = match; 10837 res.isDefault = info.hasDefault; 10838 res.labelRes = info.labelRes; 10839 res.nonLocalizedLabel = info.nonLocalizedLabel; 10840 if (userNeedsBadging(userId)) { 10841 res.noResourceId = true; 10842 } else { 10843 res.icon = info.icon; 10844 } 10845 res.iconResourceId = info.icon; 10846 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10847 return res; 10848 } 10849 10850 @Override 10851 protected void sortResults(List<ResolveInfo> results) { 10852 Collections.sort(results, mResolvePrioritySorter); 10853 } 10854 10855 @Override 10856 protected void dumpFilter(PrintWriter out, String prefix, 10857 PackageParser.ActivityIntentInfo filter) { 10858 out.print(prefix); out.print( 10859 Integer.toHexString(System.identityHashCode(filter.activity))); 10860 out.print(' '); 10861 filter.activity.printComponentShortName(out); 10862 out.print(" filter "); 10863 out.println(Integer.toHexString(System.identityHashCode(filter))); 10864 } 10865 10866 @Override 10867 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10868 return filter.activity; 10869 } 10870 10871 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10872 PackageParser.Activity activity = (PackageParser.Activity)label; 10873 out.print(prefix); out.print( 10874 Integer.toHexString(System.identityHashCode(activity))); 10875 out.print(' '); 10876 activity.printComponentShortName(out); 10877 if (count > 1) { 10878 out.print(" ("); out.print(count); out.print(" filters)"); 10879 } 10880 out.println(); 10881 } 10882 10883 // Keys are String (activity class name), values are Activity. 10884 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10885 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10886 private int mFlags; 10887 } 10888 10889 private final class ServiceIntentResolver 10890 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10891 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10892 boolean defaultOnly, int userId) { 10893 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10894 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10895 } 10896 10897 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10898 int userId) { 10899 if (!sUserManager.exists(userId)) return null; 10900 mFlags = flags; 10901 return super.queryIntent(intent, resolvedType, 10902 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10903 } 10904 10905 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10906 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10907 if (!sUserManager.exists(userId)) return null; 10908 if (packageServices == null) { 10909 return null; 10910 } 10911 mFlags = flags; 10912 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10913 final int N = packageServices.size(); 10914 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10915 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10916 10917 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10918 for (int i = 0; i < N; ++i) { 10919 intentFilters = packageServices.get(i).intents; 10920 if (intentFilters != null && intentFilters.size() > 0) { 10921 PackageParser.ServiceIntentInfo[] array = 10922 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10923 intentFilters.toArray(array); 10924 listCut.add(array); 10925 } 10926 } 10927 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10928 } 10929 10930 public final void addService(PackageParser.Service s) { 10931 mServices.put(s.getComponentName(), s); 10932 if (DEBUG_SHOW_INFO) { 10933 Log.v(TAG, " " 10934 + (s.info.nonLocalizedLabel != null 10935 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10936 Log.v(TAG, " Class=" + s.info.name); 10937 } 10938 final int NI = s.intents.size(); 10939 int j; 10940 for (j=0; j<NI; j++) { 10941 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10942 if (DEBUG_SHOW_INFO) { 10943 Log.v(TAG, " IntentFilter:"); 10944 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10945 } 10946 if (!intent.debugCheck()) { 10947 Log.w(TAG, "==> For Service " + s.info.name); 10948 } 10949 addFilter(intent); 10950 } 10951 } 10952 10953 public final void removeService(PackageParser.Service s) { 10954 mServices.remove(s.getComponentName()); 10955 if (DEBUG_SHOW_INFO) { 10956 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10957 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10958 Log.v(TAG, " Class=" + s.info.name); 10959 } 10960 final int NI = s.intents.size(); 10961 int j; 10962 for (j=0; j<NI; j++) { 10963 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10964 if (DEBUG_SHOW_INFO) { 10965 Log.v(TAG, " IntentFilter:"); 10966 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10967 } 10968 removeFilter(intent); 10969 } 10970 } 10971 10972 @Override 10973 protected boolean allowFilterResult( 10974 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10975 ServiceInfo filterSi = filter.service.info; 10976 for (int i=dest.size()-1; i>=0; i--) { 10977 ServiceInfo destAi = dest.get(i).serviceInfo; 10978 if (destAi.name == filterSi.name 10979 && destAi.packageName == filterSi.packageName) { 10980 return false; 10981 } 10982 } 10983 return true; 10984 } 10985 10986 @Override 10987 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10988 return new PackageParser.ServiceIntentInfo[size]; 10989 } 10990 10991 @Override 10992 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10993 if (!sUserManager.exists(userId)) return true; 10994 PackageParser.Package p = filter.service.owner; 10995 if (p != null) { 10996 PackageSetting ps = (PackageSetting)p.mExtras; 10997 if (ps != null) { 10998 // System apps are never considered stopped for purposes of 10999 // filtering, because there may be no way for the user to 11000 // actually re-launch them. 11001 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11002 && ps.getStopped(userId); 11003 } 11004 } 11005 return false; 11006 } 11007 11008 @Override 11009 protected boolean isPackageForFilter(String packageName, 11010 PackageParser.ServiceIntentInfo info) { 11011 return packageName.equals(info.service.owner.packageName); 11012 } 11013 11014 @Override 11015 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11016 int match, int userId) { 11017 if (!sUserManager.exists(userId)) return null; 11018 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11019 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11020 return null; 11021 } 11022 final PackageParser.Service service = info.service; 11023 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11024 if (ps == null) { 11025 return null; 11026 } 11027 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11028 ps.readUserState(userId), userId); 11029 if (si == null) { 11030 return null; 11031 } 11032 final ResolveInfo res = new ResolveInfo(); 11033 res.serviceInfo = si; 11034 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11035 res.filter = filter; 11036 } 11037 res.priority = info.getPriority(); 11038 res.preferredOrder = service.owner.mPreferredOrder; 11039 res.match = match; 11040 res.isDefault = info.hasDefault; 11041 res.labelRes = info.labelRes; 11042 res.nonLocalizedLabel = info.nonLocalizedLabel; 11043 res.icon = info.icon; 11044 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11045 return res; 11046 } 11047 11048 @Override 11049 protected void sortResults(List<ResolveInfo> results) { 11050 Collections.sort(results, mResolvePrioritySorter); 11051 } 11052 11053 @Override 11054 protected void dumpFilter(PrintWriter out, String prefix, 11055 PackageParser.ServiceIntentInfo filter) { 11056 out.print(prefix); out.print( 11057 Integer.toHexString(System.identityHashCode(filter.service))); 11058 out.print(' '); 11059 filter.service.printComponentShortName(out); 11060 out.print(" filter "); 11061 out.println(Integer.toHexString(System.identityHashCode(filter))); 11062 } 11063 11064 @Override 11065 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11066 return filter.service; 11067 } 11068 11069 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11070 PackageParser.Service service = (PackageParser.Service)label; 11071 out.print(prefix); out.print( 11072 Integer.toHexString(System.identityHashCode(service))); 11073 out.print(' '); 11074 service.printComponentShortName(out); 11075 if (count > 1) { 11076 out.print(" ("); out.print(count); out.print(" filters)"); 11077 } 11078 out.println(); 11079 } 11080 11081// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11082// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11083// final List<ResolveInfo> retList = Lists.newArrayList(); 11084// while (i.hasNext()) { 11085// final ResolveInfo resolveInfo = (ResolveInfo) i; 11086// if (isEnabledLP(resolveInfo.serviceInfo)) { 11087// retList.add(resolveInfo); 11088// } 11089// } 11090// return retList; 11091// } 11092 11093 // Keys are String (activity class name), values are Activity. 11094 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11095 = new ArrayMap<ComponentName, PackageParser.Service>(); 11096 private int mFlags; 11097 }; 11098 11099 private final class ProviderIntentResolver 11100 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11101 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11102 boolean defaultOnly, int userId) { 11103 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11104 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11105 } 11106 11107 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11108 int userId) { 11109 if (!sUserManager.exists(userId)) 11110 return null; 11111 mFlags = flags; 11112 return super.queryIntent(intent, resolvedType, 11113 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11114 } 11115 11116 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11117 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11118 if (!sUserManager.exists(userId)) 11119 return null; 11120 if (packageProviders == null) { 11121 return null; 11122 } 11123 mFlags = flags; 11124 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11125 final int N = packageProviders.size(); 11126 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11127 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11128 11129 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11130 for (int i = 0; i < N; ++i) { 11131 intentFilters = packageProviders.get(i).intents; 11132 if (intentFilters != null && intentFilters.size() > 0) { 11133 PackageParser.ProviderIntentInfo[] array = 11134 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11135 intentFilters.toArray(array); 11136 listCut.add(array); 11137 } 11138 } 11139 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11140 } 11141 11142 public final void addProvider(PackageParser.Provider p) { 11143 if (mProviders.containsKey(p.getComponentName())) { 11144 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11145 return; 11146 } 11147 11148 mProviders.put(p.getComponentName(), p); 11149 if (DEBUG_SHOW_INFO) { 11150 Log.v(TAG, " " 11151 + (p.info.nonLocalizedLabel != null 11152 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11153 Log.v(TAG, " Class=" + p.info.name); 11154 } 11155 final int NI = p.intents.size(); 11156 int j; 11157 for (j = 0; j < NI; j++) { 11158 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11159 if (DEBUG_SHOW_INFO) { 11160 Log.v(TAG, " IntentFilter:"); 11161 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11162 } 11163 if (!intent.debugCheck()) { 11164 Log.w(TAG, "==> For Provider " + p.info.name); 11165 } 11166 addFilter(intent); 11167 } 11168 } 11169 11170 public final void removeProvider(PackageParser.Provider p) { 11171 mProviders.remove(p.getComponentName()); 11172 if (DEBUG_SHOW_INFO) { 11173 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11174 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11175 Log.v(TAG, " Class=" + p.info.name); 11176 } 11177 final int NI = p.intents.size(); 11178 int j; 11179 for (j = 0; j < NI; j++) { 11180 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11181 if (DEBUG_SHOW_INFO) { 11182 Log.v(TAG, " IntentFilter:"); 11183 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11184 } 11185 removeFilter(intent); 11186 } 11187 } 11188 11189 @Override 11190 protected boolean allowFilterResult( 11191 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11192 ProviderInfo filterPi = filter.provider.info; 11193 for (int i = dest.size() - 1; i >= 0; i--) { 11194 ProviderInfo destPi = dest.get(i).providerInfo; 11195 if (destPi.name == filterPi.name 11196 && destPi.packageName == filterPi.packageName) { 11197 return false; 11198 } 11199 } 11200 return true; 11201 } 11202 11203 @Override 11204 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11205 return new PackageParser.ProviderIntentInfo[size]; 11206 } 11207 11208 @Override 11209 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11210 if (!sUserManager.exists(userId)) 11211 return true; 11212 PackageParser.Package p = filter.provider.owner; 11213 if (p != null) { 11214 PackageSetting ps = (PackageSetting) p.mExtras; 11215 if (ps != null) { 11216 // System apps are never considered stopped for purposes of 11217 // filtering, because there may be no way for the user to 11218 // actually re-launch them. 11219 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11220 && ps.getStopped(userId); 11221 } 11222 } 11223 return false; 11224 } 11225 11226 @Override 11227 protected boolean isPackageForFilter(String packageName, 11228 PackageParser.ProviderIntentInfo info) { 11229 return packageName.equals(info.provider.owner.packageName); 11230 } 11231 11232 @Override 11233 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11234 int match, int userId) { 11235 if (!sUserManager.exists(userId)) 11236 return null; 11237 final PackageParser.ProviderIntentInfo info = filter; 11238 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11239 return null; 11240 } 11241 final PackageParser.Provider provider = info.provider; 11242 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11243 if (ps == null) { 11244 return null; 11245 } 11246 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11247 ps.readUserState(userId), userId); 11248 if (pi == null) { 11249 return null; 11250 } 11251 final ResolveInfo res = new ResolveInfo(); 11252 res.providerInfo = pi; 11253 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11254 res.filter = filter; 11255 } 11256 res.priority = info.getPriority(); 11257 res.preferredOrder = provider.owner.mPreferredOrder; 11258 res.match = match; 11259 res.isDefault = info.hasDefault; 11260 res.labelRes = info.labelRes; 11261 res.nonLocalizedLabel = info.nonLocalizedLabel; 11262 res.icon = info.icon; 11263 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11264 return res; 11265 } 11266 11267 @Override 11268 protected void sortResults(List<ResolveInfo> results) { 11269 Collections.sort(results, mResolvePrioritySorter); 11270 } 11271 11272 @Override 11273 protected void dumpFilter(PrintWriter out, String prefix, 11274 PackageParser.ProviderIntentInfo filter) { 11275 out.print(prefix); 11276 out.print( 11277 Integer.toHexString(System.identityHashCode(filter.provider))); 11278 out.print(' '); 11279 filter.provider.printComponentShortName(out); 11280 out.print(" filter "); 11281 out.println(Integer.toHexString(System.identityHashCode(filter))); 11282 } 11283 11284 @Override 11285 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11286 return filter.provider; 11287 } 11288 11289 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11290 PackageParser.Provider provider = (PackageParser.Provider)label; 11291 out.print(prefix); out.print( 11292 Integer.toHexString(System.identityHashCode(provider))); 11293 out.print(' '); 11294 provider.printComponentShortName(out); 11295 if (count > 1) { 11296 out.print(" ("); out.print(count); out.print(" filters)"); 11297 } 11298 out.println(); 11299 } 11300 11301 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11302 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11303 private int mFlags; 11304 } 11305 11306 private static final class EphemeralIntentResolver 11307 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11308 @Override 11309 protected EphemeralResolveIntentInfo[] newArray(int size) { 11310 return new EphemeralResolveIntentInfo[size]; 11311 } 11312 11313 @Override 11314 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11315 return true; 11316 } 11317 11318 @Override 11319 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11320 int userId) { 11321 if (!sUserManager.exists(userId)) { 11322 return null; 11323 } 11324 return info.getEphemeralResolveInfo(); 11325 } 11326 } 11327 11328 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11329 new Comparator<ResolveInfo>() { 11330 public int compare(ResolveInfo r1, ResolveInfo r2) { 11331 int v1 = r1.priority; 11332 int v2 = r2.priority; 11333 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11334 if (v1 != v2) { 11335 return (v1 > v2) ? -1 : 1; 11336 } 11337 v1 = r1.preferredOrder; 11338 v2 = r2.preferredOrder; 11339 if (v1 != v2) { 11340 return (v1 > v2) ? -1 : 1; 11341 } 11342 if (r1.isDefault != r2.isDefault) { 11343 return r1.isDefault ? -1 : 1; 11344 } 11345 v1 = r1.match; 11346 v2 = r2.match; 11347 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11348 if (v1 != v2) { 11349 return (v1 > v2) ? -1 : 1; 11350 } 11351 if (r1.system != r2.system) { 11352 return r1.system ? -1 : 1; 11353 } 11354 if (r1.activityInfo != null) { 11355 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11356 } 11357 if (r1.serviceInfo != null) { 11358 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11359 } 11360 if (r1.providerInfo != null) { 11361 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11362 } 11363 return 0; 11364 } 11365 }; 11366 11367 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11368 new Comparator<ProviderInfo>() { 11369 public int compare(ProviderInfo p1, ProviderInfo p2) { 11370 final int v1 = p1.initOrder; 11371 final int v2 = p2.initOrder; 11372 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11373 } 11374 }; 11375 11376 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11377 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11378 final int[] userIds) { 11379 mHandler.post(new Runnable() { 11380 @Override 11381 public void run() { 11382 try { 11383 final IActivityManager am = ActivityManagerNative.getDefault(); 11384 if (am == null) return; 11385 final int[] resolvedUserIds; 11386 if (userIds == null) { 11387 resolvedUserIds = am.getRunningUserIds(); 11388 } else { 11389 resolvedUserIds = userIds; 11390 } 11391 for (int id : resolvedUserIds) { 11392 final Intent intent = new Intent(action, 11393 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11394 if (extras != null) { 11395 intent.putExtras(extras); 11396 } 11397 if (targetPkg != null) { 11398 intent.setPackage(targetPkg); 11399 } 11400 // Modify the UID when posting to other users 11401 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11402 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11403 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11404 intent.putExtra(Intent.EXTRA_UID, uid); 11405 } 11406 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11407 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11408 if (DEBUG_BROADCASTS) { 11409 RuntimeException here = new RuntimeException("here"); 11410 here.fillInStackTrace(); 11411 Slog.d(TAG, "Sending to user " + id + ": " 11412 + intent.toShortString(false, true, false, false) 11413 + " " + intent.getExtras(), here); 11414 } 11415 am.broadcastIntent(null, intent, null, finishedReceiver, 11416 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11417 null, finishedReceiver != null, false, id); 11418 } 11419 } catch (RemoteException ex) { 11420 } 11421 } 11422 }); 11423 } 11424 11425 /** 11426 * Check if the external storage media is available. This is true if there 11427 * is a mounted external storage medium or if the external storage is 11428 * emulated. 11429 */ 11430 private boolean isExternalMediaAvailable() { 11431 return mMediaMounted || Environment.isExternalStorageEmulated(); 11432 } 11433 11434 @Override 11435 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11436 // writer 11437 synchronized (mPackages) { 11438 if (!isExternalMediaAvailable()) { 11439 // If the external storage is no longer mounted at this point, 11440 // the caller may not have been able to delete all of this 11441 // packages files and can not delete any more. Bail. 11442 return null; 11443 } 11444 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11445 if (lastPackage != null) { 11446 pkgs.remove(lastPackage); 11447 } 11448 if (pkgs.size() > 0) { 11449 return pkgs.get(0); 11450 } 11451 } 11452 return null; 11453 } 11454 11455 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11456 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11457 userId, andCode ? 1 : 0, packageName); 11458 if (mSystemReady) { 11459 msg.sendToTarget(); 11460 } else { 11461 if (mPostSystemReadyMessages == null) { 11462 mPostSystemReadyMessages = new ArrayList<>(); 11463 } 11464 mPostSystemReadyMessages.add(msg); 11465 } 11466 } 11467 11468 void startCleaningPackages() { 11469 // reader 11470 if (!isExternalMediaAvailable()) { 11471 return; 11472 } 11473 synchronized (mPackages) { 11474 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11475 return; 11476 } 11477 } 11478 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11479 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11480 IActivityManager am = ActivityManagerNative.getDefault(); 11481 if (am != null) { 11482 try { 11483 am.startService(null, intent, null, mContext.getOpPackageName(), 11484 UserHandle.USER_SYSTEM); 11485 } catch (RemoteException e) { 11486 } 11487 } 11488 } 11489 11490 @Override 11491 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11492 int installFlags, String installerPackageName, int userId) { 11493 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11494 11495 final int callingUid = Binder.getCallingUid(); 11496 enforceCrossUserPermission(callingUid, userId, 11497 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11498 11499 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11500 try { 11501 if (observer != null) { 11502 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11503 } 11504 } catch (RemoteException re) { 11505 } 11506 return; 11507 } 11508 11509 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11510 installFlags |= PackageManager.INSTALL_FROM_ADB; 11511 11512 } else { 11513 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11514 // about installerPackageName. 11515 11516 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11517 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11518 } 11519 11520 UserHandle user; 11521 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11522 user = UserHandle.ALL; 11523 } else { 11524 user = new UserHandle(userId); 11525 } 11526 11527 // Only system components can circumvent runtime permissions when installing. 11528 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11529 && mContext.checkCallingOrSelfPermission(Manifest.permission 11530 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11531 throw new SecurityException("You need the " 11532 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11533 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11534 } 11535 11536 final File originFile = new File(originPath); 11537 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11538 11539 final Message msg = mHandler.obtainMessage(INIT_COPY); 11540 final VerificationInfo verificationInfo = new VerificationInfo( 11541 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11542 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11543 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11544 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11545 null /*certificates*/); 11546 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11547 msg.obj = params; 11548 11549 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11550 System.identityHashCode(msg.obj)); 11551 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11552 System.identityHashCode(msg.obj)); 11553 11554 mHandler.sendMessage(msg); 11555 } 11556 11557 void installStage(String packageName, File stagedDir, String stagedCid, 11558 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11559 String installerPackageName, int installerUid, UserHandle user, 11560 Certificate[][] certificates) { 11561 if (DEBUG_EPHEMERAL) { 11562 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11563 Slog.d(TAG, "Ephemeral install of " + packageName); 11564 } 11565 } 11566 final VerificationInfo verificationInfo = new VerificationInfo( 11567 sessionParams.originatingUri, sessionParams.referrerUri, 11568 sessionParams.originatingUid, installerUid); 11569 11570 final OriginInfo origin; 11571 if (stagedDir != null) { 11572 origin = OriginInfo.fromStagedFile(stagedDir); 11573 } else { 11574 origin = OriginInfo.fromStagedContainer(stagedCid); 11575 } 11576 11577 final Message msg = mHandler.obtainMessage(INIT_COPY); 11578 final InstallParams params = new InstallParams(origin, null, observer, 11579 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11580 verificationInfo, user, sessionParams.abiOverride, 11581 sessionParams.grantedRuntimePermissions, certificates); 11582 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11583 msg.obj = params; 11584 11585 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11586 System.identityHashCode(msg.obj)); 11587 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11588 System.identityHashCode(msg.obj)); 11589 11590 mHandler.sendMessage(msg); 11591 } 11592 11593 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11594 int userId) { 11595 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11596 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11597 } 11598 11599 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11600 int appId, int userId) { 11601 Bundle extras = new Bundle(1); 11602 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11603 11604 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11605 packageName, extras, 0, null, null, new int[] {userId}); 11606 try { 11607 IActivityManager am = ActivityManagerNative.getDefault(); 11608 if (isSystem && am.isUserRunning(userId, 0)) { 11609 // The just-installed/enabled app is bundled on the system, so presumed 11610 // to be able to run automatically without needing an explicit launch. 11611 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11612 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11613 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11614 .setPackage(packageName); 11615 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11616 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11617 } 11618 } catch (RemoteException e) { 11619 // shouldn't happen 11620 Slog.w(TAG, "Unable to bootstrap installed package", e); 11621 } 11622 } 11623 11624 @Override 11625 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11626 int userId) { 11627 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11628 PackageSetting pkgSetting; 11629 final int uid = Binder.getCallingUid(); 11630 enforceCrossUserPermission(uid, userId, 11631 true /* requireFullPermission */, true /* checkShell */, 11632 "setApplicationHiddenSetting for user " + userId); 11633 11634 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11635 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11636 return false; 11637 } 11638 11639 long callingId = Binder.clearCallingIdentity(); 11640 try { 11641 boolean sendAdded = false; 11642 boolean sendRemoved = false; 11643 // writer 11644 synchronized (mPackages) { 11645 pkgSetting = mSettings.mPackages.get(packageName); 11646 if (pkgSetting == null) { 11647 return false; 11648 } 11649 if (pkgSetting.getHidden(userId) != hidden) { 11650 pkgSetting.setHidden(hidden, userId); 11651 mSettings.writePackageRestrictionsLPr(userId); 11652 if (hidden) { 11653 sendRemoved = true; 11654 } else { 11655 sendAdded = true; 11656 } 11657 } 11658 } 11659 if (sendAdded) { 11660 sendPackageAddedForUser(packageName, pkgSetting, userId); 11661 return true; 11662 } 11663 if (sendRemoved) { 11664 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11665 "hiding pkg"); 11666 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11667 return true; 11668 } 11669 } finally { 11670 Binder.restoreCallingIdentity(callingId); 11671 } 11672 return false; 11673 } 11674 11675 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11676 int userId) { 11677 final PackageRemovedInfo info = new PackageRemovedInfo(); 11678 info.removedPackage = packageName; 11679 info.removedUsers = new int[] {userId}; 11680 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11681 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11682 } 11683 11684 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11685 if (pkgList.length > 0) { 11686 Bundle extras = new Bundle(1); 11687 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11688 11689 sendPackageBroadcast( 11690 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11691 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11692 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11693 new int[] {userId}); 11694 } 11695 } 11696 11697 /** 11698 * Returns true if application is not found or there was an error. Otherwise it returns 11699 * the hidden state of the package for the given user. 11700 */ 11701 @Override 11702 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11703 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11704 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11705 true /* requireFullPermission */, false /* checkShell */, 11706 "getApplicationHidden for user " + userId); 11707 PackageSetting pkgSetting; 11708 long callingId = Binder.clearCallingIdentity(); 11709 try { 11710 // writer 11711 synchronized (mPackages) { 11712 pkgSetting = mSettings.mPackages.get(packageName); 11713 if (pkgSetting == null) { 11714 return true; 11715 } 11716 return pkgSetting.getHidden(userId); 11717 } 11718 } finally { 11719 Binder.restoreCallingIdentity(callingId); 11720 } 11721 } 11722 11723 /** 11724 * @hide 11725 */ 11726 @Override 11727 public int installExistingPackageAsUser(String packageName, int userId) { 11728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11729 null); 11730 PackageSetting pkgSetting; 11731 final int uid = Binder.getCallingUid(); 11732 enforceCrossUserPermission(uid, userId, 11733 true /* requireFullPermission */, true /* checkShell */, 11734 "installExistingPackage for user " + userId); 11735 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11736 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11737 } 11738 11739 long callingId = Binder.clearCallingIdentity(); 11740 try { 11741 boolean installed = false; 11742 11743 // writer 11744 synchronized (mPackages) { 11745 pkgSetting = mSettings.mPackages.get(packageName); 11746 if (pkgSetting == null) { 11747 return PackageManager.INSTALL_FAILED_INVALID_URI; 11748 } 11749 if (!pkgSetting.getInstalled(userId)) { 11750 pkgSetting.setInstalled(true, userId); 11751 pkgSetting.setHidden(false, userId); 11752 mSettings.writePackageRestrictionsLPr(userId); 11753 installed = true; 11754 } 11755 } 11756 11757 if (installed) { 11758 if (pkgSetting.pkg != null) { 11759 synchronized (mInstallLock) { 11760 // We don't need to freeze for a brand new install 11761 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11762 } 11763 } 11764 sendPackageAddedForUser(packageName, pkgSetting, userId); 11765 } 11766 } finally { 11767 Binder.restoreCallingIdentity(callingId); 11768 } 11769 11770 return PackageManager.INSTALL_SUCCEEDED; 11771 } 11772 11773 boolean isUserRestricted(int userId, String restrictionKey) { 11774 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11775 if (restrictions.getBoolean(restrictionKey, false)) { 11776 Log.w(TAG, "User is restricted: " + restrictionKey); 11777 return true; 11778 } 11779 return false; 11780 } 11781 11782 @Override 11783 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11784 int userId) { 11785 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11786 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11787 true /* requireFullPermission */, true /* checkShell */, 11788 "setPackagesSuspended for user " + userId); 11789 11790 if (ArrayUtils.isEmpty(packageNames)) { 11791 return packageNames; 11792 } 11793 11794 // List of package names for whom the suspended state has changed. 11795 List<String> changedPackages = new ArrayList<>(packageNames.length); 11796 // List of package names for whom the suspended state is not set as requested in this 11797 // method. 11798 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11799 long callingId = Binder.clearCallingIdentity(); 11800 try { 11801 for (int i = 0; i < packageNames.length; i++) { 11802 String packageName = packageNames[i]; 11803 boolean changed = false; 11804 final int appId; 11805 synchronized (mPackages) { 11806 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11807 if (pkgSetting == null) { 11808 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11809 + "\". Skipping suspending/un-suspending."); 11810 unactionedPackages.add(packageName); 11811 continue; 11812 } 11813 appId = pkgSetting.appId; 11814 if (pkgSetting.getSuspended(userId) != suspended) { 11815 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11816 unactionedPackages.add(packageName); 11817 continue; 11818 } 11819 pkgSetting.setSuspended(suspended, userId); 11820 mSettings.writePackageRestrictionsLPr(userId); 11821 changed = true; 11822 changedPackages.add(packageName); 11823 } 11824 } 11825 11826 if (changed && suspended) { 11827 killApplication(packageName, UserHandle.getUid(userId, appId), 11828 "suspending package"); 11829 } 11830 } 11831 } finally { 11832 Binder.restoreCallingIdentity(callingId); 11833 } 11834 11835 if (!changedPackages.isEmpty()) { 11836 sendPackagesSuspendedForUser(changedPackages.toArray( 11837 new String[changedPackages.size()]), userId, suspended); 11838 } 11839 11840 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11841 } 11842 11843 @Override 11844 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11845 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11846 true /* requireFullPermission */, false /* checkShell */, 11847 "isPackageSuspendedForUser for user " + userId); 11848 synchronized (mPackages) { 11849 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11850 if (pkgSetting == null) { 11851 throw new IllegalArgumentException("Unknown target package: " + packageName); 11852 } 11853 return pkgSetting.getSuspended(userId); 11854 } 11855 } 11856 11857 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11858 if (isPackageDeviceAdmin(packageName, userId)) { 11859 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11860 + "\": has an active device admin"); 11861 return false; 11862 } 11863 11864 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11865 if (packageName.equals(activeLauncherPackageName)) { 11866 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11867 + "\": contains the active launcher"); 11868 return false; 11869 } 11870 11871 if (packageName.equals(mRequiredInstallerPackage)) { 11872 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11873 + "\": required for package installation"); 11874 return false; 11875 } 11876 11877 if (packageName.equals(mRequiredVerifierPackage)) { 11878 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11879 + "\": required for package verification"); 11880 return false; 11881 } 11882 11883 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11884 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11885 + "\": is the default dialer"); 11886 return false; 11887 } 11888 11889 return true; 11890 } 11891 11892 private String getActiveLauncherPackageName(int userId) { 11893 Intent intent = new Intent(Intent.ACTION_MAIN); 11894 intent.addCategory(Intent.CATEGORY_HOME); 11895 ResolveInfo resolveInfo = resolveIntent( 11896 intent, 11897 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11898 PackageManager.MATCH_DEFAULT_ONLY, 11899 userId); 11900 11901 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11902 } 11903 11904 private String getDefaultDialerPackageName(int userId) { 11905 synchronized (mPackages) { 11906 return mSettings.getDefaultDialerPackageNameLPw(userId); 11907 } 11908 } 11909 11910 @Override 11911 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11912 mContext.enforceCallingOrSelfPermission( 11913 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11914 "Only package verification agents can verify applications"); 11915 11916 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11917 final PackageVerificationResponse response = new PackageVerificationResponse( 11918 verificationCode, Binder.getCallingUid()); 11919 msg.arg1 = id; 11920 msg.obj = response; 11921 mHandler.sendMessage(msg); 11922 } 11923 11924 @Override 11925 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11926 long millisecondsToDelay) { 11927 mContext.enforceCallingOrSelfPermission( 11928 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11929 "Only package verification agents can extend verification timeouts"); 11930 11931 final PackageVerificationState state = mPendingVerification.get(id); 11932 final PackageVerificationResponse response = new PackageVerificationResponse( 11933 verificationCodeAtTimeout, Binder.getCallingUid()); 11934 11935 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11936 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11937 } 11938 if (millisecondsToDelay < 0) { 11939 millisecondsToDelay = 0; 11940 } 11941 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11942 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11943 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11944 } 11945 11946 if ((state != null) && !state.timeoutExtended()) { 11947 state.extendTimeout(); 11948 11949 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11950 msg.arg1 = id; 11951 msg.obj = response; 11952 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11953 } 11954 } 11955 11956 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11957 int verificationCode, UserHandle user) { 11958 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11959 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11960 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11961 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11962 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11963 11964 mContext.sendBroadcastAsUser(intent, user, 11965 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11966 } 11967 11968 private ComponentName matchComponentForVerifier(String packageName, 11969 List<ResolveInfo> receivers) { 11970 ActivityInfo targetReceiver = null; 11971 11972 final int NR = receivers.size(); 11973 for (int i = 0; i < NR; i++) { 11974 final ResolveInfo info = receivers.get(i); 11975 if (info.activityInfo == null) { 11976 continue; 11977 } 11978 11979 if (packageName.equals(info.activityInfo.packageName)) { 11980 targetReceiver = info.activityInfo; 11981 break; 11982 } 11983 } 11984 11985 if (targetReceiver == null) { 11986 return null; 11987 } 11988 11989 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11990 } 11991 11992 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11993 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11994 if (pkgInfo.verifiers.length == 0) { 11995 return null; 11996 } 11997 11998 final int N = pkgInfo.verifiers.length; 11999 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12000 for (int i = 0; i < N; i++) { 12001 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12002 12003 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12004 receivers); 12005 if (comp == null) { 12006 continue; 12007 } 12008 12009 final int verifierUid = getUidForVerifier(verifierInfo); 12010 if (verifierUid == -1) { 12011 continue; 12012 } 12013 12014 if (DEBUG_VERIFY) { 12015 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12016 + " with the correct signature"); 12017 } 12018 sufficientVerifiers.add(comp); 12019 verificationState.addSufficientVerifier(verifierUid); 12020 } 12021 12022 return sufficientVerifiers; 12023 } 12024 12025 private int getUidForVerifier(VerifierInfo verifierInfo) { 12026 synchronized (mPackages) { 12027 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12028 if (pkg == null) { 12029 return -1; 12030 } else if (pkg.mSignatures.length != 1) { 12031 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12032 + " has more than one signature; ignoring"); 12033 return -1; 12034 } 12035 12036 /* 12037 * If the public key of the package's signature does not match 12038 * our expected public key, then this is a different package and 12039 * we should skip. 12040 */ 12041 12042 final byte[] expectedPublicKey; 12043 try { 12044 final Signature verifierSig = pkg.mSignatures[0]; 12045 final PublicKey publicKey = verifierSig.getPublicKey(); 12046 expectedPublicKey = publicKey.getEncoded(); 12047 } catch (CertificateException e) { 12048 return -1; 12049 } 12050 12051 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12052 12053 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12054 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12055 + " does not have the expected public key; ignoring"); 12056 return -1; 12057 } 12058 12059 return pkg.applicationInfo.uid; 12060 } 12061 } 12062 12063 @Override 12064 public void finishPackageInstall(int token, boolean didLaunch) { 12065 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12066 12067 if (DEBUG_INSTALL) { 12068 Slog.v(TAG, "BM finishing package install for " + token); 12069 } 12070 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12071 12072 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12073 mHandler.sendMessage(msg); 12074 } 12075 12076 /** 12077 * Get the verification agent timeout. 12078 * 12079 * @return verification timeout in milliseconds 12080 */ 12081 private long getVerificationTimeout() { 12082 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12083 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12084 DEFAULT_VERIFICATION_TIMEOUT); 12085 } 12086 12087 /** 12088 * Get the default verification agent response code. 12089 * 12090 * @return default verification response code 12091 */ 12092 private int getDefaultVerificationResponse() { 12093 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12094 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12095 DEFAULT_VERIFICATION_RESPONSE); 12096 } 12097 12098 /** 12099 * Check whether or not package verification has been enabled. 12100 * 12101 * @return true if verification should be performed 12102 */ 12103 private boolean isVerificationEnabled(int userId, int installFlags) { 12104 if (!DEFAULT_VERIFY_ENABLE) { 12105 return false; 12106 } 12107 // Ephemeral apps don't get the full verification treatment 12108 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12109 if (DEBUG_EPHEMERAL) { 12110 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12111 } 12112 return false; 12113 } 12114 12115 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12116 12117 // Check if installing from ADB 12118 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12119 // Do not run verification in a test harness environment 12120 if (ActivityManager.isRunningInTestHarness()) { 12121 return false; 12122 } 12123 if (ensureVerifyAppsEnabled) { 12124 return true; 12125 } 12126 // Check if the developer does not want package verification for ADB installs 12127 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12128 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12129 return false; 12130 } 12131 } 12132 12133 if (ensureVerifyAppsEnabled) { 12134 return true; 12135 } 12136 12137 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12138 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12139 } 12140 12141 @Override 12142 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12143 throws RemoteException { 12144 mContext.enforceCallingOrSelfPermission( 12145 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12146 "Only intentfilter verification agents can verify applications"); 12147 12148 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12149 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12150 Binder.getCallingUid(), verificationCode, failedDomains); 12151 msg.arg1 = id; 12152 msg.obj = response; 12153 mHandler.sendMessage(msg); 12154 } 12155 12156 @Override 12157 public int getIntentVerificationStatus(String packageName, int userId) { 12158 synchronized (mPackages) { 12159 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12160 } 12161 } 12162 12163 @Override 12164 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12165 mContext.enforceCallingOrSelfPermission( 12166 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12167 12168 boolean result = false; 12169 synchronized (mPackages) { 12170 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12171 } 12172 if (result) { 12173 scheduleWritePackageRestrictionsLocked(userId); 12174 } 12175 return result; 12176 } 12177 12178 @Override 12179 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12180 String packageName) { 12181 synchronized (mPackages) { 12182 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12183 } 12184 } 12185 12186 @Override 12187 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12188 if (TextUtils.isEmpty(packageName)) { 12189 return ParceledListSlice.emptyList(); 12190 } 12191 synchronized (mPackages) { 12192 PackageParser.Package pkg = mPackages.get(packageName); 12193 if (pkg == null || pkg.activities == null) { 12194 return ParceledListSlice.emptyList(); 12195 } 12196 final int count = pkg.activities.size(); 12197 ArrayList<IntentFilter> result = new ArrayList<>(); 12198 for (int n=0; n<count; n++) { 12199 PackageParser.Activity activity = pkg.activities.get(n); 12200 if (activity.intents != null && activity.intents.size() > 0) { 12201 result.addAll(activity.intents); 12202 } 12203 } 12204 return new ParceledListSlice<>(result); 12205 } 12206 } 12207 12208 @Override 12209 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12210 mContext.enforceCallingOrSelfPermission( 12211 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12212 12213 synchronized (mPackages) { 12214 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12215 if (packageName != null) { 12216 result |= updateIntentVerificationStatus(packageName, 12217 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12218 userId); 12219 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12220 packageName, userId); 12221 } 12222 return result; 12223 } 12224 } 12225 12226 @Override 12227 public String getDefaultBrowserPackageName(int userId) { 12228 synchronized (mPackages) { 12229 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12230 } 12231 } 12232 12233 /** 12234 * Get the "allow unknown sources" setting. 12235 * 12236 * @return the current "allow unknown sources" setting 12237 */ 12238 private int getUnknownSourcesSettings() { 12239 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12240 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12241 -1); 12242 } 12243 12244 @Override 12245 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12246 final int uid = Binder.getCallingUid(); 12247 // writer 12248 synchronized (mPackages) { 12249 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12250 if (targetPackageSetting == null) { 12251 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12252 } 12253 12254 PackageSetting installerPackageSetting; 12255 if (installerPackageName != null) { 12256 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12257 if (installerPackageSetting == null) { 12258 throw new IllegalArgumentException("Unknown installer package: " 12259 + installerPackageName); 12260 } 12261 } else { 12262 installerPackageSetting = null; 12263 } 12264 12265 Signature[] callerSignature; 12266 Object obj = mSettings.getUserIdLPr(uid); 12267 if (obj != null) { 12268 if (obj instanceof SharedUserSetting) { 12269 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12270 } else if (obj instanceof PackageSetting) { 12271 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12272 } else { 12273 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12274 } 12275 } else { 12276 throw new SecurityException("Unknown calling UID: " + uid); 12277 } 12278 12279 // Verify: can't set installerPackageName to a package that is 12280 // not signed with the same cert as the caller. 12281 if (installerPackageSetting != null) { 12282 if (compareSignatures(callerSignature, 12283 installerPackageSetting.signatures.mSignatures) 12284 != PackageManager.SIGNATURE_MATCH) { 12285 throw new SecurityException( 12286 "Caller does not have same cert as new installer package " 12287 + installerPackageName); 12288 } 12289 } 12290 12291 // Verify: if target already has an installer package, it must 12292 // be signed with the same cert as the caller. 12293 if (targetPackageSetting.installerPackageName != null) { 12294 PackageSetting setting = mSettings.mPackages.get( 12295 targetPackageSetting.installerPackageName); 12296 // If the currently set package isn't valid, then it's always 12297 // okay to change it. 12298 if (setting != null) { 12299 if (compareSignatures(callerSignature, 12300 setting.signatures.mSignatures) 12301 != PackageManager.SIGNATURE_MATCH) { 12302 throw new SecurityException( 12303 "Caller does not have same cert as old installer package " 12304 + targetPackageSetting.installerPackageName); 12305 } 12306 } 12307 } 12308 12309 // Okay! 12310 targetPackageSetting.installerPackageName = installerPackageName; 12311 if (installerPackageName != null) { 12312 mSettings.mInstallerPackages.add(installerPackageName); 12313 } 12314 scheduleWriteSettingsLocked(); 12315 } 12316 } 12317 12318 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12319 // Queue up an async operation since the package installation may take a little while. 12320 mHandler.post(new Runnable() { 12321 public void run() { 12322 mHandler.removeCallbacks(this); 12323 // Result object to be returned 12324 PackageInstalledInfo res = new PackageInstalledInfo(); 12325 res.setReturnCode(currentStatus); 12326 res.uid = -1; 12327 res.pkg = null; 12328 res.removedInfo = null; 12329 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12330 args.doPreInstall(res.returnCode); 12331 synchronized (mInstallLock) { 12332 installPackageTracedLI(args, res); 12333 } 12334 args.doPostInstall(res.returnCode, res.uid); 12335 } 12336 12337 // A restore should be performed at this point if (a) the install 12338 // succeeded, (b) the operation is not an update, and (c) the new 12339 // package has not opted out of backup participation. 12340 final boolean update = res.removedInfo != null 12341 && res.removedInfo.removedPackage != null; 12342 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12343 boolean doRestore = !update 12344 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12345 12346 // Set up the post-install work request bookkeeping. This will be used 12347 // and cleaned up by the post-install event handling regardless of whether 12348 // there's a restore pass performed. Token values are >= 1. 12349 int token; 12350 if (mNextInstallToken < 0) mNextInstallToken = 1; 12351 token = mNextInstallToken++; 12352 12353 PostInstallData data = new PostInstallData(args, res); 12354 mRunningInstalls.put(token, data); 12355 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12356 12357 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12358 // Pass responsibility to the Backup Manager. It will perform a 12359 // restore if appropriate, then pass responsibility back to the 12360 // Package Manager to run the post-install observer callbacks 12361 // and broadcasts. 12362 IBackupManager bm = IBackupManager.Stub.asInterface( 12363 ServiceManager.getService(Context.BACKUP_SERVICE)); 12364 if (bm != null) { 12365 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12366 + " to BM for possible restore"); 12367 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12368 try { 12369 // TODO: http://b/22388012 12370 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12371 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12372 } else { 12373 doRestore = false; 12374 } 12375 } catch (RemoteException e) { 12376 // can't happen; the backup manager is local 12377 } catch (Exception e) { 12378 Slog.e(TAG, "Exception trying to enqueue restore", e); 12379 doRestore = false; 12380 } 12381 } else { 12382 Slog.e(TAG, "Backup Manager not found!"); 12383 doRestore = false; 12384 } 12385 } 12386 12387 if (!doRestore) { 12388 // No restore possible, or the Backup Manager was mysteriously not 12389 // available -- just fire the post-install work request directly. 12390 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12391 12392 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12393 12394 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12395 mHandler.sendMessage(msg); 12396 } 12397 } 12398 }); 12399 } 12400 12401 /** 12402 * Callback from PackageSettings whenever an app is first transitioned out of the 12403 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12404 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12405 * here whether the app is the target of an ongoing install, and only send the 12406 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12407 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12408 * handling. 12409 */ 12410 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12411 // Serialize this with the rest of the install-process message chain. In the 12412 // restore-at-install case, this Runnable will necessarily run before the 12413 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12414 // are coherent. In the non-restore case, the app has already completed install 12415 // and been launched through some other means, so it is not in a problematic 12416 // state for observers to see the FIRST_LAUNCH signal. 12417 mHandler.post(new Runnable() { 12418 @Override 12419 public void run() { 12420 for (int i = 0; i < mRunningInstalls.size(); i++) { 12421 final PostInstallData data = mRunningInstalls.valueAt(i); 12422 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12423 // right package; but is it for the right user? 12424 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12425 if (userId == data.res.newUsers[uIndex]) { 12426 if (DEBUG_BACKUP) { 12427 Slog.i(TAG, "Package " + pkgName 12428 + " being restored so deferring FIRST_LAUNCH"); 12429 } 12430 return; 12431 } 12432 } 12433 } 12434 } 12435 // didn't find it, so not being restored 12436 if (DEBUG_BACKUP) { 12437 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12438 } 12439 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12440 } 12441 }); 12442 } 12443 12444 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12445 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12446 installerPkg, null, userIds); 12447 } 12448 12449 private abstract class HandlerParams { 12450 private static final int MAX_RETRIES = 4; 12451 12452 /** 12453 * Number of times startCopy() has been attempted and had a non-fatal 12454 * error. 12455 */ 12456 private int mRetries = 0; 12457 12458 /** User handle for the user requesting the information or installation. */ 12459 private final UserHandle mUser; 12460 String traceMethod; 12461 int traceCookie; 12462 12463 HandlerParams(UserHandle user) { 12464 mUser = user; 12465 } 12466 12467 UserHandle getUser() { 12468 return mUser; 12469 } 12470 12471 HandlerParams setTraceMethod(String traceMethod) { 12472 this.traceMethod = traceMethod; 12473 return this; 12474 } 12475 12476 HandlerParams setTraceCookie(int traceCookie) { 12477 this.traceCookie = traceCookie; 12478 return this; 12479 } 12480 12481 final boolean startCopy() { 12482 boolean res; 12483 try { 12484 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12485 12486 if (++mRetries > MAX_RETRIES) { 12487 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12488 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12489 handleServiceError(); 12490 return false; 12491 } else { 12492 handleStartCopy(); 12493 res = true; 12494 } 12495 } catch (RemoteException e) { 12496 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12497 mHandler.sendEmptyMessage(MCS_RECONNECT); 12498 res = false; 12499 } 12500 handleReturnCode(); 12501 return res; 12502 } 12503 12504 final void serviceError() { 12505 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12506 handleServiceError(); 12507 handleReturnCode(); 12508 } 12509 12510 abstract void handleStartCopy() throws RemoteException; 12511 abstract void handleServiceError(); 12512 abstract void handleReturnCode(); 12513 } 12514 12515 class MeasureParams extends HandlerParams { 12516 private final PackageStats mStats; 12517 private boolean mSuccess; 12518 12519 private final IPackageStatsObserver mObserver; 12520 12521 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12522 super(new UserHandle(stats.userHandle)); 12523 mObserver = observer; 12524 mStats = stats; 12525 } 12526 12527 @Override 12528 public String toString() { 12529 return "MeasureParams{" 12530 + Integer.toHexString(System.identityHashCode(this)) 12531 + " " + mStats.packageName + "}"; 12532 } 12533 12534 @Override 12535 void handleStartCopy() throws RemoteException { 12536 synchronized (mInstallLock) { 12537 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12538 } 12539 12540 if (mSuccess) { 12541 boolean mounted = false; 12542 try { 12543 final String status = Environment.getExternalStorageState(); 12544 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12545 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12546 } catch (Exception e) { 12547 } 12548 12549 if (mounted) { 12550 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12551 12552 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12553 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12554 12555 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12556 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12557 12558 // Always subtract cache size, since it's a subdirectory 12559 mStats.externalDataSize -= mStats.externalCacheSize; 12560 12561 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12562 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12563 12564 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12565 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12566 } 12567 } 12568 } 12569 12570 @Override 12571 void handleReturnCode() { 12572 if (mObserver != null) { 12573 try { 12574 mObserver.onGetStatsCompleted(mStats, mSuccess); 12575 } catch (RemoteException e) { 12576 Slog.i(TAG, "Observer no longer exists."); 12577 } 12578 } 12579 } 12580 12581 @Override 12582 void handleServiceError() { 12583 Slog.e(TAG, "Could not measure application " + mStats.packageName 12584 + " external storage"); 12585 } 12586 } 12587 12588 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12589 throws RemoteException { 12590 long result = 0; 12591 for (File path : paths) { 12592 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12593 } 12594 return result; 12595 } 12596 12597 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12598 for (File path : paths) { 12599 try { 12600 mcs.clearDirectory(path.getAbsolutePath()); 12601 } catch (RemoteException e) { 12602 } 12603 } 12604 } 12605 12606 static class OriginInfo { 12607 /** 12608 * Location where install is coming from, before it has been 12609 * copied/renamed into place. This could be a single monolithic APK 12610 * file, or a cluster directory. This location may be untrusted. 12611 */ 12612 final File file; 12613 final String cid; 12614 12615 /** 12616 * Flag indicating that {@link #file} or {@link #cid} has already been 12617 * staged, meaning downstream users don't need to defensively copy the 12618 * contents. 12619 */ 12620 final boolean staged; 12621 12622 /** 12623 * Flag indicating that {@link #file} or {@link #cid} is an already 12624 * installed app that is being moved. 12625 */ 12626 final boolean existing; 12627 12628 final String resolvedPath; 12629 final File resolvedFile; 12630 12631 static OriginInfo fromNothing() { 12632 return new OriginInfo(null, null, false, false); 12633 } 12634 12635 static OriginInfo fromUntrustedFile(File file) { 12636 return new OriginInfo(file, null, false, false); 12637 } 12638 12639 static OriginInfo fromExistingFile(File file) { 12640 return new OriginInfo(file, null, false, true); 12641 } 12642 12643 static OriginInfo fromStagedFile(File file) { 12644 return new OriginInfo(file, null, true, false); 12645 } 12646 12647 static OriginInfo fromStagedContainer(String cid) { 12648 return new OriginInfo(null, cid, true, false); 12649 } 12650 12651 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12652 this.file = file; 12653 this.cid = cid; 12654 this.staged = staged; 12655 this.existing = existing; 12656 12657 if (cid != null) { 12658 resolvedPath = PackageHelper.getSdDir(cid); 12659 resolvedFile = new File(resolvedPath); 12660 } else if (file != null) { 12661 resolvedPath = file.getAbsolutePath(); 12662 resolvedFile = file; 12663 } else { 12664 resolvedPath = null; 12665 resolvedFile = null; 12666 } 12667 } 12668 } 12669 12670 static class MoveInfo { 12671 final int moveId; 12672 final String fromUuid; 12673 final String toUuid; 12674 final String packageName; 12675 final String dataAppName; 12676 final int appId; 12677 final String seinfo; 12678 final int targetSdkVersion; 12679 12680 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12681 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12682 this.moveId = moveId; 12683 this.fromUuid = fromUuid; 12684 this.toUuid = toUuid; 12685 this.packageName = packageName; 12686 this.dataAppName = dataAppName; 12687 this.appId = appId; 12688 this.seinfo = seinfo; 12689 this.targetSdkVersion = targetSdkVersion; 12690 } 12691 } 12692 12693 static class VerificationInfo { 12694 /** A constant used to indicate that a uid value is not present. */ 12695 public static final int NO_UID = -1; 12696 12697 /** URI referencing where the package was downloaded from. */ 12698 final Uri originatingUri; 12699 12700 /** HTTP referrer URI associated with the originatingURI. */ 12701 final Uri referrer; 12702 12703 /** UID of the application that the install request originated from. */ 12704 final int originatingUid; 12705 12706 /** UID of application requesting the install */ 12707 final int installerUid; 12708 12709 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12710 this.originatingUri = originatingUri; 12711 this.referrer = referrer; 12712 this.originatingUid = originatingUid; 12713 this.installerUid = installerUid; 12714 } 12715 } 12716 12717 class InstallParams extends HandlerParams { 12718 final OriginInfo origin; 12719 final MoveInfo move; 12720 final IPackageInstallObserver2 observer; 12721 int installFlags; 12722 final String installerPackageName; 12723 final String volumeUuid; 12724 private InstallArgs mArgs; 12725 private int mRet; 12726 final String packageAbiOverride; 12727 final String[] grantedRuntimePermissions; 12728 final VerificationInfo verificationInfo; 12729 final Certificate[][] certificates; 12730 12731 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12732 int installFlags, String installerPackageName, String volumeUuid, 12733 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12734 String[] grantedPermissions, Certificate[][] certificates) { 12735 super(user); 12736 this.origin = origin; 12737 this.move = move; 12738 this.observer = observer; 12739 this.installFlags = installFlags; 12740 this.installerPackageName = installerPackageName; 12741 this.volumeUuid = volumeUuid; 12742 this.verificationInfo = verificationInfo; 12743 this.packageAbiOverride = packageAbiOverride; 12744 this.grantedRuntimePermissions = grantedPermissions; 12745 this.certificates = certificates; 12746 } 12747 12748 @Override 12749 public String toString() { 12750 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12751 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12752 } 12753 12754 private int installLocationPolicy(PackageInfoLite pkgLite) { 12755 String packageName = pkgLite.packageName; 12756 int installLocation = pkgLite.installLocation; 12757 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12758 // reader 12759 synchronized (mPackages) { 12760 // Currently installed package which the new package is attempting to replace or 12761 // null if no such package is installed. 12762 PackageParser.Package installedPkg = mPackages.get(packageName); 12763 // Package which currently owns the data which the new package will own if installed. 12764 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12765 // will be null whereas dataOwnerPkg will contain information about the package 12766 // which was uninstalled while keeping its data. 12767 PackageParser.Package dataOwnerPkg = installedPkg; 12768 if (dataOwnerPkg == null) { 12769 PackageSetting ps = mSettings.mPackages.get(packageName); 12770 if (ps != null) { 12771 dataOwnerPkg = ps.pkg; 12772 } 12773 } 12774 12775 if (dataOwnerPkg != null) { 12776 // If installed, the package will get access to data left on the device by its 12777 // predecessor. As a security measure, this is permited only if this is not a 12778 // version downgrade or if the predecessor package is marked as debuggable and 12779 // a downgrade is explicitly requested. 12780 // 12781 // On debuggable platform builds, downgrades are permitted even for 12782 // non-debuggable packages to make testing easier. Debuggable platform builds do 12783 // not offer security guarantees and thus it's OK to disable some security 12784 // mechanisms to make debugging/testing easier on those builds. However, even on 12785 // debuggable builds downgrades of packages are permitted only if requested via 12786 // installFlags. This is because we aim to keep the behavior of debuggable 12787 // platform builds as close as possible to the behavior of non-debuggable 12788 // platform builds. 12789 final boolean downgradeRequested = 12790 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12791 final boolean packageDebuggable = 12792 (dataOwnerPkg.applicationInfo.flags 12793 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12794 final boolean downgradePermitted = 12795 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12796 if (!downgradePermitted) { 12797 try { 12798 checkDowngrade(dataOwnerPkg, pkgLite); 12799 } catch (PackageManagerException e) { 12800 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12801 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12802 } 12803 } 12804 } 12805 12806 if (installedPkg != null) { 12807 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12808 // Check for updated system application. 12809 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12810 if (onSd) { 12811 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12812 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12813 } 12814 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12815 } else { 12816 if (onSd) { 12817 // Install flag overrides everything. 12818 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12819 } 12820 // If current upgrade specifies particular preference 12821 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12822 // Application explicitly specified internal. 12823 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12824 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12825 // App explictly prefers external. Let policy decide 12826 } else { 12827 // Prefer previous location 12828 if (isExternal(installedPkg)) { 12829 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12830 } 12831 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12832 } 12833 } 12834 } else { 12835 // Invalid install. Return error code 12836 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12837 } 12838 } 12839 } 12840 // All the special cases have been taken care of. 12841 // Return result based on recommended install location. 12842 if (onSd) { 12843 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12844 } 12845 return pkgLite.recommendedInstallLocation; 12846 } 12847 12848 /* 12849 * Invoke remote method to get package information and install 12850 * location values. Override install location based on default 12851 * policy if needed and then create install arguments based 12852 * on the install location. 12853 */ 12854 public void handleStartCopy() throws RemoteException { 12855 int ret = PackageManager.INSTALL_SUCCEEDED; 12856 12857 // If we're already staged, we've firmly committed to an install location 12858 if (origin.staged) { 12859 if (origin.file != null) { 12860 installFlags |= PackageManager.INSTALL_INTERNAL; 12861 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12862 } else if (origin.cid != null) { 12863 installFlags |= PackageManager.INSTALL_EXTERNAL; 12864 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12865 } else { 12866 throw new IllegalStateException("Invalid stage location"); 12867 } 12868 } 12869 12870 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12871 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12872 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12873 PackageInfoLite pkgLite = null; 12874 12875 if (onInt && onSd) { 12876 // Check if both bits are set. 12877 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12878 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12879 } else if (onSd && ephemeral) { 12880 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12881 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12882 } else { 12883 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12884 packageAbiOverride); 12885 12886 if (DEBUG_EPHEMERAL && ephemeral) { 12887 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12888 } 12889 12890 /* 12891 * If we have too little free space, try to free cache 12892 * before giving up. 12893 */ 12894 if (!origin.staged && pkgLite.recommendedInstallLocation 12895 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12896 // TODO: focus freeing disk space on the target device 12897 final StorageManager storage = StorageManager.from(mContext); 12898 final long lowThreshold = storage.getStorageLowBytes( 12899 Environment.getDataDirectory()); 12900 12901 final long sizeBytes = mContainerService.calculateInstalledSize( 12902 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12903 12904 try { 12905 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12906 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12907 installFlags, packageAbiOverride); 12908 } catch (InstallerException e) { 12909 Slog.w(TAG, "Failed to free cache", e); 12910 } 12911 12912 /* 12913 * The cache free must have deleted the file we 12914 * downloaded to install. 12915 * 12916 * TODO: fix the "freeCache" call to not delete 12917 * the file we care about. 12918 */ 12919 if (pkgLite.recommendedInstallLocation 12920 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12921 pkgLite.recommendedInstallLocation 12922 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12923 } 12924 } 12925 } 12926 12927 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12928 int loc = pkgLite.recommendedInstallLocation; 12929 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12930 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12931 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12932 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12933 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12934 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12935 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12936 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12937 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12938 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12939 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12940 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12941 } else { 12942 // Override with defaults if needed. 12943 loc = installLocationPolicy(pkgLite); 12944 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12945 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12946 } else if (!onSd && !onInt) { 12947 // Override install location with flags 12948 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12949 // Set the flag to install on external media. 12950 installFlags |= PackageManager.INSTALL_EXTERNAL; 12951 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12952 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12953 if (DEBUG_EPHEMERAL) { 12954 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12955 } 12956 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12957 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12958 |PackageManager.INSTALL_INTERNAL); 12959 } else { 12960 // Make sure the flag for installing on external 12961 // media is unset 12962 installFlags |= PackageManager.INSTALL_INTERNAL; 12963 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12964 } 12965 } 12966 } 12967 } 12968 12969 final InstallArgs args = createInstallArgs(this); 12970 mArgs = args; 12971 12972 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12973 // TODO: http://b/22976637 12974 // Apps installed for "all" users use the device owner to verify the app 12975 UserHandle verifierUser = getUser(); 12976 if (verifierUser == UserHandle.ALL) { 12977 verifierUser = UserHandle.SYSTEM; 12978 } 12979 12980 /* 12981 * Determine if we have any installed package verifiers. If we 12982 * do, then we'll defer to them to verify the packages. 12983 */ 12984 final int requiredUid = mRequiredVerifierPackage == null ? -1 12985 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12986 verifierUser.getIdentifier()); 12987 if (!origin.existing && requiredUid != -1 12988 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12989 final Intent verification = new Intent( 12990 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12991 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12992 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12993 PACKAGE_MIME_TYPE); 12994 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12995 12996 // Query all live verifiers based on current user state 12997 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12998 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12999 13000 if (DEBUG_VERIFY) { 13001 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13002 + verification.toString() + " with " + pkgLite.verifiers.length 13003 + " optional verifiers"); 13004 } 13005 13006 final int verificationId = mPendingVerificationToken++; 13007 13008 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13009 13010 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13011 installerPackageName); 13012 13013 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13014 installFlags); 13015 13016 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13017 pkgLite.packageName); 13018 13019 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13020 pkgLite.versionCode); 13021 13022 if (verificationInfo != null) { 13023 if (verificationInfo.originatingUri != null) { 13024 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13025 verificationInfo.originatingUri); 13026 } 13027 if (verificationInfo.referrer != null) { 13028 verification.putExtra(Intent.EXTRA_REFERRER, 13029 verificationInfo.referrer); 13030 } 13031 if (verificationInfo.originatingUid >= 0) { 13032 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13033 verificationInfo.originatingUid); 13034 } 13035 if (verificationInfo.installerUid >= 0) { 13036 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13037 verificationInfo.installerUid); 13038 } 13039 } 13040 13041 final PackageVerificationState verificationState = new PackageVerificationState( 13042 requiredUid, args); 13043 13044 mPendingVerification.append(verificationId, verificationState); 13045 13046 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13047 receivers, verificationState); 13048 13049 /* 13050 * If any sufficient verifiers were listed in the package 13051 * manifest, attempt to ask them. 13052 */ 13053 if (sufficientVerifiers != null) { 13054 final int N = sufficientVerifiers.size(); 13055 if (N == 0) { 13056 Slog.i(TAG, "Additional verifiers required, but none installed."); 13057 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13058 } else { 13059 for (int i = 0; i < N; i++) { 13060 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13061 13062 final Intent sufficientIntent = new Intent(verification); 13063 sufficientIntent.setComponent(verifierComponent); 13064 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13065 } 13066 } 13067 } 13068 13069 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13070 mRequiredVerifierPackage, receivers); 13071 if (ret == PackageManager.INSTALL_SUCCEEDED 13072 && mRequiredVerifierPackage != null) { 13073 Trace.asyncTraceBegin( 13074 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13075 /* 13076 * Send the intent to the required verification agent, 13077 * but only start the verification timeout after the 13078 * target BroadcastReceivers have run. 13079 */ 13080 verification.setComponent(requiredVerifierComponent); 13081 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13082 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13083 new BroadcastReceiver() { 13084 @Override 13085 public void onReceive(Context context, Intent intent) { 13086 final Message msg = mHandler 13087 .obtainMessage(CHECK_PENDING_VERIFICATION); 13088 msg.arg1 = verificationId; 13089 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13090 } 13091 }, null, 0, null, null); 13092 13093 /* 13094 * We don't want the copy to proceed until verification 13095 * succeeds, so null out this field. 13096 */ 13097 mArgs = null; 13098 } 13099 } else { 13100 /* 13101 * No package verification is enabled, so immediately start 13102 * the remote call to initiate copy using temporary file. 13103 */ 13104 ret = args.copyApk(mContainerService, true); 13105 } 13106 } 13107 13108 mRet = ret; 13109 } 13110 13111 @Override 13112 void handleReturnCode() { 13113 // If mArgs is null, then MCS couldn't be reached. When it 13114 // reconnects, it will try again to install. At that point, this 13115 // will succeed. 13116 if (mArgs != null) { 13117 processPendingInstall(mArgs, mRet); 13118 } 13119 } 13120 13121 @Override 13122 void handleServiceError() { 13123 mArgs = createInstallArgs(this); 13124 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13125 } 13126 13127 public boolean isForwardLocked() { 13128 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13129 } 13130 } 13131 13132 /** 13133 * Used during creation of InstallArgs 13134 * 13135 * @param installFlags package installation flags 13136 * @return true if should be installed on external storage 13137 */ 13138 private static boolean installOnExternalAsec(int installFlags) { 13139 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13140 return false; 13141 } 13142 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13143 return true; 13144 } 13145 return false; 13146 } 13147 13148 /** 13149 * Used during creation of InstallArgs 13150 * 13151 * @param installFlags package installation flags 13152 * @return true if should be installed as forward locked 13153 */ 13154 private static boolean installForwardLocked(int installFlags) { 13155 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13156 } 13157 13158 private InstallArgs createInstallArgs(InstallParams params) { 13159 if (params.move != null) { 13160 return new MoveInstallArgs(params); 13161 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13162 return new AsecInstallArgs(params); 13163 } else { 13164 return new FileInstallArgs(params); 13165 } 13166 } 13167 13168 /** 13169 * Create args that describe an existing installed package. Typically used 13170 * when cleaning up old installs, or used as a move source. 13171 */ 13172 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13173 String resourcePath, String[] instructionSets) { 13174 final boolean isInAsec; 13175 if (installOnExternalAsec(installFlags)) { 13176 /* Apps on SD card are always in ASEC containers. */ 13177 isInAsec = true; 13178 } else if (installForwardLocked(installFlags) 13179 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13180 /* 13181 * Forward-locked apps are only in ASEC containers if they're the 13182 * new style 13183 */ 13184 isInAsec = true; 13185 } else { 13186 isInAsec = false; 13187 } 13188 13189 if (isInAsec) { 13190 return new AsecInstallArgs(codePath, instructionSets, 13191 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13192 } else { 13193 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13194 } 13195 } 13196 13197 static abstract class InstallArgs { 13198 /** @see InstallParams#origin */ 13199 final OriginInfo origin; 13200 /** @see InstallParams#move */ 13201 final MoveInfo move; 13202 13203 final IPackageInstallObserver2 observer; 13204 // Always refers to PackageManager flags only 13205 final int installFlags; 13206 final String installerPackageName; 13207 final String volumeUuid; 13208 final UserHandle user; 13209 final String abiOverride; 13210 final String[] installGrantPermissions; 13211 /** If non-null, drop an async trace when the install completes */ 13212 final String traceMethod; 13213 final int traceCookie; 13214 final Certificate[][] certificates; 13215 13216 // The list of instruction sets supported by this app. This is currently 13217 // only used during the rmdex() phase to clean up resources. We can get rid of this 13218 // if we move dex files under the common app path. 13219 /* nullable */ String[] instructionSets; 13220 13221 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13222 int installFlags, String installerPackageName, String volumeUuid, 13223 UserHandle user, String[] instructionSets, 13224 String abiOverride, String[] installGrantPermissions, 13225 String traceMethod, int traceCookie, Certificate[][] certificates) { 13226 this.origin = origin; 13227 this.move = move; 13228 this.installFlags = installFlags; 13229 this.observer = observer; 13230 this.installerPackageName = installerPackageName; 13231 this.volumeUuid = volumeUuid; 13232 this.user = user; 13233 this.instructionSets = instructionSets; 13234 this.abiOverride = abiOverride; 13235 this.installGrantPermissions = installGrantPermissions; 13236 this.traceMethod = traceMethod; 13237 this.traceCookie = traceCookie; 13238 this.certificates = certificates; 13239 } 13240 13241 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13242 abstract int doPreInstall(int status); 13243 13244 /** 13245 * Rename package into final resting place. All paths on the given 13246 * scanned package should be updated to reflect the rename. 13247 */ 13248 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13249 abstract int doPostInstall(int status, int uid); 13250 13251 /** @see PackageSettingBase#codePathString */ 13252 abstract String getCodePath(); 13253 /** @see PackageSettingBase#resourcePathString */ 13254 abstract String getResourcePath(); 13255 13256 // Need installer lock especially for dex file removal. 13257 abstract void cleanUpResourcesLI(); 13258 abstract boolean doPostDeleteLI(boolean delete); 13259 13260 /** 13261 * Called before the source arguments are copied. This is used mostly 13262 * for MoveParams when it needs to read the source file to put it in the 13263 * destination. 13264 */ 13265 int doPreCopy() { 13266 return PackageManager.INSTALL_SUCCEEDED; 13267 } 13268 13269 /** 13270 * Called after the source arguments are copied. This is used mostly for 13271 * MoveParams when it needs to read the source file to put it in the 13272 * destination. 13273 */ 13274 int doPostCopy(int uid) { 13275 return PackageManager.INSTALL_SUCCEEDED; 13276 } 13277 13278 protected boolean isFwdLocked() { 13279 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13280 } 13281 13282 protected boolean isExternalAsec() { 13283 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13284 } 13285 13286 protected boolean isEphemeral() { 13287 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13288 } 13289 13290 UserHandle getUser() { 13291 return user; 13292 } 13293 } 13294 13295 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13296 if (!allCodePaths.isEmpty()) { 13297 if (instructionSets == null) { 13298 throw new IllegalStateException("instructionSet == null"); 13299 } 13300 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13301 for (String codePath : allCodePaths) { 13302 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13303 try { 13304 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13305 } catch (InstallerException ignored) { 13306 } 13307 } 13308 } 13309 } 13310 } 13311 13312 /** 13313 * Logic to handle installation of non-ASEC applications, including copying 13314 * and renaming logic. 13315 */ 13316 class FileInstallArgs extends InstallArgs { 13317 private File codeFile; 13318 private File resourceFile; 13319 13320 // Example topology: 13321 // /data/app/com.example/base.apk 13322 // /data/app/com.example/split_foo.apk 13323 // /data/app/com.example/lib/arm/libfoo.so 13324 // /data/app/com.example/lib/arm64/libfoo.so 13325 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13326 13327 /** New install */ 13328 FileInstallArgs(InstallParams params) { 13329 super(params.origin, params.move, params.observer, params.installFlags, 13330 params.installerPackageName, params.volumeUuid, 13331 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13332 params.grantedRuntimePermissions, 13333 params.traceMethod, params.traceCookie, params.certificates); 13334 if (isFwdLocked()) { 13335 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13336 } 13337 } 13338 13339 /** Existing install */ 13340 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13341 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13342 null, null, null, 0, null /*certificates*/); 13343 this.codeFile = (codePath != null) ? new File(codePath) : null; 13344 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13345 } 13346 13347 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13349 try { 13350 return doCopyApk(imcs, temp); 13351 } finally { 13352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13353 } 13354 } 13355 13356 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13357 if (origin.staged) { 13358 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13359 codeFile = origin.file; 13360 resourceFile = origin.file; 13361 return PackageManager.INSTALL_SUCCEEDED; 13362 } 13363 13364 try { 13365 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13366 final File tempDir = 13367 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13368 codeFile = tempDir; 13369 resourceFile = tempDir; 13370 } catch (IOException e) { 13371 Slog.w(TAG, "Failed to create copy file: " + e); 13372 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13373 } 13374 13375 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13376 @Override 13377 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13378 if (!FileUtils.isValidExtFilename(name)) { 13379 throw new IllegalArgumentException("Invalid filename: " + name); 13380 } 13381 try { 13382 final File file = new File(codeFile, name); 13383 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13384 O_RDWR | O_CREAT, 0644); 13385 Os.chmod(file.getAbsolutePath(), 0644); 13386 return new ParcelFileDescriptor(fd); 13387 } catch (ErrnoException e) { 13388 throw new RemoteException("Failed to open: " + e.getMessage()); 13389 } 13390 } 13391 }; 13392 13393 int ret = PackageManager.INSTALL_SUCCEEDED; 13394 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13395 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13396 Slog.e(TAG, "Failed to copy package"); 13397 return ret; 13398 } 13399 13400 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13401 NativeLibraryHelper.Handle handle = null; 13402 try { 13403 handle = NativeLibraryHelper.Handle.create(codeFile); 13404 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13405 abiOverride); 13406 } catch (IOException e) { 13407 Slog.e(TAG, "Copying native libraries failed", e); 13408 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13409 } finally { 13410 IoUtils.closeQuietly(handle); 13411 } 13412 13413 return ret; 13414 } 13415 13416 int doPreInstall(int status) { 13417 if (status != PackageManager.INSTALL_SUCCEEDED) { 13418 cleanUp(); 13419 } 13420 return status; 13421 } 13422 13423 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13424 if (status != PackageManager.INSTALL_SUCCEEDED) { 13425 cleanUp(); 13426 return false; 13427 } 13428 13429 final File targetDir = codeFile.getParentFile(); 13430 final File beforeCodeFile = codeFile; 13431 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13432 13433 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13434 try { 13435 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13436 } catch (ErrnoException e) { 13437 Slog.w(TAG, "Failed to rename", e); 13438 return false; 13439 } 13440 13441 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13442 Slog.w(TAG, "Failed to restorecon"); 13443 return false; 13444 } 13445 13446 // Reflect the rename internally 13447 codeFile = afterCodeFile; 13448 resourceFile = afterCodeFile; 13449 13450 // Reflect the rename in scanned details 13451 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13452 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13453 afterCodeFile, pkg.baseCodePath)); 13454 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13455 afterCodeFile, pkg.splitCodePaths)); 13456 13457 // Reflect the rename in app info 13458 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13459 pkg.setApplicationInfoCodePath(pkg.codePath); 13460 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13461 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13462 pkg.setApplicationInfoResourcePath(pkg.codePath); 13463 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13464 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13465 13466 return true; 13467 } 13468 13469 int doPostInstall(int status, int uid) { 13470 if (status != PackageManager.INSTALL_SUCCEEDED) { 13471 cleanUp(); 13472 } 13473 return status; 13474 } 13475 13476 @Override 13477 String getCodePath() { 13478 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13479 } 13480 13481 @Override 13482 String getResourcePath() { 13483 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13484 } 13485 13486 private boolean cleanUp() { 13487 if (codeFile == null || !codeFile.exists()) { 13488 return false; 13489 } 13490 13491 removeCodePathLI(codeFile); 13492 13493 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13494 resourceFile.delete(); 13495 } 13496 13497 return true; 13498 } 13499 13500 void cleanUpResourcesLI() { 13501 // Try enumerating all code paths before deleting 13502 List<String> allCodePaths = Collections.EMPTY_LIST; 13503 if (codeFile != null && codeFile.exists()) { 13504 try { 13505 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13506 allCodePaths = pkg.getAllCodePaths(); 13507 } catch (PackageParserException e) { 13508 // Ignored; we tried our best 13509 } 13510 } 13511 13512 cleanUp(); 13513 removeDexFiles(allCodePaths, instructionSets); 13514 } 13515 13516 boolean doPostDeleteLI(boolean delete) { 13517 // XXX err, shouldn't we respect the delete flag? 13518 cleanUpResourcesLI(); 13519 return true; 13520 } 13521 } 13522 13523 private boolean isAsecExternal(String cid) { 13524 final String asecPath = PackageHelper.getSdFilesystem(cid); 13525 return !asecPath.startsWith(mAsecInternalPath); 13526 } 13527 13528 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13529 PackageManagerException { 13530 if (copyRet < 0) { 13531 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13532 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13533 throw new PackageManagerException(copyRet, message); 13534 } 13535 } 13536 } 13537 13538 /** 13539 * Extract the MountService "container ID" from the full code path of an 13540 * .apk. 13541 */ 13542 static String cidFromCodePath(String fullCodePath) { 13543 int eidx = fullCodePath.lastIndexOf("/"); 13544 String subStr1 = fullCodePath.substring(0, eidx); 13545 int sidx = subStr1.lastIndexOf("/"); 13546 return subStr1.substring(sidx+1, eidx); 13547 } 13548 13549 /** 13550 * Logic to handle installation of ASEC applications, including copying and 13551 * renaming logic. 13552 */ 13553 class AsecInstallArgs extends InstallArgs { 13554 static final String RES_FILE_NAME = "pkg.apk"; 13555 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13556 13557 String cid; 13558 String packagePath; 13559 String resourcePath; 13560 13561 /** New install */ 13562 AsecInstallArgs(InstallParams params) { 13563 super(params.origin, params.move, params.observer, params.installFlags, 13564 params.installerPackageName, params.volumeUuid, 13565 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13566 params.grantedRuntimePermissions, 13567 params.traceMethod, params.traceCookie, params.certificates); 13568 } 13569 13570 /** Existing install */ 13571 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13572 boolean isExternal, boolean isForwardLocked) { 13573 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13574 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13575 instructionSets, null, null, null, 0, null /*certificates*/); 13576 // Hackily pretend we're still looking at a full code path 13577 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13578 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13579 } 13580 13581 // Extract cid from fullCodePath 13582 int eidx = fullCodePath.lastIndexOf("/"); 13583 String subStr1 = fullCodePath.substring(0, eidx); 13584 int sidx = subStr1.lastIndexOf("/"); 13585 cid = subStr1.substring(sidx+1, eidx); 13586 setMountPath(subStr1); 13587 } 13588 13589 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13590 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13591 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13592 instructionSets, null, null, null, 0, null /*certificates*/); 13593 this.cid = cid; 13594 setMountPath(PackageHelper.getSdDir(cid)); 13595 } 13596 13597 void createCopyFile() { 13598 cid = mInstallerService.allocateExternalStageCidLegacy(); 13599 } 13600 13601 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13602 if (origin.staged && origin.cid != null) { 13603 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13604 cid = origin.cid; 13605 setMountPath(PackageHelper.getSdDir(cid)); 13606 return PackageManager.INSTALL_SUCCEEDED; 13607 } 13608 13609 if (temp) { 13610 createCopyFile(); 13611 } else { 13612 /* 13613 * Pre-emptively destroy the container since it's destroyed if 13614 * copying fails due to it existing anyway. 13615 */ 13616 PackageHelper.destroySdDir(cid); 13617 } 13618 13619 final String newMountPath = imcs.copyPackageToContainer( 13620 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13621 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13622 13623 if (newMountPath != null) { 13624 setMountPath(newMountPath); 13625 return PackageManager.INSTALL_SUCCEEDED; 13626 } else { 13627 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13628 } 13629 } 13630 13631 @Override 13632 String getCodePath() { 13633 return packagePath; 13634 } 13635 13636 @Override 13637 String getResourcePath() { 13638 return resourcePath; 13639 } 13640 13641 int doPreInstall(int status) { 13642 if (status != PackageManager.INSTALL_SUCCEEDED) { 13643 // Destroy container 13644 PackageHelper.destroySdDir(cid); 13645 } else { 13646 boolean mounted = PackageHelper.isContainerMounted(cid); 13647 if (!mounted) { 13648 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13649 Process.SYSTEM_UID); 13650 if (newMountPath != null) { 13651 setMountPath(newMountPath); 13652 } else { 13653 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13654 } 13655 } 13656 } 13657 return status; 13658 } 13659 13660 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13661 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13662 String newMountPath = null; 13663 if (PackageHelper.isContainerMounted(cid)) { 13664 // Unmount the container 13665 if (!PackageHelper.unMountSdDir(cid)) { 13666 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13667 return false; 13668 } 13669 } 13670 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13671 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13672 " which might be stale. Will try to clean up."); 13673 // Clean up the stale container and proceed to recreate. 13674 if (!PackageHelper.destroySdDir(newCacheId)) { 13675 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13676 return false; 13677 } 13678 // Successfully cleaned up stale container. Try to rename again. 13679 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13680 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13681 + " inspite of cleaning it up."); 13682 return false; 13683 } 13684 } 13685 if (!PackageHelper.isContainerMounted(newCacheId)) { 13686 Slog.w(TAG, "Mounting container " + newCacheId); 13687 newMountPath = PackageHelper.mountSdDir(newCacheId, 13688 getEncryptKey(), Process.SYSTEM_UID); 13689 } else { 13690 newMountPath = PackageHelper.getSdDir(newCacheId); 13691 } 13692 if (newMountPath == null) { 13693 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13694 return false; 13695 } 13696 Log.i(TAG, "Succesfully renamed " + cid + 13697 " to " + newCacheId + 13698 " at new path: " + newMountPath); 13699 cid = newCacheId; 13700 13701 final File beforeCodeFile = new File(packagePath); 13702 setMountPath(newMountPath); 13703 final File afterCodeFile = new File(packagePath); 13704 13705 // Reflect the rename in scanned details 13706 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13707 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13708 afterCodeFile, pkg.baseCodePath)); 13709 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13710 afterCodeFile, pkg.splitCodePaths)); 13711 13712 // Reflect the rename in app info 13713 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13714 pkg.setApplicationInfoCodePath(pkg.codePath); 13715 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13716 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13717 pkg.setApplicationInfoResourcePath(pkg.codePath); 13718 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13719 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13720 13721 return true; 13722 } 13723 13724 private void setMountPath(String mountPath) { 13725 final File mountFile = new File(mountPath); 13726 13727 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13728 if (monolithicFile.exists()) { 13729 packagePath = monolithicFile.getAbsolutePath(); 13730 if (isFwdLocked()) { 13731 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13732 } else { 13733 resourcePath = packagePath; 13734 } 13735 } else { 13736 packagePath = mountFile.getAbsolutePath(); 13737 resourcePath = packagePath; 13738 } 13739 } 13740 13741 int doPostInstall(int status, int uid) { 13742 if (status != PackageManager.INSTALL_SUCCEEDED) { 13743 cleanUp(); 13744 } else { 13745 final int groupOwner; 13746 final String protectedFile; 13747 if (isFwdLocked()) { 13748 groupOwner = UserHandle.getSharedAppGid(uid); 13749 protectedFile = RES_FILE_NAME; 13750 } else { 13751 groupOwner = -1; 13752 protectedFile = null; 13753 } 13754 13755 if (uid < Process.FIRST_APPLICATION_UID 13756 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13757 Slog.e(TAG, "Failed to finalize " + cid); 13758 PackageHelper.destroySdDir(cid); 13759 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13760 } 13761 13762 boolean mounted = PackageHelper.isContainerMounted(cid); 13763 if (!mounted) { 13764 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13765 } 13766 } 13767 return status; 13768 } 13769 13770 private void cleanUp() { 13771 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13772 13773 // Destroy secure container 13774 PackageHelper.destroySdDir(cid); 13775 } 13776 13777 private List<String> getAllCodePaths() { 13778 final File codeFile = new File(getCodePath()); 13779 if (codeFile != null && codeFile.exists()) { 13780 try { 13781 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13782 return pkg.getAllCodePaths(); 13783 } catch (PackageParserException e) { 13784 // Ignored; we tried our best 13785 } 13786 } 13787 return Collections.EMPTY_LIST; 13788 } 13789 13790 void cleanUpResourcesLI() { 13791 // Enumerate all code paths before deleting 13792 cleanUpResourcesLI(getAllCodePaths()); 13793 } 13794 13795 private void cleanUpResourcesLI(List<String> allCodePaths) { 13796 cleanUp(); 13797 removeDexFiles(allCodePaths, instructionSets); 13798 } 13799 13800 String getPackageName() { 13801 return getAsecPackageName(cid); 13802 } 13803 13804 boolean doPostDeleteLI(boolean delete) { 13805 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13806 final List<String> allCodePaths = getAllCodePaths(); 13807 boolean mounted = PackageHelper.isContainerMounted(cid); 13808 if (mounted) { 13809 // Unmount first 13810 if (PackageHelper.unMountSdDir(cid)) { 13811 mounted = false; 13812 } 13813 } 13814 if (!mounted && delete) { 13815 cleanUpResourcesLI(allCodePaths); 13816 } 13817 return !mounted; 13818 } 13819 13820 @Override 13821 int doPreCopy() { 13822 if (isFwdLocked()) { 13823 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13824 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13825 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13826 } 13827 } 13828 13829 return PackageManager.INSTALL_SUCCEEDED; 13830 } 13831 13832 @Override 13833 int doPostCopy(int uid) { 13834 if (isFwdLocked()) { 13835 if (uid < Process.FIRST_APPLICATION_UID 13836 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13837 RES_FILE_NAME)) { 13838 Slog.e(TAG, "Failed to finalize " + cid); 13839 PackageHelper.destroySdDir(cid); 13840 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13841 } 13842 } 13843 13844 return PackageManager.INSTALL_SUCCEEDED; 13845 } 13846 } 13847 13848 /** 13849 * Logic to handle movement of existing installed applications. 13850 */ 13851 class MoveInstallArgs extends InstallArgs { 13852 private File codeFile; 13853 private File resourceFile; 13854 13855 /** New install */ 13856 MoveInstallArgs(InstallParams params) { 13857 super(params.origin, params.move, params.observer, params.installFlags, 13858 params.installerPackageName, params.volumeUuid, 13859 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13860 params.grantedRuntimePermissions, 13861 params.traceMethod, params.traceCookie, params.certificates); 13862 } 13863 13864 int copyApk(IMediaContainerService imcs, boolean temp) { 13865 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13866 + move.fromUuid + " to " + move.toUuid); 13867 synchronized (mInstaller) { 13868 try { 13869 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13870 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13871 } catch (InstallerException e) { 13872 Slog.w(TAG, "Failed to move app", e); 13873 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13874 } 13875 } 13876 13877 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13878 resourceFile = codeFile; 13879 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13880 13881 return PackageManager.INSTALL_SUCCEEDED; 13882 } 13883 13884 int doPreInstall(int status) { 13885 if (status != PackageManager.INSTALL_SUCCEEDED) { 13886 cleanUp(move.toUuid); 13887 } 13888 return status; 13889 } 13890 13891 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13892 if (status != PackageManager.INSTALL_SUCCEEDED) { 13893 cleanUp(move.toUuid); 13894 return false; 13895 } 13896 13897 // Reflect the move in app info 13898 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13899 pkg.setApplicationInfoCodePath(pkg.codePath); 13900 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13901 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13902 pkg.setApplicationInfoResourcePath(pkg.codePath); 13903 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13904 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13905 13906 return true; 13907 } 13908 13909 int doPostInstall(int status, int uid) { 13910 if (status == PackageManager.INSTALL_SUCCEEDED) { 13911 cleanUp(move.fromUuid); 13912 } else { 13913 cleanUp(move.toUuid); 13914 } 13915 return status; 13916 } 13917 13918 @Override 13919 String getCodePath() { 13920 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13921 } 13922 13923 @Override 13924 String getResourcePath() { 13925 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13926 } 13927 13928 private boolean cleanUp(String volumeUuid) { 13929 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13930 move.dataAppName); 13931 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13932 final int[] userIds = sUserManager.getUserIds(); 13933 synchronized (mInstallLock) { 13934 // Clean up both app data and code 13935 // All package moves are frozen until finished 13936 for (int userId : userIds) { 13937 try { 13938 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13939 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13940 } catch (InstallerException e) { 13941 Slog.w(TAG, String.valueOf(e)); 13942 } 13943 } 13944 removeCodePathLI(codeFile); 13945 } 13946 return true; 13947 } 13948 13949 void cleanUpResourcesLI() { 13950 throw new UnsupportedOperationException(); 13951 } 13952 13953 boolean doPostDeleteLI(boolean delete) { 13954 throw new UnsupportedOperationException(); 13955 } 13956 } 13957 13958 static String getAsecPackageName(String packageCid) { 13959 int idx = packageCid.lastIndexOf("-"); 13960 if (idx == -1) { 13961 return packageCid; 13962 } 13963 return packageCid.substring(0, idx); 13964 } 13965 13966 // Utility method used to create code paths based on package name and available index. 13967 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13968 String idxStr = ""; 13969 int idx = 1; 13970 // Fall back to default value of idx=1 if prefix is not 13971 // part of oldCodePath 13972 if (oldCodePath != null) { 13973 String subStr = oldCodePath; 13974 // Drop the suffix right away 13975 if (suffix != null && subStr.endsWith(suffix)) { 13976 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13977 } 13978 // If oldCodePath already contains prefix find out the 13979 // ending index to either increment or decrement. 13980 int sidx = subStr.lastIndexOf(prefix); 13981 if (sidx != -1) { 13982 subStr = subStr.substring(sidx + prefix.length()); 13983 if (subStr != null) { 13984 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13985 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13986 } 13987 try { 13988 idx = Integer.parseInt(subStr); 13989 if (idx <= 1) { 13990 idx++; 13991 } else { 13992 idx--; 13993 } 13994 } catch(NumberFormatException e) { 13995 } 13996 } 13997 } 13998 } 13999 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14000 return prefix + idxStr; 14001 } 14002 14003 private File getNextCodePath(File targetDir, String packageName) { 14004 int suffix = 1; 14005 File result; 14006 do { 14007 result = new File(targetDir, packageName + "-" + suffix); 14008 suffix++; 14009 } while (result.exists()); 14010 return result; 14011 } 14012 14013 // Utility method that returns the relative package path with respect 14014 // to the installation directory. Like say for /data/data/com.test-1.apk 14015 // string com.test-1 is returned. 14016 static String deriveCodePathName(String codePath) { 14017 if (codePath == null) { 14018 return null; 14019 } 14020 final File codeFile = new File(codePath); 14021 final String name = codeFile.getName(); 14022 if (codeFile.isDirectory()) { 14023 return name; 14024 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14025 final int lastDot = name.lastIndexOf('.'); 14026 return name.substring(0, lastDot); 14027 } else { 14028 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14029 return null; 14030 } 14031 } 14032 14033 static class PackageInstalledInfo { 14034 String name; 14035 int uid; 14036 // The set of users that originally had this package installed. 14037 int[] origUsers; 14038 // The set of users that now have this package installed. 14039 int[] newUsers; 14040 PackageParser.Package pkg; 14041 int returnCode; 14042 String returnMsg; 14043 PackageRemovedInfo removedInfo; 14044 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14045 14046 public void setError(int code, String msg) { 14047 setReturnCode(code); 14048 setReturnMessage(msg); 14049 Slog.w(TAG, msg); 14050 } 14051 14052 public void setError(String msg, PackageParserException e) { 14053 setReturnCode(e.error); 14054 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14055 Slog.w(TAG, msg, e); 14056 } 14057 14058 public void setError(String msg, PackageManagerException e) { 14059 returnCode = e.error; 14060 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14061 Slog.w(TAG, msg, e); 14062 } 14063 14064 public void setReturnCode(int returnCode) { 14065 this.returnCode = returnCode; 14066 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14067 for (int i = 0; i < childCount; i++) { 14068 addedChildPackages.valueAt(i).returnCode = returnCode; 14069 } 14070 } 14071 14072 private void setReturnMessage(String returnMsg) { 14073 this.returnMsg = returnMsg; 14074 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14075 for (int i = 0; i < childCount; i++) { 14076 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14077 } 14078 } 14079 14080 // In some error cases we want to convey more info back to the observer 14081 String origPackage; 14082 String origPermission; 14083 } 14084 14085 /* 14086 * Install a non-existing package. 14087 */ 14088 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14089 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14090 PackageInstalledInfo res) { 14091 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14092 14093 // Remember this for later, in case we need to rollback this install 14094 String pkgName = pkg.packageName; 14095 14096 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14097 14098 synchronized(mPackages) { 14099 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14100 // A package with the same name is already installed, though 14101 // it has been renamed to an older name. The package we 14102 // are trying to install should be installed as an update to 14103 // the existing one, but that has not been requested, so bail. 14104 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14105 + " without first uninstalling package running as " 14106 + mSettings.mRenamedPackages.get(pkgName)); 14107 return; 14108 } 14109 if (mPackages.containsKey(pkgName)) { 14110 // Don't allow installation over an existing package with the same name. 14111 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14112 + " without first uninstalling."); 14113 return; 14114 } 14115 } 14116 14117 try { 14118 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14119 System.currentTimeMillis(), user); 14120 14121 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14122 14123 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14124 prepareAppDataAfterInstallLIF(newPackage); 14125 14126 } else { 14127 // Remove package from internal structures, but keep around any 14128 // data that might have already existed 14129 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14130 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14131 } 14132 } catch (PackageManagerException e) { 14133 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14134 } 14135 14136 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14137 } 14138 14139 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14140 // Can't rotate keys during boot or if sharedUser. 14141 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14142 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14143 return false; 14144 } 14145 // app is using upgradeKeySets; make sure all are valid 14146 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14147 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14148 for (int i = 0; i < upgradeKeySets.length; i++) { 14149 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14150 Slog.wtf(TAG, "Package " 14151 + (oldPs.name != null ? oldPs.name : "<null>") 14152 + " contains upgrade-key-set reference to unknown key-set: " 14153 + upgradeKeySets[i] 14154 + " reverting to signatures check."); 14155 return false; 14156 } 14157 } 14158 return true; 14159 } 14160 14161 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14162 // Upgrade keysets are being used. Determine if new package has a superset of the 14163 // required keys. 14164 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14165 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14166 for (int i = 0; i < upgradeKeySets.length; i++) { 14167 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14168 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14169 return true; 14170 } 14171 } 14172 return false; 14173 } 14174 14175 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14176 try (DigestInputStream digestStream = 14177 new DigestInputStream(new FileInputStream(file), digest)) { 14178 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14179 } 14180 } 14181 14182 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14183 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14184 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14185 14186 final PackageParser.Package oldPackage; 14187 final String pkgName = pkg.packageName; 14188 final int[] allUsers; 14189 final int[] installedUsers; 14190 14191 synchronized(mPackages) { 14192 oldPackage = mPackages.get(pkgName); 14193 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14194 14195 // don't allow upgrade to target a release SDK from a pre-release SDK 14196 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14197 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14198 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14199 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14200 if (oldTargetsPreRelease 14201 && !newTargetsPreRelease 14202 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14203 Slog.w(TAG, "Can't install package targeting released sdk"); 14204 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14205 return; 14206 } 14207 14208 // don't allow an upgrade from full to ephemeral 14209 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14210 if (isEphemeral && !oldIsEphemeral) { 14211 // can't downgrade from full to ephemeral 14212 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14213 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14214 return; 14215 } 14216 14217 // verify signatures are valid 14218 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14219 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14220 if (!checkUpgradeKeySetLP(ps, pkg)) { 14221 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14222 "New package not signed by keys specified by upgrade-keysets: " 14223 + pkgName); 14224 return; 14225 } 14226 } else { 14227 // default to original signature matching 14228 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14229 != PackageManager.SIGNATURE_MATCH) { 14230 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14231 "New package has a different signature: " + pkgName); 14232 return; 14233 } 14234 } 14235 14236 // don't allow a system upgrade unless the upgrade hash matches 14237 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14238 byte[] digestBytes = null; 14239 try { 14240 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14241 updateDigest(digest, new File(pkg.baseCodePath)); 14242 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14243 for (String path : pkg.splitCodePaths) { 14244 updateDigest(digest, new File(path)); 14245 } 14246 } 14247 digestBytes = digest.digest(); 14248 } catch (NoSuchAlgorithmException | IOException e) { 14249 res.setError(INSTALL_FAILED_INVALID_APK, 14250 "Could not compute hash: " + pkgName); 14251 return; 14252 } 14253 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14254 res.setError(INSTALL_FAILED_INVALID_APK, 14255 "New package fails restrict-update check: " + pkgName); 14256 return; 14257 } 14258 // retain upgrade restriction 14259 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14260 } 14261 14262 // Check for shared user id changes 14263 String invalidPackageName = 14264 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14265 if (invalidPackageName != null) { 14266 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14267 "Package " + invalidPackageName + " tried to change user " 14268 + oldPackage.mSharedUserId); 14269 return; 14270 } 14271 14272 // In case of rollback, remember per-user/profile install state 14273 allUsers = sUserManager.getUserIds(); 14274 installedUsers = ps.queryInstalledUsers(allUsers, true); 14275 } 14276 14277 // Update what is removed 14278 res.removedInfo = new PackageRemovedInfo(); 14279 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14280 res.removedInfo.removedPackage = oldPackage.packageName; 14281 res.removedInfo.isUpdate = true; 14282 res.removedInfo.origUsers = installedUsers; 14283 final int childCount = (oldPackage.childPackages != null) 14284 ? oldPackage.childPackages.size() : 0; 14285 for (int i = 0; i < childCount; i++) { 14286 boolean childPackageUpdated = false; 14287 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14288 if (res.addedChildPackages != null) { 14289 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14290 if (childRes != null) { 14291 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14292 childRes.removedInfo.removedPackage = childPkg.packageName; 14293 childRes.removedInfo.isUpdate = true; 14294 childPackageUpdated = true; 14295 } 14296 } 14297 if (!childPackageUpdated) { 14298 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14299 childRemovedRes.removedPackage = childPkg.packageName; 14300 childRemovedRes.isUpdate = false; 14301 childRemovedRes.dataRemoved = true; 14302 synchronized (mPackages) { 14303 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14304 if (childPs != null) { 14305 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14306 } 14307 } 14308 if (res.removedInfo.removedChildPackages == null) { 14309 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14310 } 14311 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14312 } 14313 } 14314 14315 boolean sysPkg = (isSystemApp(oldPackage)); 14316 if (sysPkg) { 14317 // Set the system/privileged flags as needed 14318 final boolean privileged = 14319 (oldPackage.applicationInfo.privateFlags 14320 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14321 final int systemPolicyFlags = policyFlags 14322 | PackageParser.PARSE_IS_SYSTEM 14323 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14324 14325 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14326 user, allUsers, installerPackageName, res); 14327 } else { 14328 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14329 user, allUsers, installerPackageName, res); 14330 } 14331 } 14332 14333 public List<String> getPreviousCodePaths(String packageName) { 14334 final PackageSetting ps = mSettings.mPackages.get(packageName); 14335 final List<String> result = new ArrayList<String>(); 14336 if (ps != null && ps.oldCodePaths != null) { 14337 result.addAll(ps.oldCodePaths); 14338 } 14339 return result; 14340 } 14341 14342 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14343 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14344 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14345 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14346 + deletedPackage); 14347 14348 String pkgName = deletedPackage.packageName; 14349 boolean deletedPkg = true; 14350 boolean addedPkg = false; 14351 boolean updatedSettings = false; 14352 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14353 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14354 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14355 14356 final long origUpdateTime = (pkg.mExtras != null) 14357 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14358 14359 // First delete the existing package while retaining the data directory 14360 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14361 res.removedInfo, true, pkg)) { 14362 // If the existing package wasn't successfully deleted 14363 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14364 deletedPkg = false; 14365 } else { 14366 // Successfully deleted the old package; proceed with replace. 14367 14368 // If deleted package lived in a container, give users a chance to 14369 // relinquish resources before killing. 14370 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14371 if (DEBUG_INSTALL) { 14372 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14373 } 14374 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14375 final ArrayList<String> pkgList = new ArrayList<String>(1); 14376 pkgList.add(deletedPackage.applicationInfo.packageName); 14377 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14378 } 14379 14380 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14381 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14382 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14383 14384 try { 14385 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14386 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14387 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14388 14389 // Update the in-memory copy of the previous code paths. 14390 PackageSetting ps = mSettings.mPackages.get(pkgName); 14391 if (!killApp) { 14392 if (ps.oldCodePaths == null) { 14393 ps.oldCodePaths = new ArraySet<>(); 14394 } 14395 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14396 if (deletedPackage.splitCodePaths != null) { 14397 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14398 } 14399 } else { 14400 ps.oldCodePaths = null; 14401 } 14402 if (ps.childPackageNames != null) { 14403 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14404 final String childPkgName = ps.childPackageNames.get(i); 14405 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14406 childPs.oldCodePaths = ps.oldCodePaths; 14407 } 14408 } 14409 prepareAppDataAfterInstallLIF(newPackage); 14410 addedPkg = true; 14411 } catch (PackageManagerException e) { 14412 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14413 } 14414 } 14415 14416 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14417 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14418 14419 // Revert all internal state mutations and added folders for the failed install 14420 if (addedPkg) { 14421 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14422 res.removedInfo, true, null); 14423 } 14424 14425 // Restore the old package 14426 if (deletedPkg) { 14427 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14428 File restoreFile = new File(deletedPackage.codePath); 14429 // Parse old package 14430 boolean oldExternal = isExternal(deletedPackage); 14431 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14432 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14433 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14434 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14435 try { 14436 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14437 null); 14438 } catch (PackageManagerException e) { 14439 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14440 + e.getMessage()); 14441 return; 14442 } 14443 14444 synchronized (mPackages) { 14445 // Ensure the installer package name up to date 14446 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14447 14448 // Update permissions for restored package 14449 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14450 14451 mSettings.writeLPr(); 14452 } 14453 14454 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14455 } 14456 } else { 14457 synchronized (mPackages) { 14458 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14459 if (ps != null) { 14460 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14461 if (res.removedInfo.removedChildPackages != null) { 14462 final int childCount = res.removedInfo.removedChildPackages.size(); 14463 // Iterate in reverse as we may modify the collection 14464 for (int i = childCount - 1; i >= 0; i--) { 14465 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14466 if (res.addedChildPackages.containsKey(childPackageName)) { 14467 res.removedInfo.removedChildPackages.removeAt(i); 14468 } else { 14469 PackageRemovedInfo childInfo = res.removedInfo 14470 .removedChildPackages.valueAt(i); 14471 childInfo.removedForAllUsers = mPackages.get( 14472 childInfo.removedPackage) == null; 14473 } 14474 } 14475 } 14476 } 14477 } 14478 } 14479 } 14480 14481 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14482 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14483 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14484 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14485 + ", old=" + deletedPackage); 14486 14487 final boolean disabledSystem; 14488 14489 // Remove existing system package 14490 removePackageLI(deletedPackage, true); 14491 14492 synchronized (mPackages) { 14493 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14494 } 14495 if (!disabledSystem) { 14496 // We didn't need to disable the .apk as a current system package, 14497 // which means we are replacing another update that is already 14498 // installed. We need to make sure to delete the older one's .apk. 14499 res.removedInfo.args = createInstallArgsForExisting(0, 14500 deletedPackage.applicationInfo.getCodePath(), 14501 deletedPackage.applicationInfo.getResourcePath(), 14502 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14503 } else { 14504 res.removedInfo.args = null; 14505 } 14506 14507 // Successfully disabled the old package. Now proceed with re-installation 14508 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14509 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14510 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14511 14512 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14513 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14514 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14515 14516 PackageParser.Package newPackage = null; 14517 try { 14518 // Add the package to the internal data structures 14519 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14520 14521 // Set the update and install times 14522 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14523 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14524 System.currentTimeMillis()); 14525 14526 // Update the package dynamic state if succeeded 14527 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14528 // Now that the install succeeded make sure we remove data 14529 // directories for any child package the update removed. 14530 final int deletedChildCount = (deletedPackage.childPackages != null) 14531 ? deletedPackage.childPackages.size() : 0; 14532 final int newChildCount = (newPackage.childPackages != null) 14533 ? newPackage.childPackages.size() : 0; 14534 for (int i = 0; i < deletedChildCount; i++) { 14535 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14536 boolean childPackageDeleted = true; 14537 for (int j = 0; j < newChildCount; j++) { 14538 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14539 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14540 childPackageDeleted = false; 14541 break; 14542 } 14543 } 14544 if (childPackageDeleted) { 14545 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14546 deletedChildPkg.packageName); 14547 if (ps != null && res.removedInfo.removedChildPackages != null) { 14548 PackageRemovedInfo removedChildRes = res.removedInfo 14549 .removedChildPackages.get(deletedChildPkg.packageName); 14550 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14551 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14552 } 14553 } 14554 } 14555 14556 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14557 prepareAppDataAfterInstallLIF(newPackage); 14558 } 14559 } catch (PackageManagerException e) { 14560 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14561 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14562 } 14563 14564 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14565 // Re installation failed. Restore old information 14566 // Remove new pkg information 14567 if (newPackage != null) { 14568 removeInstalledPackageLI(newPackage, true); 14569 } 14570 // Add back the old system package 14571 try { 14572 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14573 } catch (PackageManagerException e) { 14574 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14575 } 14576 14577 synchronized (mPackages) { 14578 if (disabledSystem) { 14579 enableSystemPackageLPw(deletedPackage); 14580 } 14581 14582 // Ensure the installer package name up to date 14583 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14584 14585 // Update permissions for restored package 14586 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14587 14588 mSettings.writeLPr(); 14589 } 14590 14591 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14592 + " after failed upgrade"); 14593 } 14594 } 14595 14596 /** 14597 * Checks whether the parent or any of the child packages have a change shared 14598 * user. For a package to be a valid update the shred users of the parent and 14599 * the children should match. We may later support changing child shared users. 14600 * @param oldPkg The updated package. 14601 * @param newPkg The update package. 14602 * @return The shared user that change between the versions. 14603 */ 14604 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14605 PackageParser.Package newPkg) { 14606 // Check parent shared user 14607 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14608 return newPkg.packageName; 14609 } 14610 // Check child shared users 14611 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14612 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14613 for (int i = 0; i < newChildCount; i++) { 14614 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14615 // If this child was present, did it have the same shared user? 14616 for (int j = 0; j < oldChildCount; j++) { 14617 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14618 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14619 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14620 return newChildPkg.packageName; 14621 } 14622 } 14623 } 14624 return null; 14625 } 14626 14627 private void removeNativeBinariesLI(PackageSetting ps) { 14628 // Remove the lib path for the parent package 14629 if (ps != null) { 14630 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14631 // Remove the lib path for the child packages 14632 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14633 for (int i = 0; i < childCount; i++) { 14634 PackageSetting childPs = null; 14635 synchronized (mPackages) { 14636 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14637 } 14638 if (childPs != null) { 14639 NativeLibraryHelper.removeNativeBinariesLI(childPs 14640 .legacyNativeLibraryPathString); 14641 } 14642 } 14643 } 14644 } 14645 14646 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14647 // Enable the parent package 14648 mSettings.enableSystemPackageLPw(pkg.packageName); 14649 // Enable the child packages 14650 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14651 for (int i = 0; i < childCount; i++) { 14652 PackageParser.Package childPkg = pkg.childPackages.get(i); 14653 mSettings.enableSystemPackageLPw(childPkg.packageName); 14654 } 14655 } 14656 14657 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14658 PackageParser.Package newPkg) { 14659 // Disable the parent package (parent always replaced) 14660 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14661 // Disable the child packages 14662 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14663 for (int i = 0; i < childCount; i++) { 14664 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14665 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14666 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14667 } 14668 return disabled; 14669 } 14670 14671 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14672 String installerPackageName) { 14673 // Enable the parent package 14674 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14675 // Enable the child packages 14676 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14677 for (int i = 0; i < childCount; i++) { 14678 PackageParser.Package childPkg = pkg.childPackages.get(i); 14679 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14680 } 14681 } 14682 14683 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14684 // Collect all used permissions in the UID 14685 ArraySet<String> usedPermissions = new ArraySet<>(); 14686 final int packageCount = su.packages.size(); 14687 for (int i = 0; i < packageCount; i++) { 14688 PackageSetting ps = su.packages.valueAt(i); 14689 if (ps.pkg == null) { 14690 continue; 14691 } 14692 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14693 for (int j = 0; j < requestedPermCount; j++) { 14694 String permission = ps.pkg.requestedPermissions.get(j); 14695 BasePermission bp = mSettings.mPermissions.get(permission); 14696 if (bp != null) { 14697 usedPermissions.add(permission); 14698 } 14699 } 14700 } 14701 14702 PermissionsState permissionsState = su.getPermissionsState(); 14703 // Prune install permissions 14704 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14705 final int installPermCount = installPermStates.size(); 14706 for (int i = installPermCount - 1; i >= 0; i--) { 14707 PermissionState permissionState = installPermStates.get(i); 14708 if (!usedPermissions.contains(permissionState.getName())) { 14709 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14710 if (bp != null) { 14711 permissionsState.revokeInstallPermission(bp); 14712 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14713 PackageManager.MASK_PERMISSION_FLAGS, 0); 14714 } 14715 } 14716 } 14717 14718 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14719 14720 // Prune runtime permissions 14721 for (int userId : allUserIds) { 14722 List<PermissionState> runtimePermStates = permissionsState 14723 .getRuntimePermissionStates(userId); 14724 final int runtimePermCount = runtimePermStates.size(); 14725 for (int i = runtimePermCount - 1; i >= 0; i--) { 14726 PermissionState permissionState = runtimePermStates.get(i); 14727 if (!usedPermissions.contains(permissionState.getName())) { 14728 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14729 if (bp != null) { 14730 permissionsState.revokeRuntimePermission(bp, userId); 14731 permissionsState.updatePermissionFlags(bp, userId, 14732 PackageManager.MASK_PERMISSION_FLAGS, 0); 14733 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14734 runtimePermissionChangedUserIds, userId); 14735 } 14736 } 14737 } 14738 } 14739 14740 return runtimePermissionChangedUserIds; 14741 } 14742 14743 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14744 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14745 // Update the parent package setting 14746 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14747 res, user); 14748 // Update the child packages setting 14749 final int childCount = (newPackage.childPackages != null) 14750 ? newPackage.childPackages.size() : 0; 14751 for (int i = 0; i < childCount; i++) { 14752 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14753 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14754 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14755 childRes.origUsers, childRes, user); 14756 } 14757 } 14758 14759 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14760 String installerPackageName, int[] allUsers, int[] installedForUsers, 14761 PackageInstalledInfo res, UserHandle user) { 14762 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14763 14764 String pkgName = newPackage.packageName; 14765 synchronized (mPackages) { 14766 //write settings. the installStatus will be incomplete at this stage. 14767 //note that the new package setting would have already been 14768 //added to mPackages. It hasn't been persisted yet. 14769 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14770 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14771 mSettings.writeLPr(); 14772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14773 } 14774 14775 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14776 synchronized (mPackages) { 14777 updatePermissionsLPw(newPackage.packageName, newPackage, 14778 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14779 ? UPDATE_PERMISSIONS_ALL : 0)); 14780 // For system-bundled packages, we assume that installing an upgraded version 14781 // of the package implies that the user actually wants to run that new code, 14782 // so we enable the package. 14783 PackageSetting ps = mSettings.mPackages.get(pkgName); 14784 final int userId = user.getIdentifier(); 14785 if (ps != null) { 14786 if (isSystemApp(newPackage)) { 14787 if (DEBUG_INSTALL) { 14788 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14789 } 14790 // Enable system package for requested users 14791 if (res.origUsers != null) { 14792 for (int origUserId : res.origUsers) { 14793 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14794 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14795 origUserId, installerPackageName); 14796 } 14797 } 14798 } 14799 // Also convey the prior install/uninstall state 14800 if (allUsers != null && installedForUsers != null) { 14801 for (int currentUserId : allUsers) { 14802 final boolean installed = ArrayUtils.contains( 14803 installedForUsers, currentUserId); 14804 if (DEBUG_INSTALL) { 14805 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14806 } 14807 ps.setInstalled(installed, currentUserId); 14808 } 14809 // these install state changes will be persisted in the 14810 // upcoming call to mSettings.writeLPr(). 14811 } 14812 } 14813 // It's implied that when a user requests installation, they want the app to be 14814 // installed and enabled. 14815 if (userId != UserHandle.USER_ALL) { 14816 ps.setInstalled(true, userId); 14817 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14818 } 14819 } 14820 res.name = pkgName; 14821 res.uid = newPackage.applicationInfo.uid; 14822 res.pkg = newPackage; 14823 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14824 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14825 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14826 //to update install status 14827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14828 mSettings.writeLPr(); 14829 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14830 } 14831 14832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14833 } 14834 14835 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14836 try { 14837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14838 installPackageLI(args, res); 14839 } finally { 14840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14841 } 14842 } 14843 14844 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14845 final int installFlags = args.installFlags; 14846 final String installerPackageName = args.installerPackageName; 14847 final String volumeUuid = args.volumeUuid; 14848 final File tmpPackageFile = new File(args.getCodePath()); 14849 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14850 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14851 || (args.volumeUuid != null)); 14852 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14853 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14854 boolean replace = false; 14855 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14856 if (args.move != null) { 14857 // moving a complete application; perform an initial scan on the new install location 14858 scanFlags |= SCAN_INITIAL; 14859 } 14860 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14861 scanFlags |= SCAN_DONT_KILL_APP; 14862 } 14863 14864 // Result object to be returned 14865 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14866 14867 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14868 14869 // Sanity check 14870 if (ephemeral && (forwardLocked || onExternal)) { 14871 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14872 + " external=" + onExternal); 14873 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14874 return; 14875 } 14876 14877 // Retrieve PackageSettings and parse package 14878 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14879 | PackageParser.PARSE_ENFORCE_CODE 14880 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14881 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14882 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14883 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14884 PackageParser pp = new PackageParser(); 14885 pp.setSeparateProcesses(mSeparateProcesses); 14886 pp.setDisplayMetrics(mMetrics); 14887 14888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14889 final PackageParser.Package pkg; 14890 try { 14891 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14892 } catch (PackageParserException e) { 14893 res.setError("Failed parse during installPackageLI", e); 14894 return; 14895 } finally { 14896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14897 } 14898 14899 // If we are installing a clustered package add results for the children 14900 if (pkg.childPackages != null) { 14901 synchronized (mPackages) { 14902 final int childCount = pkg.childPackages.size(); 14903 for (int i = 0; i < childCount; i++) { 14904 PackageParser.Package childPkg = pkg.childPackages.get(i); 14905 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14906 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14907 childRes.pkg = childPkg; 14908 childRes.name = childPkg.packageName; 14909 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14910 if (childPs != null) { 14911 childRes.origUsers = childPs.queryInstalledUsers( 14912 sUserManager.getUserIds(), true); 14913 } 14914 if ((mPackages.containsKey(childPkg.packageName))) { 14915 childRes.removedInfo = new PackageRemovedInfo(); 14916 childRes.removedInfo.removedPackage = childPkg.packageName; 14917 } 14918 if (res.addedChildPackages == null) { 14919 res.addedChildPackages = new ArrayMap<>(); 14920 } 14921 res.addedChildPackages.put(childPkg.packageName, childRes); 14922 } 14923 } 14924 } 14925 14926 // If package doesn't declare API override, mark that we have an install 14927 // time CPU ABI override. 14928 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14929 pkg.cpuAbiOverride = args.abiOverride; 14930 } 14931 14932 String pkgName = res.name = pkg.packageName; 14933 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14934 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14935 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14936 return; 14937 } 14938 } 14939 14940 try { 14941 // either use what we've been given or parse directly from the APK 14942 if (args.certificates != null) { 14943 try { 14944 PackageParser.populateCertificates(pkg, args.certificates); 14945 } catch (PackageParserException e) { 14946 // there was something wrong with the certificates we were given; 14947 // try to pull them from the APK 14948 PackageParser.collectCertificates(pkg, parseFlags); 14949 } 14950 } else { 14951 PackageParser.collectCertificates(pkg, parseFlags); 14952 } 14953 } catch (PackageParserException e) { 14954 res.setError("Failed collect during installPackageLI", e); 14955 return; 14956 } 14957 14958 // Get rid of all references to package scan path via parser. 14959 pp = null; 14960 String oldCodePath = null; 14961 boolean systemApp = false; 14962 synchronized (mPackages) { 14963 // Check if installing already existing package 14964 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14965 String oldName = mSettings.mRenamedPackages.get(pkgName); 14966 if (pkg.mOriginalPackages != null 14967 && pkg.mOriginalPackages.contains(oldName) 14968 && mPackages.containsKey(oldName)) { 14969 // This package is derived from an original package, 14970 // and this device has been updating from that original 14971 // name. We must continue using the original name, so 14972 // rename the new package here. 14973 pkg.setPackageName(oldName); 14974 pkgName = pkg.packageName; 14975 replace = true; 14976 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14977 + oldName + " pkgName=" + pkgName); 14978 } else if (mPackages.containsKey(pkgName)) { 14979 // This package, under its official name, already exists 14980 // on the device; we should replace it. 14981 replace = true; 14982 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14983 } 14984 14985 // Child packages are installed through the parent package 14986 if (pkg.parentPackage != null) { 14987 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14988 "Package " + pkg.packageName + " is child of package " 14989 + pkg.parentPackage.parentPackage + ". Child packages " 14990 + "can be updated only through the parent package."); 14991 return; 14992 } 14993 14994 if (replace) { 14995 // Prevent apps opting out from runtime permissions 14996 PackageParser.Package oldPackage = mPackages.get(pkgName); 14997 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14998 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14999 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15000 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15001 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15002 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15003 + " doesn't support runtime permissions but the old" 15004 + " target SDK " + oldTargetSdk + " does."); 15005 return; 15006 } 15007 15008 // Prevent installing of child packages 15009 if (oldPackage.parentPackage != null) { 15010 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15011 "Package " + pkg.packageName + " is child of package " 15012 + oldPackage.parentPackage + ". Child packages " 15013 + "can be updated only through the parent package."); 15014 return; 15015 } 15016 } 15017 } 15018 15019 PackageSetting ps = mSettings.mPackages.get(pkgName); 15020 if (ps != null) { 15021 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15022 15023 // Quick sanity check that we're signed correctly if updating; 15024 // we'll check this again later when scanning, but we want to 15025 // bail early here before tripping over redefined permissions. 15026 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15027 if (!checkUpgradeKeySetLP(ps, pkg)) { 15028 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15029 + pkg.packageName + " upgrade keys do not match the " 15030 + "previously installed version"); 15031 return; 15032 } 15033 } else { 15034 try { 15035 verifySignaturesLP(ps, pkg); 15036 } catch (PackageManagerException e) { 15037 res.setError(e.error, e.getMessage()); 15038 return; 15039 } 15040 } 15041 15042 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15043 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15044 systemApp = (ps.pkg.applicationInfo.flags & 15045 ApplicationInfo.FLAG_SYSTEM) != 0; 15046 } 15047 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15048 } 15049 15050 // Check whether the newly-scanned package wants to define an already-defined perm 15051 int N = pkg.permissions.size(); 15052 for (int i = N-1; i >= 0; i--) { 15053 PackageParser.Permission perm = pkg.permissions.get(i); 15054 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15055 if (bp != null) { 15056 // If the defining package is signed with our cert, it's okay. This 15057 // also includes the "updating the same package" case, of course. 15058 // "updating same package" could also involve key-rotation. 15059 final boolean sigsOk; 15060 if (bp.sourcePackage.equals(pkg.packageName) 15061 && (bp.packageSetting instanceof PackageSetting) 15062 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15063 scanFlags))) { 15064 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15065 } else { 15066 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15067 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15068 } 15069 if (!sigsOk) { 15070 // If the owning package is the system itself, we log but allow 15071 // install to proceed; we fail the install on all other permission 15072 // redefinitions. 15073 if (!bp.sourcePackage.equals("android")) { 15074 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15075 + pkg.packageName + " attempting to redeclare permission " 15076 + perm.info.name + " already owned by " + bp.sourcePackage); 15077 res.origPermission = perm.info.name; 15078 res.origPackage = bp.sourcePackage; 15079 return; 15080 } else { 15081 Slog.w(TAG, "Package " + pkg.packageName 15082 + " attempting to redeclare system permission " 15083 + perm.info.name + "; ignoring new declaration"); 15084 pkg.permissions.remove(i); 15085 } 15086 } 15087 } 15088 } 15089 } 15090 15091 if (systemApp) { 15092 if (onExternal) { 15093 // Abort update; system app can't be replaced with app on sdcard 15094 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15095 "Cannot install updates to system apps on sdcard"); 15096 return; 15097 } else if (ephemeral) { 15098 // Abort update; system app can't be replaced with an ephemeral app 15099 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15100 "Cannot update a system app with an ephemeral app"); 15101 return; 15102 } 15103 } 15104 15105 if (args.move != null) { 15106 // We did an in-place move, so dex is ready to roll 15107 scanFlags |= SCAN_NO_DEX; 15108 scanFlags |= SCAN_MOVE; 15109 15110 synchronized (mPackages) { 15111 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15112 if (ps == null) { 15113 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15114 "Missing settings for moved package " + pkgName); 15115 } 15116 15117 // We moved the entire application as-is, so bring over the 15118 // previously derived ABI information. 15119 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15120 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15121 } 15122 15123 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15124 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15125 scanFlags |= SCAN_NO_DEX; 15126 15127 try { 15128 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15129 args.abiOverride : pkg.cpuAbiOverride); 15130 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15131 true /* extract libs */); 15132 } catch (PackageManagerException pme) { 15133 Slog.e(TAG, "Error deriving application ABI", pme); 15134 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15135 return; 15136 } 15137 15138 // Shared libraries for the package need to be updated. 15139 synchronized (mPackages) { 15140 try { 15141 updateSharedLibrariesLPw(pkg, null); 15142 } catch (PackageManagerException e) { 15143 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15144 } 15145 } 15146 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15147 // Do not run PackageDexOptimizer through the local performDexOpt 15148 // method because `pkg` may not be in `mPackages` yet. 15149 // 15150 // Also, don't fail application installs if the dexopt step fails. 15151 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15152 null /* instructionSets */, false /* checkProfiles */, 15153 getCompilerFilterForReason(REASON_INSTALL)); 15154 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15155 15156 // Notify BackgroundDexOptService that the package has been changed. 15157 // If this is an update of a package which used to fail to compile, 15158 // BDOS will remove it from its blacklist. 15159 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15160 } 15161 15162 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15163 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15164 return; 15165 } 15166 15167 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15168 15169 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15170 "installPackageLI")) { 15171 if (replace) { 15172 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15173 installerPackageName, res); 15174 } else { 15175 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15176 args.user, installerPackageName, volumeUuid, res); 15177 } 15178 } 15179 synchronized (mPackages) { 15180 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15181 if (ps != null) { 15182 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15183 } 15184 15185 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15186 for (int i = 0; i < childCount; i++) { 15187 PackageParser.Package childPkg = pkg.childPackages.get(i); 15188 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15189 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15190 if (childPs != null) { 15191 childRes.newUsers = childPs.queryInstalledUsers( 15192 sUserManager.getUserIds(), true); 15193 } 15194 } 15195 } 15196 } 15197 15198 private void startIntentFilterVerifications(int userId, boolean replacing, 15199 PackageParser.Package pkg) { 15200 if (mIntentFilterVerifierComponent == null) { 15201 Slog.w(TAG, "No IntentFilter verification will not be done as " 15202 + "there is no IntentFilterVerifier available!"); 15203 return; 15204 } 15205 15206 final int verifierUid = getPackageUid( 15207 mIntentFilterVerifierComponent.getPackageName(), 15208 MATCH_DEBUG_TRIAGED_MISSING, 15209 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15210 15211 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15212 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15213 mHandler.sendMessage(msg); 15214 15215 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15216 for (int i = 0; i < childCount; i++) { 15217 PackageParser.Package childPkg = pkg.childPackages.get(i); 15218 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15219 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15220 mHandler.sendMessage(msg); 15221 } 15222 } 15223 15224 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15225 PackageParser.Package pkg) { 15226 int size = pkg.activities.size(); 15227 if (size == 0) { 15228 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15229 "No activity, so no need to verify any IntentFilter!"); 15230 return; 15231 } 15232 15233 final boolean hasDomainURLs = hasDomainURLs(pkg); 15234 if (!hasDomainURLs) { 15235 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15236 "No domain URLs, so no need to verify any IntentFilter!"); 15237 return; 15238 } 15239 15240 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15241 + " if any IntentFilter from the " + size 15242 + " Activities needs verification ..."); 15243 15244 int count = 0; 15245 final String packageName = pkg.packageName; 15246 15247 synchronized (mPackages) { 15248 // If this is a new install and we see that we've already run verification for this 15249 // package, we have nothing to do: it means the state was restored from backup. 15250 if (!replacing) { 15251 IntentFilterVerificationInfo ivi = 15252 mSettings.getIntentFilterVerificationLPr(packageName); 15253 if (ivi != null) { 15254 if (DEBUG_DOMAIN_VERIFICATION) { 15255 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15256 + ivi.getStatusString()); 15257 } 15258 return; 15259 } 15260 } 15261 15262 // If any filters need to be verified, then all need to be. 15263 boolean needToVerify = false; 15264 for (PackageParser.Activity a : pkg.activities) { 15265 for (ActivityIntentInfo filter : a.intents) { 15266 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15267 if (DEBUG_DOMAIN_VERIFICATION) { 15268 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15269 } 15270 needToVerify = true; 15271 break; 15272 } 15273 } 15274 } 15275 15276 if (needToVerify) { 15277 final int verificationId = mIntentFilterVerificationToken++; 15278 for (PackageParser.Activity a : pkg.activities) { 15279 for (ActivityIntentInfo filter : a.intents) { 15280 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15281 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15282 "Verification needed for IntentFilter:" + filter.toString()); 15283 mIntentFilterVerifier.addOneIntentFilterVerification( 15284 verifierUid, userId, verificationId, filter, packageName); 15285 count++; 15286 } 15287 } 15288 } 15289 } 15290 } 15291 15292 if (count > 0) { 15293 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15294 + " IntentFilter verification" + (count > 1 ? "s" : "") 15295 + " for userId:" + userId); 15296 mIntentFilterVerifier.startVerifications(userId); 15297 } else { 15298 if (DEBUG_DOMAIN_VERIFICATION) { 15299 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15300 } 15301 } 15302 } 15303 15304 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15305 final ComponentName cn = filter.activity.getComponentName(); 15306 final String packageName = cn.getPackageName(); 15307 15308 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15309 packageName); 15310 if (ivi == null) { 15311 return true; 15312 } 15313 int status = ivi.getStatus(); 15314 switch (status) { 15315 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15316 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15317 return true; 15318 15319 default: 15320 // Nothing to do 15321 return false; 15322 } 15323 } 15324 15325 private static boolean isMultiArch(ApplicationInfo info) { 15326 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15327 } 15328 15329 private static boolean isExternal(PackageParser.Package pkg) { 15330 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15331 } 15332 15333 private static boolean isExternal(PackageSetting ps) { 15334 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15335 } 15336 15337 private static boolean isEphemeral(PackageParser.Package pkg) { 15338 return pkg.applicationInfo.isEphemeralApp(); 15339 } 15340 15341 private static boolean isEphemeral(PackageSetting ps) { 15342 return ps.pkg != null && isEphemeral(ps.pkg); 15343 } 15344 15345 private static boolean isSystemApp(PackageParser.Package pkg) { 15346 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15347 } 15348 15349 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15350 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15351 } 15352 15353 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15354 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15355 } 15356 15357 private static boolean isSystemApp(PackageSetting ps) { 15358 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15359 } 15360 15361 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15362 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15363 } 15364 15365 private int packageFlagsToInstallFlags(PackageSetting ps) { 15366 int installFlags = 0; 15367 if (isEphemeral(ps)) { 15368 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15369 } 15370 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15371 // This existing package was an external ASEC install when we have 15372 // the external flag without a UUID 15373 installFlags |= PackageManager.INSTALL_EXTERNAL; 15374 } 15375 if (ps.isForwardLocked()) { 15376 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15377 } 15378 return installFlags; 15379 } 15380 15381 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15382 if (isExternal(pkg)) { 15383 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15384 return StorageManager.UUID_PRIMARY_PHYSICAL; 15385 } else { 15386 return pkg.volumeUuid; 15387 } 15388 } else { 15389 return StorageManager.UUID_PRIVATE_INTERNAL; 15390 } 15391 } 15392 15393 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15394 if (isExternal(pkg)) { 15395 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15396 return mSettings.getExternalVersion(); 15397 } else { 15398 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15399 } 15400 } else { 15401 return mSettings.getInternalVersion(); 15402 } 15403 } 15404 15405 private void deleteTempPackageFiles() { 15406 final FilenameFilter filter = new FilenameFilter() { 15407 public boolean accept(File dir, String name) { 15408 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15409 } 15410 }; 15411 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15412 file.delete(); 15413 } 15414 } 15415 15416 @Override 15417 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15418 int flags) { 15419 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15420 flags); 15421 } 15422 15423 @Override 15424 public void deletePackage(final String packageName, 15425 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15426 mContext.enforceCallingOrSelfPermission( 15427 android.Manifest.permission.DELETE_PACKAGES, null); 15428 Preconditions.checkNotNull(packageName); 15429 Preconditions.checkNotNull(observer); 15430 final int uid = Binder.getCallingUid(); 15431 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15432 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15433 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15434 mContext.enforceCallingOrSelfPermission( 15435 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15436 "deletePackage for user " + userId); 15437 } 15438 15439 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15440 try { 15441 observer.onPackageDeleted(packageName, 15442 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15443 } catch (RemoteException re) { 15444 } 15445 return; 15446 } 15447 15448 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15449 try { 15450 observer.onPackageDeleted(packageName, 15451 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15452 } catch (RemoteException re) { 15453 } 15454 return; 15455 } 15456 15457 if (DEBUG_REMOVE) { 15458 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15459 + " deleteAllUsers: " + deleteAllUsers ); 15460 } 15461 // Queue up an async operation since the package deletion may take a little while. 15462 mHandler.post(new Runnable() { 15463 public void run() { 15464 mHandler.removeCallbacks(this); 15465 int returnCode; 15466 if (!deleteAllUsers) { 15467 returnCode = deletePackageX(packageName, userId, deleteFlags); 15468 } else { 15469 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15470 // If nobody is blocking uninstall, proceed with delete for all users 15471 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15472 returnCode = deletePackageX(packageName, userId, deleteFlags); 15473 } else { 15474 // Otherwise uninstall individually for users with blockUninstalls=false 15475 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15476 for (int userId : users) { 15477 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15478 returnCode = deletePackageX(packageName, userId, userFlags); 15479 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15480 Slog.w(TAG, "Package delete failed for user " + userId 15481 + ", returnCode " + returnCode); 15482 } 15483 } 15484 } 15485 // The app has only been marked uninstalled for certain users. 15486 // We still need to report that delete was blocked 15487 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15488 } 15489 } 15490 try { 15491 observer.onPackageDeleted(packageName, returnCode, null); 15492 } catch (RemoteException e) { 15493 Log.i(TAG, "Observer no longer exists."); 15494 } //end catch 15495 } //end run 15496 }); 15497 } 15498 15499 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15500 int[] result = EMPTY_INT_ARRAY; 15501 for (int userId : userIds) { 15502 if (getBlockUninstallForUser(packageName, userId)) { 15503 result = ArrayUtils.appendInt(result, userId); 15504 } 15505 } 15506 return result; 15507 } 15508 15509 @Override 15510 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15511 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15512 } 15513 15514 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15515 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15516 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15517 try { 15518 if (dpm != null) { 15519 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15520 /* callingUserOnly =*/ false); 15521 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15522 : deviceOwnerComponentName.getPackageName(); 15523 // Does the package contains the device owner? 15524 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15525 // this check is probably not needed, since DO should be registered as a device 15526 // admin on some user too. (Original bug for this: b/17657954) 15527 if (packageName.equals(deviceOwnerPackageName)) { 15528 return true; 15529 } 15530 // Does it contain a device admin for any user? 15531 int[] users; 15532 if (userId == UserHandle.USER_ALL) { 15533 users = sUserManager.getUserIds(); 15534 } else { 15535 users = new int[]{userId}; 15536 } 15537 for (int i = 0; i < users.length; ++i) { 15538 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15539 return true; 15540 } 15541 } 15542 } 15543 } catch (RemoteException e) { 15544 } 15545 return false; 15546 } 15547 15548 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15549 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15550 } 15551 15552 /** 15553 * This method is an internal method that could be get invoked either 15554 * to delete an installed package or to clean up a failed installation. 15555 * After deleting an installed package, a broadcast is sent to notify any 15556 * listeners that the package has been removed. For cleaning up a failed 15557 * installation, the broadcast is not necessary since the package's 15558 * installation wouldn't have sent the initial broadcast either 15559 * The key steps in deleting a package are 15560 * deleting the package information in internal structures like mPackages, 15561 * deleting the packages base directories through installd 15562 * updating mSettings to reflect current status 15563 * persisting settings for later use 15564 * sending a broadcast if necessary 15565 */ 15566 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15567 final PackageRemovedInfo info = new PackageRemovedInfo(); 15568 final boolean res; 15569 15570 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15571 ? UserHandle.USER_ALL : userId; 15572 15573 if (isPackageDeviceAdmin(packageName, removeUser)) { 15574 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15575 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15576 } 15577 15578 PackageSetting uninstalledPs = null; 15579 15580 // for the uninstall-updates case and restricted profiles, remember the per- 15581 // user handle installed state 15582 int[] allUsers; 15583 synchronized (mPackages) { 15584 uninstalledPs = mSettings.mPackages.get(packageName); 15585 if (uninstalledPs == null) { 15586 Slog.w(TAG, "Not removing non-existent package " + packageName); 15587 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15588 } 15589 allUsers = sUserManager.getUserIds(); 15590 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15591 } 15592 15593 final int freezeUser; 15594 if (isUpdatedSystemApp(uninstalledPs) 15595 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15596 // We're downgrading a system app, which will apply to all users, so 15597 // freeze them all during the downgrade 15598 freezeUser = UserHandle.USER_ALL; 15599 } else { 15600 freezeUser = removeUser; 15601 } 15602 15603 synchronized (mInstallLock) { 15604 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15605 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15606 deleteFlags, "deletePackageX")) { 15607 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15608 deleteFlags | REMOVE_CHATTY, info, true, null); 15609 } 15610 synchronized (mPackages) { 15611 if (res) { 15612 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15613 } 15614 } 15615 } 15616 15617 if (res) { 15618 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15619 info.sendPackageRemovedBroadcasts(killApp); 15620 info.sendSystemPackageUpdatedBroadcasts(); 15621 info.sendSystemPackageAppearedBroadcasts(); 15622 } 15623 // Force a gc here. 15624 Runtime.getRuntime().gc(); 15625 // Delete the resources here after sending the broadcast to let 15626 // other processes clean up before deleting resources. 15627 if (info.args != null) { 15628 synchronized (mInstallLock) { 15629 info.args.doPostDeleteLI(true); 15630 } 15631 } 15632 15633 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15634 } 15635 15636 class PackageRemovedInfo { 15637 String removedPackage; 15638 int uid = -1; 15639 int removedAppId = -1; 15640 int[] origUsers; 15641 int[] removedUsers = null; 15642 boolean isRemovedPackageSystemUpdate = false; 15643 boolean isUpdate; 15644 boolean dataRemoved; 15645 boolean removedForAllUsers; 15646 // Clean up resources deleted packages. 15647 InstallArgs args = null; 15648 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15649 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15650 15651 void sendPackageRemovedBroadcasts(boolean killApp) { 15652 sendPackageRemovedBroadcastInternal(killApp); 15653 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15654 for (int i = 0; i < childCount; i++) { 15655 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15656 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15657 } 15658 } 15659 15660 void sendSystemPackageUpdatedBroadcasts() { 15661 if (isRemovedPackageSystemUpdate) { 15662 sendSystemPackageUpdatedBroadcastsInternal(); 15663 final int childCount = (removedChildPackages != null) 15664 ? removedChildPackages.size() : 0; 15665 for (int i = 0; i < childCount; i++) { 15666 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15667 if (childInfo.isRemovedPackageSystemUpdate) { 15668 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15669 } 15670 } 15671 } 15672 } 15673 15674 void sendSystemPackageAppearedBroadcasts() { 15675 final int packageCount = (appearedChildPackages != null) 15676 ? appearedChildPackages.size() : 0; 15677 for (int i = 0; i < packageCount; i++) { 15678 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15679 for (int userId : installedInfo.newUsers) { 15680 sendPackageAddedForUser(installedInfo.name, true, 15681 UserHandle.getAppId(installedInfo.uid), userId); 15682 } 15683 } 15684 } 15685 15686 private void sendSystemPackageUpdatedBroadcastsInternal() { 15687 Bundle extras = new Bundle(2); 15688 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15689 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15690 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15691 extras, 0, null, null, null); 15692 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15693 extras, 0, null, null, null); 15694 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15695 null, 0, removedPackage, null, null); 15696 } 15697 15698 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15699 Bundle extras = new Bundle(2); 15700 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15701 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15702 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15703 if (isUpdate || isRemovedPackageSystemUpdate) { 15704 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15705 } 15706 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15707 if (removedPackage != null) { 15708 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15709 extras, 0, null, null, removedUsers); 15710 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15711 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15712 removedPackage, extras, 0, null, null, removedUsers); 15713 } 15714 } 15715 if (removedAppId >= 0) { 15716 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15717 removedUsers); 15718 } 15719 } 15720 } 15721 15722 /* 15723 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15724 * flag is not set, the data directory is removed as well. 15725 * make sure this flag is set for partially installed apps. If not its meaningless to 15726 * delete a partially installed application. 15727 */ 15728 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15729 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15730 String packageName = ps.name; 15731 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15732 // Retrieve object to delete permissions for shared user later on 15733 final PackageParser.Package deletedPkg; 15734 final PackageSetting deletedPs; 15735 // reader 15736 synchronized (mPackages) { 15737 deletedPkg = mPackages.get(packageName); 15738 deletedPs = mSettings.mPackages.get(packageName); 15739 if (outInfo != null) { 15740 outInfo.removedPackage = packageName; 15741 outInfo.removedUsers = deletedPs != null 15742 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15743 : null; 15744 } 15745 } 15746 15747 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15748 15749 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15750 final PackageParser.Package resolvedPkg; 15751 if (deletedPkg != null) { 15752 resolvedPkg = deletedPkg; 15753 } else { 15754 // We don't have a parsed package when it lives on an ejected 15755 // adopted storage device, so fake something together 15756 resolvedPkg = new PackageParser.Package(ps.name); 15757 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15758 } 15759 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15760 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15761 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15762 if (outInfo != null) { 15763 outInfo.dataRemoved = true; 15764 } 15765 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15766 } 15767 15768 // writer 15769 synchronized (mPackages) { 15770 if (deletedPs != null) { 15771 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15772 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15773 clearDefaultBrowserIfNeeded(packageName); 15774 if (outInfo != null) { 15775 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15776 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15777 } 15778 updatePermissionsLPw(deletedPs.name, null, 0); 15779 if (deletedPs.sharedUser != null) { 15780 // Remove permissions associated with package. Since runtime 15781 // permissions are per user we have to kill the removed package 15782 // or packages running under the shared user of the removed 15783 // package if revoking the permissions requested only by the removed 15784 // package is successful and this causes a change in gids. 15785 for (int userId : UserManagerService.getInstance().getUserIds()) { 15786 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15787 userId); 15788 if (userIdToKill == UserHandle.USER_ALL 15789 || userIdToKill >= UserHandle.USER_SYSTEM) { 15790 // If gids changed for this user, kill all affected packages. 15791 mHandler.post(new Runnable() { 15792 @Override 15793 public void run() { 15794 // This has to happen with no lock held. 15795 killApplication(deletedPs.name, deletedPs.appId, 15796 KILL_APP_REASON_GIDS_CHANGED); 15797 } 15798 }); 15799 break; 15800 } 15801 } 15802 } 15803 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15804 } 15805 // make sure to preserve per-user disabled state if this removal was just 15806 // a downgrade of a system app to the factory package 15807 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15808 if (DEBUG_REMOVE) { 15809 Slog.d(TAG, "Propagating install state across downgrade"); 15810 } 15811 for (int userId : allUserHandles) { 15812 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15813 if (DEBUG_REMOVE) { 15814 Slog.d(TAG, " user " + userId + " => " + installed); 15815 } 15816 ps.setInstalled(installed, userId); 15817 } 15818 } 15819 } 15820 // can downgrade to reader 15821 if (writeSettings) { 15822 // Save settings now 15823 mSettings.writeLPr(); 15824 } 15825 } 15826 if (outInfo != null) { 15827 // A user ID was deleted here. Go through all users and remove it 15828 // from KeyStore. 15829 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15830 } 15831 } 15832 15833 static boolean locationIsPrivileged(File path) { 15834 try { 15835 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15836 .getCanonicalPath(); 15837 return path.getCanonicalPath().startsWith(privilegedAppDir); 15838 } catch (IOException e) { 15839 Slog.e(TAG, "Unable to access code path " + path); 15840 } 15841 return false; 15842 } 15843 15844 /* 15845 * Tries to delete system package. 15846 */ 15847 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15848 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15849 boolean writeSettings) { 15850 if (deletedPs.parentPackageName != null) { 15851 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15852 return false; 15853 } 15854 15855 final boolean applyUserRestrictions 15856 = (allUserHandles != null) && (outInfo.origUsers != null); 15857 final PackageSetting disabledPs; 15858 // Confirm if the system package has been updated 15859 // An updated system app can be deleted. This will also have to restore 15860 // the system pkg from system partition 15861 // reader 15862 synchronized (mPackages) { 15863 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15864 } 15865 15866 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15867 + " disabledPs=" + disabledPs); 15868 15869 if (disabledPs == null) { 15870 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15871 return false; 15872 } else if (DEBUG_REMOVE) { 15873 Slog.d(TAG, "Deleting system pkg from data partition"); 15874 } 15875 15876 if (DEBUG_REMOVE) { 15877 if (applyUserRestrictions) { 15878 Slog.d(TAG, "Remembering install states:"); 15879 for (int userId : allUserHandles) { 15880 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15881 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15882 } 15883 } 15884 } 15885 15886 // Delete the updated package 15887 outInfo.isRemovedPackageSystemUpdate = true; 15888 if (outInfo.removedChildPackages != null) { 15889 final int childCount = (deletedPs.childPackageNames != null) 15890 ? deletedPs.childPackageNames.size() : 0; 15891 for (int i = 0; i < childCount; i++) { 15892 String childPackageName = deletedPs.childPackageNames.get(i); 15893 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15894 .contains(childPackageName)) { 15895 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15896 childPackageName); 15897 if (childInfo != null) { 15898 childInfo.isRemovedPackageSystemUpdate = true; 15899 } 15900 } 15901 } 15902 } 15903 15904 if (disabledPs.versionCode < deletedPs.versionCode) { 15905 // Delete data for downgrades 15906 flags &= ~PackageManager.DELETE_KEEP_DATA; 15907 } else { 15908 // Preserve data by setting flag 15909 flags |= PackageManager.DELETE_KEEP_DATA; 15910 } 15911 15912 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15913 outInfo, writeSettings, disabledPs.pkg); 15914 if (!ret) { 15915 return false; 15916 } 15917 15918 // writer 15919 synchronized (mPackages) { 15920 // Reinstate the old system package 15921 enableSystemPackageLPw(disabledPs.pkg); 15922 // Remove any native libraries from the upgraded package. 15923 removeNativeBinariesLI(deletedPs); 15924 } 15925 15926 // Install the system package 15927 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15928 int parseFlags = mDefParseFlags 15929 | PackageParser.PARSE_MUST_BE_APK 15930 | PackageParser.PARSE_IS_SYSTEM 15931 | PackageParser.PARSE_IS_SYSTEM_DIR; 15932 if (locationIsPrivileged(disabledPs.codePath)) { 15933 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15934 } 15935 15936 final PackageParser.Package newPkg; 15937 try { 15938 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15939 } catch (PackageManagerException e) { 15940 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15941 + e.getMessage()); 15942 return false; 15943 } 15944 15945 prepareAppDataAfterInstallLIF(newPkg); 15946 15947 // writer 15948 synchronized (mPackages) { 15949 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15950 15951 // Propagate the permissions state as we do not want to drop on the floor 15952 // runtime permissions. The update permissions method below will take 15953 // care of removing obsolete permissions and grant install permissions. 15954 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15955 updatePermissionsLPw(newPkg.packageName, newPkg, 15956 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15957 15958 if (applyUserRestrictions) { 15959 if (DEBUG_REMOVE) { 15960 Slog.d(TAG, "Propagating install state across reinstall"); 15961 } 15962 for (int userId : allUserHandles) { 15963 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15964 if (DEBUG_REMOVE) { 15965 Slog.d(TAG, " user " + userId + " => " + installed); 15966 } 15967 ps.setInstalled(installed, userId); 15968 15969 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15970 } 15971 // Regardless of writeSettings we need to ensure that this restriction 15972 // state propagation is persisted 15973 mSettings.writeAllUsersPackageRestrictionsLPr(); 15974 } 15975 // can downgrade to reader here 15976 if (writeSettings) { 15977 mSettings.writeLPr(); 15978 } 15979 } 15980 return true; 15981 } 15982 15983 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15984 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15985 PackageRemovedInfo outInfo, boolean writeSettings, 15986 PackageParser.Package replacingPackage) { 15987 synchronized (mPackages) { 15988 if (outInfo != null) { 15989 outInfo.uid = ps.appId; 15990 } 15991 15992 if (outInfo != null && outInfo.removedChildPackages != null) { 15993 final int childCount = (ps.childPackageNames != null) 15994 ? ps.childPackageNames.size() : 0; 15995 for (int i = 0; i < childCount; i++) { 15996 String childPackageName = ps.childPackageNames.get(i); 15997 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15998 if (childPs == null) { 15999 return false; 16000 } 16001 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16002 childPackageName); 16003 if (childInfo != null) { 16004 childInfo.uid = childPs.appId; 16005 } 16006 } 16007 } 16008 } 16009 16010 // Delete package data from internal structures and also remove data if flag is set 16011 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16012 16013 // Delete the child packages data 16014 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16015 for (int i = 0; i < childCount; i++) { 16016 PackageSetting childPs; 16017 synchronized (mPackages) { 16018 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16019 } 16020 if (childPs != null) { 16021 PackageRemovedInfo childOutInfo = (outInfo != null 16022 && outInfo.removedChildPackages != null) 16023 ? outInfo.removedChildPackages.get(childPs.name) : null; 16024 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16025 && (replacingPackage != null 16026 && !replacingPackage.hasChildPackage(childPs.name)) 16027 ? flags & ~DELETE_KEEP_DATA : flags; 16028 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16029 deleteFlags, writeSettings); 16030 } 16031 } 16032 16033 // Delete application code and resources only for parent packages 16034 if (ps.parentPackageName == null) { 16035 if (deleteCodeAndResources && (outInfo != null)) { 16036 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16037 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16038 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16039 } 16040 } 16041 16042 return true; 16043 } 16044 16045 @Override 16046 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16047 int userId) { 16048 mContext.enforceCallingOrSelfPermission( 16049 android.Manifest.permission.DELETE_PACKAGES, null); 16050 synchronized (mPackages) { 16051 PackageSetting ps = mSettings.mPackages.get(packageName); 16052 if (ps == null) { 16053 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16054 return false; 16055 } 16056 if (!ps.getInstalled(userId)) { 16057 // Can't block uninstall for an app that is not installed or enabled. 16058 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16059 return false; 16060 } 16061 ps.setBlockUninstall(blockUninstall, userId); 16062 mSettings.writePackageRestrictionsLPr(userId); 16063 } 16064 return true; 16065 } 16066 16067 @Override 16068 public boolean getBlockUninstallForUser(String packageName, int userId) { 16069 synchronized (mPackages) { 16070 PackageSetting ps = mSettings.mPackages.get(packageName); 16071 if (ps == null) { 16072 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16073 return false; 16074 } 16075 return ps.getBlockUninstall(userId); 16076 } 16077 } 16078 16079 @Override 16080 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16081 int callingUid = Binder.getCallingUid(); 16082 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16083 throw new SecurityException( 16084 "setRequiredForSystemUser can only be run by the system or root"); 16085 } 16086 synchronized (mPackages) { 16087 PackageSetting ps = mSettings.mPackages.get(packageName); 16088 if (ps == null) { 16089 Log.w(TAG, "Package doesn't exist: " + packageName); 16090 return false; 16091 } 16092 if (systemUserApp) { 16093 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16094 } else { 16095 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16096 } 16097 mSettings.writeLPr(); 16098 } 16099 return true; 16100 } 16101 16102 /* 16103 * This method handles package deletion in general 16104 */ 16105 private boolean deletePackageLIF(String packageName, UserHandle user, 16106 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16107 PackageRemovedInfo outInfo, boolean writeSettings, 16108 PackageParser.Package replacingPackage) { 16109 if (packageName == null) { 16110 Slog.w(TAG, "Attempt to delete null packageName."); 16111 return false; 16112 } 16113 16114 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16115 16116 PackageSetting ps; 16117 16118 synchronized (mPackages) { 16119 ps = mSettings.mPackages.get(packageName); 16120 if (ps == null) { 16121 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16122 return false; 16123 } 16124 16125 if (ps.parentPackageName != null && (!isSystemApp(ps) 16126 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16127 if (DEBUG_REMOVE) { 16128 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16129 + ((user == null) ? UserHandle.USER_ALL : user)); 16130 } 16131 final int removedUserId = (user != null) ? user.getIdentifier() 16132 : UserHandle.USER_ALL; 16133 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16134 return false; 16135 } 16136 markPackageUninstalledForUserLPw(ps, user); 16137 scheduleWritePackageRestrictionsLocked(user); 16138 return true; 16139 } 16140 } 16141 16142 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16143 && user.getIdentifier() != UserHandle.USER_ALL)) { 16144 // The caller is asking that the package only be deleted for a single 16145 // user. To do this, we just mark its uninstalled state and delete 16146 // its data. If this is a system app, we only allow this to happen if 16147 // they have set the special DELETE_SYSTEM_APP which requests different 16148 // semantics than normal for uninstalling system apps. 16149 markPackageUninstalledForUserLPw(ps, user); 16150 16151 if (!isSystemApp(ps)) { 16152 // Do not uninstall the APK if an app should be cached 16153 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16154 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16155 // Other user still have this package installed, so all 16156 // we need to do is clear this user's data and save that 16157 // it is uninstalled. 16158 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16159 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16160 return false; 16161 } 16162 scheduleWritePackageRestrictionsLocked(user); 16163 return true; 16164 } else { 16165 // We need to set it back to 'installed' so the uninstall 16166 // broadcasts will be sent correctly. 16167 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16168 ps.setInstalled(true, user.getIdentifier()); 16169 } 16170 } else { 16171 // This is a system app, so we assume that the 16172 // other users still have this package installed, so all 16173 // we need to do is clear this user's data and save that 16174 // it is uninstalled. 16175 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16176 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16177 return false; 16178 } 16179 scheduleWritePackageRestrictionsLocked(user); 16180 return true; 16181 } 16182 } 16183 16184 // If we are deleting a composite package for all users, keep track 16185 // of result for each child. 16186 if (ps.childPackageNames != null && outInfo != null) { 16187 synchronized (mPackages) { 16188 final int childCount = ps.childPackageNames.size(); 16189 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16190 for (int i = 0; i < childCount; i++) { 16191 String childPackageName = ps.childPackageNames.get(i); 16192 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16193 childInfo.removedPackage = childPackageName; 16194 outInfo.removedChildPackages.put(childPackageName, childInfo); 16195 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16196 if (childPs != null) { 16197 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16198 } 16199 } 16200 } 16201 } 16202 16203 boolean ret = false; 16204 if (isSystemApp(ps)) { 16205 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16206 // When an updated system application is deleted we delete the existing resources 16207 // as well and fall back to existing code in system partition 16208 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16209 } else { 16210 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16211 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16212 outInfo, writeSettings, replacingPackage); 16213 } 16214 16215 // Take a note whether we deleted the package for all users 16216 if (outInfo != null) { 16217 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16218 if (outInfo.removedChildPackages != null) { 16219 synchronized (mPackages) { 16220 final int childCount = outInfo.removedChildPackages.size(); 16221 for (int i = 0; i < childCount; i++) { 16222 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16223 if (childInfo != null) { 16224 childInfo.removedForAllUsers = mPackages.get( 16225 childInfo.removedPackage) == null; 16226 } 16227 } 16228 } 16229 } 16230 // If we uninstalled an update to a system app there may be some 16231 // child packages that appeared as they are declared in the system 16232 // app but were not declared in the update. 16233 if (isSystemApp(ps)) { 16234 synchronized (mPackages) { 16235 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16236 final int childCount = (updatedPs.childPackageNames != null) 16237 ? updatedPs.childPackageNames.size() : 0; 16238 for (int i = 0; i < childCount; i++) { 16239 String childPackageName = updatedPs.childPackageNames.get(i); 16240 if (outInfo.removedChildPackages == null 16241 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16242 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16243 if (childPs == null) { 16244 continue; 16245 } 16246 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16247 installRes.name = childPackageName; 16248 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16249 installRes.pkg = mPackages.get(childPackageName); 16250 installRes.uid = childPs.pkg.applicationInfo.uid; 16251 if (outInfo.appearedChildPackages == null) { 16252 outInfo.appearedChildPackages = new ArrayMap<>(); 16253 } 16254 outInfo.appearedChildPackages.put(childPackageName, installRes); 16255 } 16256 } 16257 } 16258 } 16259 } 16260 16261 return ret; 16262 } 16263 16264 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16265 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16266 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16267 for (int nextUserId : userIds) { 16268 if (DEBUG_REMOVE) { 16269 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16270 } 16271 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16272 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16273 false /*hidden*/, false /*suspended*/, null, null, null, 16274 false /*blockUninstall*/, 16275 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16276 } 16277 } 16278 16279 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16280 PackageRemovedInfo outInfo) { 16281 final PackageParser.Package pkg; 16282 synchronized (mPackages) { 16283 pkg = mPackages.get(ps.name); 16284 } 16285 16286 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16287 : new int[] {userId}; 16288 for (int nextUserId : userIds) { 16289 if (DEBUG_REMOVE) { 16290 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16291 + nextUserId); 16292 } 16293 16294 destroyAppDataLIF(pkg, userId, 16295 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16296 destroyAppProfilesLIF(pkg, userId); 16297 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16298 schedulePackageCleaning(ps.name, nextUserId, false); 16299 synchronized (mPackages) { 16300 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16301 scheduleWritePackageRestrictionsLocked(nextUserId); 16302 } 16303 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16304 } 16305 } 16306 16307 if (outInfo != null) { 16308 outInfo.removedPackage = ps.name; 16309 outInfo.removedAppId = ps.appId; 16310 outInfo.removedUsers = userIds; 16311 } 16312 16313 return true; 16314 } 16315 16316 private final class ClearStorageConnection implements ServiceConnection { 16317 IMediaContainerService mContainerService; 16318 16319 @Override 16320 public void onServiceConnected(ComponentName name, IBinder service) { 16321 synchronized (this) { 16322 mContainerService = IMediaContainerService.Stub.asInterface(service); 16323 notifyAll(); 16324 } 16325 } 16326 16327 @Override 16328 public void onServiceDisconnected(ComponentName name) { 16329 } 16330 } 16331 16332 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16333 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16334 16335 final boolean mounted; 16336 if (Environment.isExternalStorageEmulated()) { 16337 mounted = true; 16338 } else { 16339 final String status = Environment.getExternalStorageState(); 16340 16341 mounted = status.equals(Environment.MEDIA_MOUNTED) 16342 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16343 } 16344 16345 if (!mounted) { 16346 return; 16347 } 16348 16349 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16350 int[] users; 16351 if (userId == UserHandle.USER_ALL) { 16352 users = sUserManager.getUserIds(); 16353 } else { 16354 users = new int[] { userId }; 16355 } 16356 final ClearStorageConnection conn = new ClearStorageConnection(); 16357 if (mContext.bindServiceAsUser( 16358 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16359 try { 16360 for (int curUser : users) { 16361 long timeout = SystemClock.uptimeMillis() + 5000; 16362 synchronized (conn) { 16363 long now; 16364 while (conn.mContainerService == null && 16365 (now = SystemClock.uptimeMillis()) < timeout) { 16366 try { 16367 conn.wait(timeout - now); 16368 } catch (InterruptedException e) { 16369 } 16370 } 16371 } 16372 if (conn.mContainerService == null) { 16373 return; 16374 } 16375 16376 final UserEnvironment userEnv = new UserEnvironment(curUser); 16377 clearDirectory(conn.mContainerService, 16378 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16379 if (allData) { 16380 clearDirectory(conn.mContainerService, 16381 userEnv.buildExternalStorageAppDataDirs(packageName)); 16382 clearDirectory(conn.mContainerService, 16383 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16384 } 16385 } 16386 } finally { 16387 mContext.unbindService(conn); 16388 } 16389 } 16390 } 16391 16392 @Override 16393 public void clearApplicationProfileData(String packageName) { 16394 enforceSystemOrRoot("Only the system can clear all profile data"); 16395 16396 final PackageParser.Package pkg; 16397 synchronized (mPackages) { 16398 pkg = mPackages.get(packageName); 16399 } 16400 16401 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16402 synchronized (mInstallLock) { 16403 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16404 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16405 true /* removeBaseMarker */); 16406 } 16407 } 16408 } 16409 16410 @Override 16411 public void clearApplicationUserData(final String packageName, 16412 final IPackageDataObserver observer, final int userId) { 16413 mContext.enforceCallingOrSelfPermission( 16414 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16415 16416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16417 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16418 16419 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16420 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16421 } 16422 // Queue up an async operation since the package deletion may take a little while. 16423 mHandler.post(new Runnable() { 16424 public void run() { 16425 mHandler.removeCallbacks(this); 16426 final boolean succeeded; 16427 try (PackageFreezer freezer = freezePackage(packageName, 16428 "clearApplicationUserData")) { 16429 synchronized (mInstallLock) { 16430 succeeded = clearApplicationUserDataLIF(packageName, userId); 16431 } 16432 clearExternalStorageDataSync(packageName, userId, true); 16433 } 16434 if (succeeded) { 16435 // invoke DeviceStorageMonitor's update method to clear any notifications 16436 DeviceStorageMonitorInternal dsm = LocalServices 16437 .getService(DeviceStorageMonitorInternal.class); 16438 if (dsm != null) { 16439 dsm.checkMemory(); 16440 } 16441 } 16442 if(observer != null) { 16443 try { 16444 observer.onRemoveCompleted(packageName, succeeded); 16445 } catch (RemoteException e) { 16446 Log.i(TAG, "Observer no longer exists."); 16447 } 16448 } //end if observer 16449 } //end run 16450 }); 16451 } 16452 16453 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16454 if (packageName == null) { 16455 Slog.w(TAG, "Attempt to delete null packageName."); 16456 return false; 16457 } 16458 16459 // Try finding details about the requested package 16460 PackageParser.Package pkg; 16461 synchronized (mPackages) { 16462 pkg = mPackages.get(packageName); 16463 if (pkg == null) { 16464 final PackageSetting ps = mSettings.mPackages.get(packageName); 16465 if (ps != null) { 16466 pkg = ps.pkg; 16467 } 16468 } 16469 16470 if (pkg == null) { 16471 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16472 return false; 16473 } 16474 16475 PackageSetting ps = (PackageSetting) pkg.mExtras; 16476 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16477 } 16478 16479 clearAppDataLIF(pkg, userId, 16480 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16481 16482 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16483 removeKeystoreDataIfNeeded(userId, appId); 16484 16485 UserManagerInternal umInternal = getUserManagerInternal(); 16486 final int flags; 16487 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16488 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16489 } else if (umInternal.isUserRunning(userId)) { 16490 flags = StorageManager.FLAG_STORAGE_DE; 16491 } else { 16492 flags = 0; 16493 } 16494 prepareAppDataContentsLIF(pkg, userId, flags); 16495 16496 return true; 16497 } 16498 16499 /** 16500 * Reverts user permission state changes (permissions and flags) in 16501 * all packages for a given user. 16502 * 16503 * @param userId The device user for which to do a reset. 16504 */ 16505 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16506 final int packageCount = mPackages.size(); 16507 for (int i = 0; i < packageCount; i++) { 16508 PackageParser.Package pkg = mPackages.valueAt(i); 16509 PackageSetting ps = (PackageSetting) pkg.mExtras; 16510 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16511 } 16512 } 16513 16514 private void resetNetworkPolicies(int userId) { 16515 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16516 } 16517 16518 /** 16519 * Reverts user permission state changes (permissions and flags). 16520 * 16521 * @param ps The package for which to reset. 16522 * @param userId The device user for which to do a reset. 16523 */ 16524 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16525 final PackageSetting ps, final int userId) { 16526 if (ps.pkg == null) { 16527 return; 16528 } 16529 16530 // These are flags that can change base on user actions. 16531 final int userSettableMask = FLAG_PERMISSION_USER_SET 16532 | FLAG_PERMISSION_USER_FIXED 16533 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16534 | FLAG_PERMISSION_REVIEW_REQUIRED; 16535 16536 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16537 | FLAG_PERMISSION_POLICY_FIXED; 16538 16539 boolean writeInstallPermissions = false; 16540 boolean writeRuntimePermissions = false; 16541 16542 final int permissionCount = ps.pkg.requestedPermissions.size(); 16543 for (int i = 0; i < permissionCount; i++) { 16544 String permission = ps.pkg.requestedPermissions.get(i); 16545 16546 BasePermission bp = mSettings.mPermissions.get(permission); 16547 if (bp == null) { 16548 continue; 16549 } 16550 16551 // If shared user we just reset the state to which only this app contributed. 16552 if (ps.sharedUser != null) { 16553 boolean used = false; 16554 final int packageCount = ps.sharedUser.packages.size(); 16555 for (int j = 0; j < packageCount; j++) { 16556 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16557 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16558 && pkg.pkg.requestedPermissions.contains(permission)) { 16559 used = true; 16560 break; 16561 } 16562 } 16563 if (used) { 16564 continue; 16565 } 16566 } 16567 16568 PermissionsState permissionsState = ps.getPermissionsState(); 16569 16570 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16571 16572 // Always clear the user settable flags. 16573 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16574 bp.name) != null; 16575 // If permission review is enabled and this is a legacy app, mark the 16576 // permission as requiring a review as this is the initial state. 16577 int flags = 0; 16578 if (Build.PERMISSIONS_REVIEW_REQUIRED 16579 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16580 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16581 } 16582 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16583 if (hasInstallState) { 16584 writeInstallPermissions = true; 16585 } else { 16586 writeRuntimePermissions = true; 16587 } 16588 } 16589 16590 // Below is only runtime permission handling. 16591 if (!bp.isRuntime()) { 16592 continue; 16593 } 16594 16595 // Never clobber system or policy. 16596 if ((oldFlags & policyOrSystemFlags) != 0) { 16597 continue; 16598 } 16599 16600 // If this permission was granted by default, make sure it is. 16601 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16602 if (permissionsState.grantRuntimePermission(bp, userId) 16603 != PERMISSION_OPERATION_FAILURE) { 16604 writeRuntimePermissions = true; 16605 } 16606 // If permission review is enabled the permissions for a legacy apps 16607 // are represented as constantly granted runtime ones, so don't revoke. 16608 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16609 // Otherwise, reset the permission. 16610 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16611 switch (revokeResult) { 16612 case PERMISSION_OPERATION_SUCCESS: 16613 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16614 writeRuntimePermissions = true; 16615 final int appId = ps.appId; 16616 mHandler.post(new Runnable() { 16617 @Override 16618 public void run() { 16619 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16620 } 16621 }); 16622 } break; 16623 } 16624 } 16625 } 16626 16627 // Synchronously write as we are taking permissions away. 16628 if (writeRuntimePermissions) { 16629 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16630 } 16631 16632 // Synchronously write as we are taking permissions away. 16633 if (writeInstallPermissions) { 16634 mSettings.writeLPr(); 16635 } 16636 } 16637 16638 /** 16639 * Remove entries from the keystore daemon. Will only remove it if the 16640 * {@code appId} is valid. 16641 */ 16642 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16643 if (appId < 0) { 16644 return; 16645 } 16646 16647 final KeyStore keyStore = KeyStore.getInstance(); 16648 if (keyStore != null) { 16649 if (userId == UserHandle.USER_ALL) { 16650 for (final int individual : sUserManager.getUserIds()) { 16651 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16652 } 16653 } else { 16654 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16655 } 16656 } else { 16657 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16658 } 16659 } 16660 16661 @Override 16662 public void deleteApplicationCacheFiles(final String packageName, 16663 final IPackageDataObserver observer) { 16664 final int userId = UserHandle.getCallingUserId(); 16665 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16666 } 16667 16668 @Override 16669 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16670 final IPackageDataObserver observer) { 16671 mContext.enforceCallingOrSelfPermission( 16672 android.Manifest.permission.DELETE_CACHE_FILES, null); 16673 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16674 /* requireFullPermission= */ true, /* checkShell= */ false, 16675 "delete application cache files"); 16676 16677 final PackageParser.Package pkg; 16678 synchronized (mPackages) { 16679 pkg = mPackages.get(packageName); 16680 } 16681 16682 // Queue up an async operation since the package deletion may take a little while. 16683 mHandler.post(new Runnable() { 16684 public void run() { 16685 synchronized (mInstallLock) { 16686 final int flags = StorageManager.FLAG_STORAGE_DE 16687 | StorageManager.FLAG_STORAGE_CE; 16688 // We're only clearing cache files, so we don't care if the 16689 // app is unfrozen and still able to run 16690 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16691 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16692 } 16693 clearExternalStorageDataSync(packageName, userId, false); 16694 if (observer != null) { 16695 try { 16696 observer.onRemoveCompleted(packageName, true); 16697 } catch (RemoteException e) { 16698 Log.i(TAG, "Observer no longer exists."); 16699 } 16700 } 16701 } 16702 }); 16703 } 16704 16705 @Override 16706 public void getPackageSizeInfo(final String packageName, int userHandle, 16707 final IPackageStatsObserver observer) { 16708 mContext.enforceCallingOrSelfPermission( 16709 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16710 if (packageName == null) { 16711 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16712 } 16713 16714 PackageStats stats = new PackageStats(packageName, userHandle); 16715 16716 /* 16717 * Queue up an async operation since the package measurement may take a 16718 * little while. 16719 */ 16720 Message msg = mHandler.obtainMessage(INIT_COPY); 16721 msg.obj = new MeasureParams(stats, observer); 16722 mHandler.sendMessage(msg); 16723 } 16724 16725 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16726 final PackageSetting ps; 16727 synchronized (mPackages) { 16728 ps = mSettings.mPackages.get(packageName); 16729 if (ps == null) { 16730 Slog.w(TAG, "Failed to find settings for " + packageName); 16731 return false; 16732 } 16733 } 16734 try { 16735 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16736 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16737 ps.getCeDataInode(userId), ps.codePathString, stats); 16738 } catch (InstallerException e) { 16739 Slog.w(TAG, String.valueOf(e)); 16740 return false; 16741 } 16742 16743 // For now, ignore code size of packages on system partition 16744 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16745 stats.codeSize = 0; 16746 } 16747 16748 return true; 16749 } 16750 16751 private int getUidTargetSdkVersionLockedLPr(int uid) { 16752 Object obj = mSettings.getUserIdLPr(uid); 16753 if (obj instanceof SharedUserSetting) { 16754 final SharedUserSetting sus = (SharedUserSetting) obj; 16755 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16756 final Iterator<PackageSetting> it = sus.packages.iterator(); 16757 while (it.hasNext()) { 16758 final PackageSetting ps = it.next(); 16759 if (ps.pkg != null) { 16760 int v = ps.pkg.applicationInfo.targetSdkVersion; 16761 if (v < vers) vers = v; 16762 } 16763 } 16764 return vers; 16765 } else if (obj instanceof PackageSetting) { 16766 final PackageSetting ps = (PackageSetting) obj; 16767 if (ps.pkg != null) { 16768 return ps.pkg.applicationInfo.targetSdkVersion; 16769 } 16770 } 16771 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16772 } 16773 16774 @Override 16775 public void addPreferredActivity(IntentFilter filter, int match, 16776 ComponentName[] set, ComponentName activity, int userId) { 16777 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16778 "Adding preferred"); 16779 } 16780 16781 private void addPreferredActivityInternal(IntentFilter filter, int match, 16782 ComponentName[] set, ComponentName activity, boolean always, int userId, 16783 String opname) { 16784 // writer 16785 int callingUid = Binder.getCallingUid(); 16786 enforceCrossUserPermission(callingUid, userId, 16787 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16788 if (filter.countActions() == 0) { 16789 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16790 return; 16791 } 16792 synchronized (mPackages) { 16793 if (mContext.checkCallingOrSelfPermission( 16794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16795 != PackageManager.PERMISSION_GRANTED) { 16796 if (getUidTargetSdkVersionLockedLPr(callingUid) 16797 < Build.VERSION_CODES.FROYO) { 16798 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16799 + callingUid); 16800 return; 16801 } 16802 mContext.enforceCallingOrSelfPermission( 16803 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16804 } 16805 16806 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16807 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16808 + userId + ":"); 16809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16810 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16811 scheduleWritePackageRestrictionsLocked(userId); 16812 } 16813 } 16814 16815 @Override 16816 public void replacePreferredActivity(IntentFilter filter, int match, 16817 ComponentName[] set, ComponentName activity, int userId) { 16818 if (filter.countActions() != 1) { 16819 throw new IllegalArgumentException( 16820 "replacePreferredActivity expects filter to have only 1 action."); 16821 } 16822 if (filter.countDataAuthorities() != 0 16823 || filter.countDataPaths() != 0 16824 || filter.countDataSchemes() > 1 16825 || filter.countDataTypes() != 0) { 16826 throw new IllegalArgumentException( 16827 "replacePreferredActivity expects filter to have no data authorities, " + 16828 "paths, or types; and at most one scheme."); 16829 } 16830 16831 final int callingUid = Binder.getCallingUid(); 16832 enforceCrossUserPermission(callingUid, userId, 16833 true /* requireFullPermission */, false /* checkShell */, 16834 "replace preferred activity"); 16835 synchronized (mPackages) { 16836 if (mContext.checkCallingOrSelfPermission( 16837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16838 != PackageManager.PERMISSION_GRANTED) { 16839 if (getUidTargetSdkVersionLockedLPr(callingUid) 16840 < Build.VERSION_CODES.FROYO) { 16841 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16842 + Binder.getCallingUid()); 16843 return; 16844 } 16845 mContext.enforceCallingOrSelfPermission( 16846 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16847 } 16848 16849 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16850 if (pir != null) { 16851 // Get all of the existing entries that exactly match this filter. 16852 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16853 if (existing != null && existing.size() == 1) { 16854 PreferredActivity cur = existing.get(0); 16855 if (DEBUG_PREFERRED) { 16856 Slog.i(TAG, "Checking replace of preferred:"); 16857 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16858 if (!cur.mPref.mAlways) { 16859 Slog.i(TAG, " -- CUR; not mAlways!"); 16860 } else { 16861 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16862 Slog.i(TAG, " -- CUR: mSet=" 16863 + Arrays.toString(cur.mPref.mSetComponents)); 16864 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16865 Slog.i(TAG, " -- NEW: mMatch=" 16866 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16867 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16868 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16869 } 16870 } 16871 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16872 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16873 && cur.mPref.sameSet(set)) { 16874 // Setting the preferred activity to what it happens to be already 16875 if (DEBUG_PREFERRED) { 16876 Slog.i(TAG, "Replacing with same preferred activity " 16877 + cur.mPref.mShortComponent + " for user " 16878 + userId + ":"); 16879 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16880 } 16881 return; 16882 } 16883 } 16884 16885 if (existing != null) { 16886 if (DEBUG_PREFERRED) { 16887 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16888 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16889 } 16890 for (int i = 0; i < existing.size(); i++) { 16891 PreferredActivity pa = existing.get(i); 16892 if (DEBUG_PREFERRED) { 16893 Slog.i(TAG, "Removing existing preferred activity " 16894 + pa.mPref.mComponent + ":"); 16895 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16896 } 16897 pir.removeFilter(pa); 16898 } 16899 } 16900 } 16901 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16902 "Replacing preferred"); 16903 } 16904 } 16905 16906 @Override 16907 public void clearPackagePreferredActivities(String packageName) { 16908 final int uid = Binder.getCallingUid(); 16909 // writer 16910 synchronized (mPackages) { 16911 PackageParser.Package pkg = mPackages.get(packageName); 16912 if (pkg == null || pkg.applicationInfo.uid != uid) { 16913 if (mContext.checkCallingOrSelfPermission( 16914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16915 != PackageManager.PERMISSION_GRANTED) { 16916 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16917 < Build.VERSION_CODES.FROYO) { 16918 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16919 + Binder.getCallingUid()); 16920 return; 16921 } 16922 mContext.enforceCallingOrSelfPermission( 16923 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16924 } 16925 } 16926 16927 int user = UserHandle.getCallingUserId(); 16928 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16929 scheduleWritePackageRestrictionsLocked(user); 16930 } 16931 } 16932 } 16933 16934 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16935 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16936 ArrayList<PreferredActivity> removed = null; 16937 boolean changed = false; 16938 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16939 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16940 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16941 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16942 continue; 16943 } 16944 Iterator<PreferredActivity> it = pir.filterIterator(); 16945 while (it.hasNext()) { 16946 PreferredActivity pa = it.next(); 16947 // Mark entry for removal only if it matches the package name 16948 // and the entry is of type "always". 16949 if (packageName == null || 16950 (pa.mPref.mComponent.getPackageName().equals(packageName) 16951 && pa.mPref.mAlways)) { 16952 if (removed == null) { 16953 removed = new ArrayList<PreferredActivity>(); 16954 } 16955 removed.add(pa); 16956 } 16957 } 16958 if (removed != null) { 16959 for (int j=0; j<removed.size(); j++) { 16960 PreferredActivity pa = removed.get(j); 16961 pir.removeFilter(pa); 16962 } 16963 changed = true; 16964 } 16965 } 16966 return changed; 16967 } 16968 16969 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16970 private void clearIntentFilterVerificationsLPw(int userId) { 16971 final int packageCount = mPackages.size(); 16972 for (int i = 0; i < packageCount; i++) { 16973 PackageParser.Package pkg = mPackages.valueAt(i); 16974 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16975 } 16976 } 16977 16978 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16979 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16980 if (userId == UserHandle.USER_ALL) { 16981 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16982 sUserManager.getUserIds())) { 16983 for (int oneUserId : sUserManager.getUserIds()) { 16984 scheduleWritePackageRestrictionsLocked(oneUserId); 16985 } 16986 } 16987 } else { 16988 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16989 scheduleWritePackageRestrictionsLocked(userId); 16990 } 16991 } 16992 } 16993 16994 void clearDefaultBrowserIfNeeded(String packageName) { 16995 for (int oneUserId : sUserManager.getUserIds()) { 16996 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16997 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16998 if (packageName.equals(defaultBrowserPackageName)) { 16999 setDefaultBrowserPackageName(null, oneUserId); 17000 } 17001 } 17002 } 17003 17004 @Override 17005 public void resetApplicationPreferences(int userId) { 17006 mContext.enforceCallingOrSelfPermission( 17007 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17008 final long identity = Binder.clearCallingIdentity(); 17009 // writer 17010 try { 17011 synchronized (mPackages) { 17012 clearPackagePreferredActivitiesLPw(null, userId); 17013 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17014 // TODO: We have to reset the default SMS and Phone. This requires 17015 // significant refactoring to keep all default apps in the package 17016 // manager (cleaner but more work) or have the services provide 17017 // callbacks to the package manager to request a default app reset. 17018 applyFactoryDefaultBrowserLPw(userId); 17019 clearIntentFilterVerificationsLPw(userId); 17020 primeDomainVerificationsLPw(userId); 17021 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17022 scheduleWritePackageRestrictionsLocked(userId); 17023 } 17024 resetNetworkPolicies(userId); 17025 } finally { 17026 Binder.restoreCallingIdentity(identity); 17027 } 17028 } 17029 17030 @Override 17031 public int getPreferredActivities(List<IntentFilter> outFilters, 17032 List<ComponentName> outActivities, String packageName) { 17033 17034 int num = 0; 17035 final int userId = UserHandle.getCallingUserId(); 17036 // reader 17037 synchronized (mPackages) { 17038 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17039 if (pir != null) { 17040 final Iterator<PreferredActivity> it = pir.filterIterator(); 17041 while (it.hasNext()) { 17042 final PreferredActivity pa = it.next(); 17043 if (packageName == null 17044 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17045 && pa.mPref.mAlways)) { 17046 if (outFilters != null) { 17047 outFilters.add(new IntentFilter(pa)); 17048 } 17049 if (outActivities != null) { 17050 outActivities.add(pa.mPref.mComponent); 17051 } 17052 } 17053 } 17054 } 17055 } 17056 17057 return num; 17058 } 17059 17060 @Override 17061 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17062 int userId) { 17063 int callingUid = Binder.getCallingUid(); 17064 if (callingUid != Process.SYSTEM_UID) { 17065 throw new SecurityException( 17066 "addPersistentPreferredActivity can only be run by the system"); 17067 } 17068 if (filter.countActions() == 0) { 17069 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17070 return; 17071 } 17072 synchronized (mPackages) { 17073 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17074 ":"); 17075 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17076 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17077 new PersistentPreferredActivity(filter, activity)); 17078 scheduleWritePackageRestrictionsLocked(userId); 17079 } 17080 } 17081 17082 @Override 17083 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17084 int callingUid = Binder.getCallingUid(); 17085 if (callingUid != Process.SYSTEM_UID) { 17086 throw new SecurityException( 17087 "clearPackagePersistentPreferredActivities can only be run by the system"); 17088 } 17089 ArrayList<PersistentPreferredActivity> removed = null; 17090 boolean changed = false; 17091 synchronized (mPackages) { 17092 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17093 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17094 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17095 .valueAt(i); 17096 if (userId != thisUserId) { 17097 continue; 17098 } 17099 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17100 while (it.hasNext()) { 17101 PersistentPreferredActivity ppa = it.next(); 17102 // Mark entry for removal only if it matches the package name. 17103 if (ppa.mComponent.getPackageName().equals(packageName)) { 17104 if (removed == null) { 17105 removed = new ArrayList<PersistentPreferredActivity>(); 17106 } 17107 removed.add(ppa); 17108 } 17109 } 17110 if (removed != null) { 17111 for (int j=0; j<removed.size(); j++) { 17112 PersistentPreferredActivity ppa = removed.get(j); 17113 ppir.removeFilter(ppa); 17114 } 17115 changed = true; 17116 } 17117 } 17118 17119 if (changed) { 17120 scheduleWritePackageRestrictionsLocked(userId); 17121 } 17122 } 17123 } 17124 17125 /** 17126 * Common machinery for picking apart a restored XML blob and passing 17127 * it to a caller-supplied functor to be applied to the running system. 17128 */ 17129 private void restoreFromXml(XmlPullParser parser, int userId, 17130 String expectedStartTag, BlobXmlRestorer functor) 17131 throws IOException, XmlPullParserException { 17132 int type; 17133 while ((type = parser.next()) != XmlPullParser.START_TAG 17134 && type != XmlPullParser.END_DOCUMENT) { 17135 } 17136 if (type != XmlPullParser.START_TAG) { 17137 // oops didn't find a start tag?! 17138 if (DEBUG_BACKUP) { 17139 Slog.e(TAG, "Didn't find start tag during restore"); 17140 } 17141 return; 17142 } 17143Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17144 // this is supposed to be TAG_PREFERRED_BACKUP 17145 if (!expectedStartTag.equals(parser.getName())) { 17146 if (DEBUG_BACKUP) { 17147 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17148 } 17149 return; 17150 } 17151 17152 // skip interfering stuff, then we're aligned with the backing implementation 17153 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17154Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17155 functor.apply(parser, userId); 17156 } 17157 17158 private interface BlobXmlRestorer { 17159 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17160 } 17161 17162 /** 17163 * Non-Binder method, support for the backup/restore mechanism: write the 17164 * full set of preferred activities in its canonical XML format. Returns the 17165 * XML output as a byte array, or null if there is none. 17166 */ 17167 @Override 17168 public byte[] getPreferredActivityBackup(int userId) { 17169 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17170 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17171 } 17172 17173 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17174 try { 17175 final XmlSerializer serializer = new FastXmlSerializer(); 17176 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17177 serializer.startDocument(null, true); 17178 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17179 17180 synchronized (mPackages) { 17181 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17182 } 17183 17184 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17185 serializer.endDocument(); 17186 serializer.flush(); 17187 } catch (Exception e) { 17188 if (DEBUG_BACKUP) { 17189 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17190 } 17191 return null; 17192 } 17193 17194 return dataStream.toByteArray(); 17195 } 17196 17197 @Override 17198 public void restorePreferredActivities(byte[] backup, int userId) { 17199 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17200 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17201 } 17202 17203 try { 17204 final XmlPullParser parser = Xml.newPullParser(); 17205 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17206 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17207 new BlobXmlRestorer() { 17208 @Override 17209 public void apply(XmlPullParser parser, int userId) 17210 throws XmlPullParserException, IOException { 17211 synchronized (mPackages) { 17212 mSettings.readPreferredActivitiesLPw(parser, userId); 17213 } 17214 } 17215 } ); 17216 } catch (Exception e) { 17217 if (DEBUG_BACKUP) { 17218 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17219 } 17220 } 17221 } 17222 17223 /** 17224 * Non-Binder method, support for the backup/restore mechanism: write the 17225 * default browser (etc) settings in its canonical XML format. Returns the default 17226 * browser XML representation as a byte array, or null if there is none. 17227 */ 17228 @Override 17229 public byte[] getDefaultAppsBackup(int userId) { 17230 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17231 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17232 } 17233 17234 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17235 try { 17236 final XmlSerializer serializer = new FastXmlSerializer(); 17237 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17238 serializer.startDocument(null, true); 17239 serializer.startTag(null, TAG_DEFAULT_APPS); 17240 17241 synchronized (mPackages) { 17242 mSettings.writeDefaultAppsLPr(serializer, userId); 17243 } 17244 17245 serializer.endTag(null, TAG_DEFAULT_APPS); 17246 serializer.endDocument(); 17247 serializer.flush(); 17248 } catch (Exception e) { 17249 if (DEBUG_BACKUP) { 17250 Slog.e(TAG, "Unable to write default apps for backup", e); 17251 } 17252 return null; 17253 } 17254 17255 return dataStream.toByteArray(); 17256 } 17257 17258 @Override 17259 public void restoreDefaultApps(byte[] backup, int userId) { 17260 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17261 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17262 } 17263 17264 try { 17265 final XmlPullParser parser = Xml.newPullParser(); 17266 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17267 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17268 new BlobXmlRestorer() { 17269 @Override 17270 public void apply(XmlPullParser parser, int userId) 17271 throws XmlPullParserException, IOException { 17272 synchronized (mPackages) { 17273 mSettings.readDefaultAppsLPw(parser, userId); 17274 } 17275 } 17276 } ); 17277 } catch (Exception e) { 17278 if (DEBUG_BACKUP) { 17279 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17280 } 17281 } 17282 } 17283 17284 @Override 17285 public byte[] getIntentFilterVerificationBackup(int userId) { 17286 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17287 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17288 } 17289 17290 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17291 try { 17292 final XmlSerializer serializer = new FastXmlSerializer(); 17293 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17294 serializer.startDocument(null, true); 17295 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17296 17297 synchronized (mPackages) { 17298 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17299 } 17300 17301 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17302 serializer.endDocument(); 17303 serializer.flush(); 17304 } catch (Exception e) { 17305 if (DEBUG_BACKUP) { 17306 Slog.e(TAG, "Unable to write default apps for backup", e); 17307 } 17308 return null; 17309 } 17310 17311 return dataStream.toByteArray(); 17312 } 17313 17314 @Override 17315 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17316 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17317 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17318 } 17319 17320 try { 17321 final XmlPullParser parser = Xml.newPullParser(); 17322 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17323 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17324 new BlobXmlRestorer() { 17325 @Override 17326 public void apply(XmlPullParser parser, int userId) 17327 throws XmlPullParserException, IOException { 17328 synchronized (mPackages) { 17329 mSettings.readAllDomainVerificationsLPr(parser, userId); 17330 mSettings.writeLPr(); 17331 } 17332 } 17333 } ); 17334 } catch (Exception e) { 17335 if (DEBUG_BACKUP) { 17336 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17337 } 17338 } 17339 } 17340 17341 @Override 17342 public byte[] getPermissionGrantBackup(int userId) { 17343 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17344 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17345 } 17346 17347 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17348 try { 17349 final XmlSerializer serializer = new FastXmlSerializer(); 17350 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17351 serializer.startDocument(null, true); 17352 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17353 17354 synchronized (mPackages) { 17355 serializeRuntimePermissionGrantsLPr(serializer, userId); 17356 } 17357 17358 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17359 serializer.endDocument(); 17360 serializer.flush(); 17361 } catch (Exception e) { 17362 if (DEBUG_BACKUP) { 17363 Slog.e(TAG, "Unable to write default apps for backup", e); 17364 } 17365 return null; 17366 } 17367 17368 return dataStream.toByteArray(); 17369 } 17370 17371 @Override 17372 public void restorePermissionGrants(byte[] backup, int userId) { 17373 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17374 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17375 } 17376 17377 try { 17378 final XmlPullParser parser = Xml.newPullParser(); 17379 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17380 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17381 new BlobXmlRestorer() { 17382 @Override 17383 public void apply(XmlPullParser parser, int userId) 17384 throws XmlPullParserException, IOException { 17385 synchronized (mPackages) { 17386 processRestoredPermissionGrantsLPr(parser, userId); 17387 } 17388 } 17389 } ); 17390 } catch (Exception e) { 17391 if (DEBUG_BACKUP) { 17392 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17393 } 17394 } 17395 } 17396 17397 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17398 throws IOException { 17399 serializer.startTag(null, TAG_ALL_GRANTS); 17400 17401 final int N = mSettings.mPackages.size(); 17402 for (int i = 0; i < N; i++) { 17403 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17404 boolean pkgGrantsKnown = false; 17405 17406 PermissionsState packagePerms = ps.getPermissionsState(); 17407 17408 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17409 final int grantFlags = state.getFlags(); 17410 // only look at grants that are not system/policy fixed 17411 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17412 final boolean isGranted = state.isGranted(); 17413 // And only back up the user-twiddled state bits 17414 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17415 final String packageName = mSettings.mPackages.keyAt(i); 17416 if (!pkgGrantsKnown) { 17417 serializer.startTag(null, TAG_GRANT); 17418 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17419 pkgGrantsKnown = true; 17420 } 17421 17422 final boolean userSet = 17423 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17424 final boolean userFixed = 17425 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17426 final boolean revoke = 17427 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17428 17429 serializer.startTag(null, TAG_PERMISSION); 17430 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17431 if (isGranted) { 17432 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17433 } 17434 if (userSet) { 17435 serializer.attribute(null, ATTR_USER_SET, "true"); 17436 } 17437 if (userFixed) { 17438 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17439 } 17440 if (revoke) { 17441 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17442 } 17443 serializer.endTag(null, TAG_PERMISSION); 17444 } 17445 } 17446 } 17447 17448 if (pkgGrantsKnown) { 17449 serializer.endTag(null, TAG_GRANT); 17450 } 17451 } 17452 17453 serializer.endTag(null, TAG_ALL_GRANTS); 17454 } 17455 17456 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17457 throws XmlPullParserException, IOException { 17458 String pkgName = null; 17459 int outerDepth = parser.getDepth(); 17460 int type; 17461 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17462 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17463 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17464 continue; 17465 } 17466 17467 final String tagName = parser.getName(); 17468 if (tagName.equals(TAG_GRANT)) { 17469 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17470 if (DEBUG_BACKUP) { 17471 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17472 } 17473 } else if (tagName.equals(TAG_PERMISSION)) { 17474 17475 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17476 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17477 17478 int newFlagSet = 0; 17479 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17480 newFlagSet |= FLAG_PERMISSION_USER_SET; 17481 } 17482 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17483 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17484 } 17485 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17486 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17487 } 17488 if (DEBUG_BACKUP) { 17489 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17490 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17491 } 17492 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17493 if (ps != null) { 17494 // Already installed so we apply the grant immediately 17495 if (DEBUG_BACKUP) { 17496 Slog.v(TAG, " + already installed; applying"); 17497 } 17498 PermissionsState perms = ps.getPermissionsState(); 17499 BasePermission bp = mSettings.mPermissions.get(permName); 17500 if (bp != null) { 17501 if (isGranted) { 17502 perms.grantRuntimePermission(bp, userId); 17503 } 17504 if (newFlagSet != 0) { 17505 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17506 } 17507 } 17508 } else { 17509 // Need to wait for post-restore install to apply the grant 17510 if (DEBUG_BACKUP) { 17511 Slog.v(TAG, " - not yet installed; saving for later"); 17512 } 17513 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17514 isGranted, newFlagSet, userId); 17515 } 17516 } else { 17517 PackageManagerService.reportSettingsProblem(Log.WARN, 17518 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17519 XmlUtils.skipCurrentTag(parser); 17520 } 17521 } 17522 17523 scheduleWriteSettingsLocked(); 17524 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17525 } 17526 17527 @Override 17528 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17529 int sourceUserId, int targetUserId, int flags) { 17530 mContext.enforceCallingOrSelfPermission( 17531 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17532 int callingUid = Binder.getCallingUid(); 17533 enforceOwnerRights(ownerPackage, callingUid); 17534 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17535 if (intentFilter.countActions() == 0) { 17536 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17537 return; 17538 } 17539 synchronized (mPackages) { 17540 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17541 ownerPackage, targetUserId, flags); 17542 CrossProfileIntentResolver resolver = 17543 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17544 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17545 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17546 if (existing != null) { 17547 int size = existing.size(); 17548 for (int i = 0; i < size; i++) { 17549 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17550 return; 17551 } 17552 } 17553 } 17554 resolver.addFilter(newFilter); 17555 scheduleWritePackageRestrictionsLocked(sourceUserId); 17556 } 17557 } 17558 17559 @Override 17560 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17561 mContext.enforceCallingOrSelfPermission( 17562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17563 int callingUid = Binder.getCallingUid(); 17564 enforceOwnerRights(ownerPackage, callingUid); 17565 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17566 synchronized (mPackages) { 17567 CrossProfileIntentResolver resolver = 17568 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17569 ArraySet<CrossProfileIntentFilter> set = 17570 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17571 for (CrossProfileIntentFilter filter : set) { 17572 if (filter.getOwnerPackage().equals(ownerPackage)) { 17573 resolver.removeFilter(filter); 17574 } 17575 } 17576 scheduleWritePackageRestrictionsLocked(sourceUserId); 17577 } 17578 } 17579 17580 // Enforcing that callingUid is owning pkg on userId 17581 private void enforceOwnerRights(String pkg, int callingUid) { 17582 // The system owns everything. 17583 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17584 return; 17585 } 17586 int callingUserId = UserHandle.getUserId(callingUid); 17587 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17588 if (pi == null) { 17589 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17590 + callingUserId); 17591 } 17592 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17593 throw new SecurityException("Calling uid " + callingUid 17594 + " does not own package " + pkg); 17595 } 17596 } 17597 17598 @Override 17599 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17600 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17601 } 17602 17603 private Intent getHomeIntent() { 17604 Intent intent = new Intent(Intent.ACTION_MAIN); 17605 intent.addCategory(Intent.CATEGORY_HOME); 17606 return intent; 17607 } 17608 17609 private IntentFilter getHomeFilter() { 17610 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17611 filter.addCategory(Intent.CATEGORY_HOME); 17612 filter.addCategory(Intent.CATEGORY_DEFAULT); 17613 return filter; 17614 } 17615 17616 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17617 int userId) { 17618 Intent intent = getHomeIntent(); 17619 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17620 PackageManager.GET_META_DATA, userId); 17621 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17622 true, false, false, userId); 17623 17624 allHomeCandidates.clear(); 17625 if (list != null) { 17626 for (ResolveInfo ri : list) { 17627 allHomeCandidates.add(ri); 17628 } 17629 } 17630 return (preferred == null || preferred.activityInfo == null) 17631 ? null 17632 : new ComponentName(preferred.activityInfo.packageName, 17633 preferred.activityInfo.name); 17634 } 17635 17636 @Override 17637 public void setHomeActivity(ComponentName comp, int userId) { 17638 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17639 getHomeActivitiesAsUser(homeActivities, userId); 17640 17641 boolean found = false; 17642 17643 final int size = homeActivities.size(); 17644 final ComponentName[] set = new ComponentName[size]; 17645 for (int i = 0; i < size; i++) { 17646 final ResolveInfo candidate = homeActivities.get(i); 17647 final ActivityInfo info = candidate.activityInfo; 17648 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17649 set[i] = activityName; 17650 if (!found && activityName.equals(comp)) { 17651 found = true; 17652 } 17653 } 17654 if (!found) { 17655 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17656 + userId); 17657 } 17658 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17659 set, comp, userId); 17660 } 17661 17662 private @Nullable String getSetupWizardPackageName() { 17663 final Intent intent = new Intent(Intent.ACTION_MAIN); 17664 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17665 17666 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17667 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17668 | MATCH_DISABLED_COMPONENTS, 17669 UserHandle.myUserId()); 17670 if (matches.size() == 1) { 17671 return matches.get(0).getComponentInfo().packageName; 17672 } else { 17673 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17674 + ": matches=" + matches); 17675 return null; 17676 } 17677 } 17678 17679 @Override 17680 public void setApplicationEnabledSetting(String appPackageName, 17681 int newState, int flags, int userId, String callingPackage) { 17682 if (!sUserManager.exists(userId)) return; 17683 if (callingPackage == null) { 17684 callingPackage = Integer.toString(Binder.getCallingUid()); 17685 } 17686 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17687 } 17688 17689 @Override 17690 public void setComponentEnabledSetting(ComponentName componentName, 17691 int newState, int flags, int userId) { 17692 if (!sUserManager.exists(userId)) return; 17693 setEnabledSetting(componentName.getPackageName(), 17694 componentName.getClassName(), newState, flags, userId, null); 17695 } 17696 17697 private void setEnabledSetting(final String packageName, String className, int newState, 17698 final int flags, int userId, String callingPackage) { 17699 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17700 || newState == COMPONENT_ENABLED_STATE_ENABLED 17701 || newState == COMPONENT_ENABLED_STATE_DISABLED 17702 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17703 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17704 throw new IllegalArgumentException("Invalid new component state: " 17705 + newState); 17706 } 17707 PackageSetting pkgSetting; 17708 final int uid = Binder.getCallingUid(); 17709 final int permission; 17710 if (uid == Process.SYSTEM_UID) { 17711 permission = PackageManager.PERMISSION_GRANTED; 17712 } else { 17713 permission = mContext.checkCallingOrSelfPermission( 17714 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17715 } 17716 enforceCrossUserPermission(uid, userId, 17717 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17718 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17719 boolean sendNow = false; 17720 boolean isApp = (className == null); 17721 String componentName = isApp ? packageName : className; 17722 int packageUid = -1; 17723 ArrayList<String> components; 17724 17725 // writer 17726 synchronized (mPackages) { 17727 pkgSetting = mSettings.mPackages.get(packageName); 17728 if (pkgSetting == null) { 17729 if (className == null) { 17730 throw new IllegalArgumentException("Unknown package: " + packageName); 17731 } 17732 throw new IllegalArgumentException( 17733 "Unknown component: " + packageName + "/" + className); 17734 } 17735 } 17736 17737 // Limit who can change which apps 17738 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17739 // Don't allow apps that don't have permission to modify other apps 17740 if (!allowedByPermission) { 17741 throw new SecurityException( 17742 "Permission Denial: attempt to change component state from pid=" 17743 + Binder.getCallingPid() 17744 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17745 } 17746 // Don't allow changing profile and device owners. 17747 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17748 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17749 } 17750 } 17751 17752 synchronized (mPackages) { 17753 if (uid == Process.SHELL_UID) { 17754 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17755 int oldState = pkgSetting.getEnabled(userId); 17756 if (className == null 17757 && 17758 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17759 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17760 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17761 && 17762 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17763 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17764 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17765 // ok 17766 } else { 17767 throw new SecurityException( 17768 "Shell cannot change component state for " + packageName + "/" 17769 + className + " to " + newState); 17770 } 17771 } 17772 if (className == null) { 17773 // We're dealing with an application/package level state change 17774 if (pkgSetting.getEnabled(userId) == newState) { 17775 // Nothing to do 17776 return; 17777 } 17778 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17779 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17780 // Don't care about who enables an app. 17781 callingPackage = null; 17782 } 17783 pkgSetting.setEnabled(newState, userId, callingPackage); 17784 // pkgSetting.pkg.mSetEnabled = newState; 17785 } else { 17786 // We're dealing with a component level state change 17787 // First, verify that this is a valid class name. 17788 PackageParser.Package pkg = pkgSetting.pkg; 17789 if (pkg == null || !pkg.hasComponentClassName(className)) { 17790 if (pkg != null && 17791 pkg.applicationInfo.targetSdkVersion >= 17792 Build.VERSION_CODES.JELLY_BEAN) { 17793 throw new IllegalArgumentException("Component class " + className 17794 + " does not exist in " + packageName); 17795 } else { 17796 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17797 + className + " does not exist in " + packageName); 17798 } 17799 } 17800 switch (newState) { 17801 case COMPONENT_ENABLED_STATE_ENABLED: 17802 if (!pkgSetting.enableComponentLPw(className, userId)) { 17803 return; 17804 } 17805 break; 17806 case COMPONENT_ENABLED_STATE_DISABLED: 17807 if (!pkgSetting.disableComponentLPw(className, userId)) { 17808 return; 17809 } 17810 break; 17811 case COMPONENT_ENABLED_STATE_DEFAULT: 17812 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17813 return; 17814 } 17815 break; 17816 default: 17817 Slog.e(TAG, "Invalid new component state: " + newState); 17818 return; 17819 } 17820 } 17821 scheduleWritePackageRestrictionsLocked(userId); 17822 components = mPendingBroadcasts.get(userId, packageName); 17823 final boolean newPackage = components == null; 17824 if (newPackage) { 17825 components = new ArrayList<String>(); 17826 } 17827 if (!components.contains(componentName)) { 17828 components.add(componentName); 17829 } 17830 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17831 sendNow = true; 17832 // Purge entry from pending broadcast list if another one exists already 17833 // since we are sending one right away. 17834 mPendingBroadcasts.remove(userId, packageName); 17835 } else { 17836 if (newPackage) { 17837 mPendingBroadcasts.put(userId, packageName, components); 17838 } 17839 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17840 // Schedule a message 17841 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17842 } 17843 } 17844 } 17845 17846 long callingId = Binder.clearCallingIdentity(); 17847 try { 17848 if (sendNow) { 17849 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17850 sendPackageChangedBroadcast(packageName, 17851 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17852 } 17853 } finally { 17854 Binder.restoreCallingIdentity(callingId); 17855 } 17856 } 17857 17858 @Override 17859 public void flushPackageRestrictionsAsUser(int userId) { 17860 if (!sUserManager.exists(userId)) { 17861 return; 17862 } 17863 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17864 false /* checkShell */, "flushPackageRestrictions"); 17865 synchronized (mPackages) { 17866 mSettings.writePackageRestrictionsLPr(userId); 17867 mDirtyUsers.remove(userId); 17868 if (mDirtyUsers.isEmpty()) { 17869 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17870 } 17871 } 17872 } 17873 17874 private void sendPackageChangedBroadcast(String packageName, 17875 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17876 if (DEBUG_INSTALL) 17877 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17878 + componentNames); 17879 Bundle extras = new Bundle(4); 17880 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17881 String nameList[] = new String[componentNames.size()]; 17882 componentNames.toArray(nameList); 17883 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17884 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17885 extras.putInt(Intent.EXTRA_UID, packageUid); 17886 // If this is not reporting a change of the overall package, then only send it 17887 // to registered receivers. We don't want to launch a swath of apps for every 17888 // little component state change. 17889 final int flags = !componentNames.contains(packageName) 17890 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17891 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17892 new int[] {UserHandle.getUserId(packageUid)}); 17893 } 17894 17895 @Override 17896 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17897 if (!sUserManager.exists(userId)) return; 17898 final int uid = Binder.getCallingUid(); 17899 final int permission = mContext.checkCallingOrSelfPermission( 17900 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17901 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17902 enforceCrossUserPermission(uid, userId, 17903 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17904 // writer 17905 synchronized (mPackages) { 17906 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17907 allowedByPermission, uid, userId)) { 17908 scheduleWritePackageRestrictionsLocked(userId); 17909 } 17910 } 17911 } 17912 17913 @Override 17914 public String getInstallerPackageName(String packageName) { 17915 // reader 17916 synchronized (mPackages) { 17917 return mSettings.getInstallerPackageNameLPr(packageName); 17918 } 17919 } 17920 17921 public boolean isOrphaned(String packageName) { 17922 // reader 17923 synchronized (mPackages) { 17924 return mSettings.isOrphaned(packageName); 17925 } 17926 } 17927 17928 @Override 17929 public int getApplicationEnabledSetting(String packageName, int userId) { 17930 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17931 int uid = Binder.getCallingUid(); 17932 enforceCrossUserPermission(uid, userId, 17933 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17934 // reader 17935 synchronized (mPackages) { 17936 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17937 } 17938 } 17939 17940 @Override 17941 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17942 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17943 int uid = Binder.getCallingUid(); 17944 enforceCrossUserPermission(uid, userId, 17945 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17946 // reader 17947 synchronized (mPackages) { 17948 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17949 } 17950 } 17951 17952 @Override 17953 public void enterSafeMode() { 17954 enforceSystemOrRoot("Only the system can request entering safe mode"); 17955 17956 if (!mSystemReady) { 17957 mSafeMode = true; 17958 } 17959 } 17960 17961 @Override 17962 public void systemReady() { 17963 mSystemReady = true; 17964 17965 // Read the compatibilty setting when the system is ready. 17966 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17967 mContext.getContentResolver(), 17968 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17969 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17970 if (DEBUG_SETTINGS) { 17971 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17972 } 17973 17974 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17975 17976 synchronized (mPackages) { 17977 // Verify that all of the preferred activity components actually 17978 // exist. It is possible for applications to be updated and at 17979 // that point remove a previously declared activity component that 17980 // had been set as a preferred activity. We try to clean this up 17981 // the next time we encounter that preferred activity, but it is 17982 // possible for the user flow to never be able to return to that 17983 // situation so here we do a sanity check to make sure we haven't 17984 // left any junk around. 17985 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17986 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17987 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17988 removed.clear(); 17989 for (PreferredActivity pa : pir.filterSet()) { 17990 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17991 removed.add(pa); 17992 } 17993 } 17994 if (removed.size() > 0) { 17995 for (int r=0; r<removed.size(); r++) { 17996 PreferredActivity pa = removed.get(r); 17997 Slog.w(TAG, "Removing dangling preferred activity: " 17998 + pa.mPref.mComponent); 17999 pir.removeFilter(pa); 18000 } 18001 mSettings.writePackageRestrictionsLPr( 18002 mSettings.mPreferredActivities.keyAt(i)); 18003 } 18004 } 18005 18006 for (int userId : UserManagerService.getInstance().getUserIds()) { 18007 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18008 grantPermissionsUserIds = ArrayUtils.appendInt( 18009 grantPermissionsUserIds, userId); 18010 } 18011 } 18012 } 18013 sUserManager.systemReady(); 18014 18015 // If we upgraded grant all default permissions before kicking off. 18016 for (int userId : grantPermissionsUserIds) { 18017 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18018 } 18019 18020 // Kick off any messages waiting for system ready 18021 if (mPostSystemReadyMessages != null) { 18022 for (Message msg : mPostSystemReadyMessages) { 18023 msg.sendToTarget(); 18024 } 18025 mPostSystemReadyMessages = null; 18026 } 18027 18028 // Watch for external volumes that come and go over time 18029 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18030 storage.registerListener(mStorageListener); 18031 18032 mInstallerService.systemReady(); 18033 mPackageDexOptimizer.systemReady(); 18034 18035 MountServiceInternal mountServiceInternal = LocalServices.getService( 18036 MountServiceInternal.class); 18037 mountServiceInternal.addExternalStoragePolicy( 18038 new MountServiceInternal.ExternalStorageMountPolicy() { 18039 @Override 18040 public int getMountMode(int uid, String packageName) { 18041 if (Process.isIsolated(uid)) { 18042 return Zygote.MOUNT_EXTERNAL_NONE; 18043 } 18044 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18045 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18046 } 18047 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18048 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18049 } 18050 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18051 return Zygote.MOUNT_EXTERNAL_READ; 18052 } 18053 return Zygote.MOUNT_EXTERNAL_WRITE; 18054 } 18055 18056 @Override 18057 public boolean hasExternalStorage(int uid, String packageName) { 18058 return true; 18059 } 18060 }); 18061 18062 // Now that we're mostly running, clean up stale users and apps 18063 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18064 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18065 } 18066 18067 @Override 18068 public boolean isSafeMode() { 18069 return mSafeMode; 18070 } 18071 18072 @Override 18073 public boolean hasSystemUidErrors() { 18074 return mHasSystemUidErrors; 18075 } 18076 18077 static String arrayToString(int[] array) { 18078 StringBuffer buf = new StringBuffer(128); 18079 buf.append('['); 18080 if (array != null) { 18081 for (int i=0; i<array.length; i++) { 18082 if (i > 0) buf.append(", "); 18083 buf.append(array[i]); 18084 } 18085 } 18086 buf.append(']'); 18087 return buf.toString(); 18088 } 18089 18090 static class DumpState { 18091 public static final int DUMP_LIBS = 1 << 0; 18092 public static final int DUMP_FEATURES = 1 << 1; 18093 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18094 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18095 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18096 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18097 public static final int DUMP_PERMISSIONS = 1 << 6; 18098 public static final int DUMP_PACKAGES = 1 << 7; 18099 public static final int DUMP_SHARED_USERS = 1 << 8; 18100 public static final int DUMP_MESSAGES = 1 << 9; 18101 public static final int DUMP_PROVIDERS = 1 << 10; 18102 public static final int DUMP_VERIFIERS = 1 << 11; 18103 public static final int DUMP_PREFERRED = 1 << 12; 18104 public static final int DUMP_PREFERRED_XML = 1 << 13; 18105 public static final int DUMP_KEYSETS = 1 << 14; 18106 public static final int DUMP_VERSION = 1 << 15; 18107 public static final int DUMP_INSTALLS = 1 << 16; 18108 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18109 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18110 public static final int DUMP_FROZEN = 1 << 19; 18111 public static final int DUMP_DEXOPT = 1 << 20; 18112 18113 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18114 18115 private int mTypes; 18116 18117 private int mOptions; 18118 18119 private boolean mTitlePrinted; 18120 18121 private SharedUserSetting mSharedUser; 18122 18123 public boolean isDumping(int type) { 18124 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18125 return true; 18126 } 18127 18128 return (mTypes & type) != 0; 18129 } 18130 18131 public void setDump(int type) { 18132 mTypes |= type; 18133 } 18134 18135 public boolean isOptionEnabled(int option) { 18136 return (mOptions & option) != 0; 18137 } 18138 18139 public void setOptionEnabled(int option) { 18140 mOptions |= option; 18141 } 18142 18143 public boolean onTitlePrinted() { 18144 final boolean printed = mTitlePrinted; 18145 mTitlePrinted = true; 18146 return printed; 18147 } 18148 18149 public boolean getTitlePrinted() { 18150 return mTitlePrinted; 18151 } 18152 18153 public void setTitlePrinted(boolean enabled) { 18154 mTitlePrinted = enabled; 18155 } 18156 18157 public SharedUserSetting getSharedUser() { 18158 return mSharedUser; 18159 } 18160 18161 public void setSharedUser(SharedUserSetting user) { 18162 mSharedUser = user; 18163 } 18164 } 18165 18166 @Override 18167 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18168 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18169 (new PackageManagerShellCommand(this)).exec( 18170 this, in, out, err, args, resultReceiver); 18171 } 18172 18173 @Override 18174 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18175 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18176 != PackageManager.PERMISSION_GRANTED) { 18177 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18178 + Binder.getCallingPid() 18179 + ", uid=" + Binder.getCallingUid() 18180 + " without permission " 18181 + android.Manifest.permission.DUMP); 18182 return; 18183 } 18184 18185 DumpState dumpState = new DumpState(); 18186 boolean fullPreferred = false; 18187 boolean checkin = false; 18188 18189 String packageName = null; 18190 ArraySet<String> permissionNames = null; 18191 18192 int opti = 0; 18193 while (opti < args.length) { 18194 String opt = args[opti]; 18195 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18196 break; 18197 } 18198 opti++; 18199 18200 if ("-a".equals(opt)) { 18201 // Right now we only know how to print all. 18202 } else if ("-h".equals(opt)) { 18203 pw.println("Package manager dump options:"); 18204 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18205 pw.println(" --checkin: dump for a checkin"); 18206 pw.println(" -f: print details of intent filters"); 18207 pw.println(" -h: print this help"); 18208 pw.println(" cmd may be one of:"); 18209 pw.println(" l[ibraries]: list known shared libraries"); 18210 pw.println(" f[eatures]: list device features"); 18211 pw.println(" k[eysets]: print known keysets"); 18212 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18213 pw.println(" perm[issions]: dump permissions"); 18214 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18215 pw.println(" pref[erred]: print preferred package settings"); 18216 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18217 pw.println(" prov[iders]: dump content providers"); 18218 pw.println(" p[ackages]: dump installed packages"); 18219 pw.println(" s[hared-users]: dump shared user IDs"); 18220 pw.println(" m[essages]: print collected runtime messages"); 18221 pw.println(" v[erifiers]: print package verifier info"); 18222 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18223 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18224 pw.println(" version: print database version info"); 18225 pw.println(" write: write current settings now"); 18226 pw.println(" installs: details about install sessions"); 18227 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18228 pw.println(" dexopt: dump dexopt state"); 18229 pw.println(" <package.name>: info about given package"); 18230 return; 18231 } else if ("--checkin".equals(opt)) { 18232 checkin = true; 18233 } else if ("-f".equals(opt)) { 18234 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18235 } else { 18236 pw.println("Unknown argument: " + opt + "; use -h for help"); 18237 } 18238 } 18239 18240 // Is the caller requesting to dump a particular piece of data? 18241 if (opti < args.length) { 18242 String cmd = args[opti]; 18243 opti++; 18244 // Is this a package name? 18245 if ("android".equals(cmd) || cmd.contains(".")) { 18246 packageName = cmd; 18247 // When dumping a single package, we always dump all of its 18248 // filter information since the amount of data will be reasonable. 18249 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18250 } else if ("check-permission".equals(cmd)) { 18251 if (opti >= args.length) { 18252 pw.println("Error: check-permission missing permission argument"); 18253 return; 18254 } 18255 String perm = args[opti]; 18256 opti++; 18257 if (opti >= args.length) { 18258 pw.println("Error: check-permission missing package argument"); 18259 return; 18260 } 18261 String pkg = args[opti]; 18262 opti++; 18263 int user = UserHandle.getUserId(Binder.getCallingUid()); 18264 if (opti < args.length) { 18265 try { 18266 user = Integer.parseInt(args[opti]); 18267 } catch (NumberFormatException e) { 18268 pw.println("Error: check-permission user argument is not a number: " 18269 + args[opti]); 18270 return; 18271 } 18272 } 18273 pw.println(checkPermission(perm, pkg, user)); 18274 return; 18275 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18276 dumpState.setDump(DumpState.DUMP_LIBS); 18277 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18278 dumpState.setDump(DumpState.DUMP_FEATURES); 18279 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18280 if (opti >= args.length) { 18281 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18282 | DumpState.DUMP_SERVICE_RESOLVERS 18283 | DumpState.DUMP_RECEIVER_RESOLVERS 18284 | DumpState.DUMP_CONTENT_RESOLVERS); 18285 } else { 18286 while (opti < args.length) { 18287 String name = args[opti]; 18288 if ("a".equals(name) || "activity".equals(name)) { 18289 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18290 } else if ("s".equals(name) || "service".equals(name)) { 18291 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18292 } else if ("r".equals(name) || "receiver".equals(name)) { 18293 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18294 } else if ("c".equals(name) || "content".equals(name)) { 18295 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18296 } else { 18297 pw.println("Error: unknown resolver table type: " + name); 18298 return; 18299 } 18300 opti++; 18301 } 18302 } 18303 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18304 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18305 } else if ("permission".equals(cmd)) { 18306 if (opti >= args.length) { 18307 pw.println("Error: permission requires permission name"); 18308 return; 18309 } 18310 permissionNames = new ArraySet<>(); 18311 while (opti < args.length) { 18312 permissionNames.add(args[opti]); 18313 opti++; 18314 } 18315 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18316 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18317 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18318 dumpState.setDump(DumpState.DUMP_PREFERRED); 18319 } else if ("preferred-xml".equals(cmd)) { 18320 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18321 if (opti < args.length && "--full".equals(args[opti])) { 18322 fullPreferred = true; 18323 opti++; 18324 } 18325 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18326 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18327 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18328 dumpState.setDump(DumpState.DUMP_PACKAGES); 18329 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18330 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18331 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18332 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18333 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18334 dumpState.setDump(DumpState.DUMP_MESSAGES); 18335 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18336 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18337 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18338 || "intent-filter-verifiers".equals(cmd)) { 18339 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18340 } else if ("version".equals(cmd)) { 18341 dumpState.setDump(DumpState.DUMP_VERSION); 18342 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18343 dumpState.setDump(DumpState.DUMP_KEYSETS); 18344 } else if ("installs".equals(cmd)) { 18345 dumpState.setDump(DumpState.DUMP_INSTALLS); 18346 } else if ("frozen".equals(cmd)) { 18347 dumpState.setDump(DumpState.DUMP_FROZEN); 18348 } else if ("dexopt".equals(cmd)) { 18349 dumpState.setDump(DumpState.DUMP_DEXOPT); 18350 } else if ("write".equals(cmd)) { 18351 synchronized (mPackages) { 18352 mSettings.writeLPr(); 18353 pw.println("Settings written."); 18354 return; 18355 } 18356 } 18357 } 18358 18359 if (checkin) { 18360 pw.println("vers,1"); 18361 } 18362 18363 // reader 18364 synchronized (mPackages) { 18365 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18366 if (!checkin) { 18367 if (dumpState.onTitlePrinted()) 18368 pw.println(); 18369 pw.println("Database versions:"); 18370 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18371 } 18372 } 18373 18374 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18375 if (!checkin) { 18376 if (dumpState.onTitlePrinted()) 18377 pw.println(); 18378 pw.println("Verifiers:"); 18379 pw.print(" Required: "); 18380 pw.print(mRequiredVerifierPackage); 18381 pw.print(" (uid="); 18382 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18383 UserHandle.USER_SYSTEM)); 18384 pw.println(")"); 18385 } else if (mRequiredVerifierPackage != null) { 18386 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18387 pw.print(","); 18388 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18389 UserHandle.USER_SYSTEM)); 18390 } 18391 } 18392 18393 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18394 packageName == null) { 18395 if (mIntentFilterVerifierComponent != null) { 18396 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18397 if (!checkin) { 18398 if (dumpState.onTitlePrinted()) 18399 pw.println(); 18400 pw.println("Intent Filter Verifier:"); 18401 pw.print(" Using: "); 18402 pw.print(verifierPackageName); 18403 pw.print(" (uid="); 18404 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18405 UserHandle.USER_SYSTEM)); 18406 pw.println(")"); 18407 } else if (verifierPackageName != null) { 18408 pw.print("ifv,"); pw.print(verifierPackageName); 18409 pw.print(","); 18410 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18411 UserHandle.USER_SYSTEM)); 18412 } 18413 } else { 18414 pw.println(); 18415 pw.println("No Intent Filter Verifier available!"); 18416 } 18417 } 18418 18419 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18420 boolean printedHeader = false; 18421 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18422 while (it.hasNext()) { 18423 String name = it.next(); 18424 SharedLibraryEntry ent = mSharedLibraries.get(name); 18425 if (!checkin) { 18426 if (!printedHeader) { 18427 if (dumpState.onTitlePrinted()) 18428 pw.println(); 18429 pw.println("Libraries:"); 18430 printedHeader = true; 18431 } 18432 pw.print(" "); 18433 } else { 18434 pw.print("lib,"); 18435 } 18436 pw.print(name); 18437 if (!checkin) { 18438 pw.print(" -> "); 18439 } 18440 if (ent.path != null) { 18441 if (!checkin) { 18442 pw.print("(jar) "); 18443 pw.print(ent.path); 18444 } else { 18445 pw.print(",jar,"); 18446 pw.print(ent.path); 18447 } 18448 } else { 18449 if (!checkin) { 18450 pw.print("(apk) "); 18451 pw.print(ent.apk); 18452 } else { 18453 pw.print(",apk,"); 18454 pw.print(ent.apk); 18455 } 18456 } 18457 pw.println(); 18458 } 18459 } 18460 18461 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18462 if (dumpState.onTitlePrinted()) 18463 pw.println(); 18464 if (!checkin) { 18465 pw.println("Features:"); 18466 } 18467 18468 for (FeatureInfo feat : mAvailableFeatures.values()) { 18469 if (checkin) { 18470 pw.print("feat,"); 18471 pw.print(feat.name); 18472 pw.print(","); 18473 pw.println(feat.version); 18474 } else { 18475 pw.print(" "); 18476 pw.print(feat.name); 18477 if (feat.version > 0) { 18478 pw.print(" version="); 18479 pw.print(feat.version); 18480 } 18481 pw.println(); 18482 } 18483 } 18484 } 18485 18486 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18487 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18488 : "Activity Resolver Table:", " ", packageName, 18489 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18490 dumpState.setTitlePrinted(true); 18491 } 18492 } 18493 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18494 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18495 : "Receiver Resolver Table:", " ", packageName, 18496 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18497 dumpState.setTitlePrinted(true); 18498 } 18499 } 18500 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18501 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18502 : "Service Resolver Table:", " ", packageName, 18503 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18504 dumpState.setTitlePrinted(true); 18505 } 18506 } 18507 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18508 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18509 : "Provider Resolver Table:", " ", packageName, 18510 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18511 dumpState.setTitlePrinted(true); 18512 } 18513 } 18514 18515 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18516 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18517 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18518 int user = mSettings.mPreferredActivities.keyAt(i); 18519 if (pir.dump(pw, 18520 dumpState.getTitlePrinted() 18521 ? "\nPreferred Activities User " + user + ":" 18522 : "Preferred Activities User " + user + ":", " ", 18523 packageName, true, false)) { 18524 dumpState.setTitlePrinted(true); 18525 } 18526 } 18527 } 18528 18529 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18530 pw.flush(); 18531 FileOutputStream fout = new FileOutputStream(fd); 18532 BufferedOutputStream str = new BufferedOutputStream(fout); 18533 XmlSerializer serializer = new FastXmlSerializer(); 18534 try { 18535 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18536 serializer.startDocument(null, true); 18537 serializer.setFeature( 18538 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18539 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18540 serializer.endDocument(); 18541 serializer.flush(); 18542 } catch (IllegalArgumentException e) { 18543 pw.println("Failed writing: " + e); 18544 } catch (IllegalStateException e) { 18545 pw.println("Failed writing: " + e); 18546 } catch (IOException e) { 18547 pw.println("Failed writing: " + e); 18548 } 18549 } 18550 18551 if (!checkin 18552 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18553 && packageName == null) { 18554 pw.println(); 18555 int count = mSettings.mPackages.size(); 18556 if (count == 0) { 18557 pw.println("No applications!"); 18558 pw.println(); 18559 } else { 18560 final String prefix = " "; 18561 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18562 if (allPackageSettings.size() == 0) { 18563 pw.println("No domain preferred apps!"); 18564 pw.println(); 18565 } else { 18566 pw.println("App verification status:"); 18567 pw.println(); 18568 count = 0; 18569 for (PackageSetting ps : allPackageSettings) { 18570 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18571 if (ivi == null || ivi.getPackageName() == null) continue; 18572 pw.println(prefix + "Package: " + ivi.getPackageName()); 18573 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18574 pw.println(prefix + "Status: " + ivi.getStatusString()); 18575 pw.println(); 18576 count++; 18577 } 18578 if (count == 0) { 18579 pw.println(prefix + "No app verification established."); 18580 pw.println(); 18581 } 18582 for (int userId : sUserManager.getUserIds()) { 18583 pw.println("App linkages for user " + userId + ":"); 18584 pw.println(); 18585 count = 0; 18586 for (PackageSetting ps : allPackageSettings) { 18587 final long status = ps.getDomainVerificationStatusForUser(userId); 18588 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18589 continue; 18590 } 18591 pw.println(prefix + "Package: " + ps.name); 18592 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18593 String statusStr = IntentFilterVerificationInfo. 18594 getStatusStringFromValue(status); 18595 pw.println(prefix + "Status: " + statusStr); 18596 pw.println(); 18597 count++; 18598 } 18599 if (count == 0) { 18600 pw.println(prefix + "No configured app linkages."); 18601 pw.println(); 18602 } 18603 } 18604 } 18605 } 18606 } 18607 18608 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18609 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18610 if (packageName == null && permissionNames == null) { 18611 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18612 if (iperm == 0) { 18613 if (dumpState.onTitlePrinted()) 18614 pw.println(); 18615 pw.println("AppOp Permissions:"); 18616 } 18617 pw.print(" AppOp Permission "); 18618 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18619 pw.println(":"); 18620 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18621 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18622 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18623 } 18624 } 18625 } 18626 } 18627 18628 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18629 boolean printedSomething = false; 18630 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18631 if (packageName != null && !packageName.equals(p.info.packageName)) { 18632 continue; 18633 } 18634 if (!printedSomething) { 18635 if (dumpState.onTitlePrinted()) 18636 pw.println(); 18637 pw.println("Registered ContentProviders:"); 18638 printedSomething = true; 18639 } 18640 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18641 pw.print(" "); pw.println(p.toString()); 18642 } 18643 printedSomething = false; 18644 for (Map.Entry<String, PackageParser.Provider> entry : 18645 mProvidersByAuthority.entrySet()) { 18646 PackageParser.Provider p = entry.getValue(); 18647 if (packageName != null && !packageName.equals(p.info.packageName)) { 18648 continue; 18649 } 18650 if (!printedSomething) { 18651 if (dumpState.onTitlePrinted()) 18652 pw.println(); 18653 pw.println("ContentProvider Authorities:"); 18654 printedSomething = true; 18655 } 18656 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18657 pw.print(" "); pw.println(p.toString()); 18658 if (p.info != null && p.info.applicationInfo != null) { 18659 final String appInfo = p.info.applicationInfo.toString(); 18660 pw.print(" applicationInfo="); pw.println(appInfo); 18661 } 18662 } 18663 } 18664 18665 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18666 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18667 } 18668 18669 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18670 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18671 } 18672 18673 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18674 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18675 } 18676 18677 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18678 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18679 } 18680 18681 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18682 // XXX should handle packageName != null by dumping only install data that 18683 // the given package is involved with. 18684 if (dumpState.onTitlePrinted()) pw.println(); 18685 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18686 } 18687 18688 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18689 // XXX should handle packageName != null by dumping only install data that 18690 // the given package is involved with. 18691 if (dumpState.onTitlePrinted()) pw.println(); 18692 18693 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18694 ipw.println(); 18695 ipw.println("Frozen packages:"); 18696 ipw.increaseIndent(); 18697 if (mFrozenPackages.size() == 0) { 18698 ipw.println("(none)"); 18699 } else { 18700 for (int i = 0; i < mFrozenPackages.size(); i++) { 18701 ipw.println(mFrozenPackages.valueAt(i)); 18702 } 18703 } 18704 ipw.decreaseIndent(); 18705 } 18706 18707 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18708 if (dumpState.onTitlePrinted()) pw.println(); 18709 dumpDexoptStateLPr(pw, packageName); 18710 } 18711 18712 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18713 if (dumpState.onTitlePrinted()) pw.println(); 18714 mSettings.dumpReadMessagesLPr(pw, dumpState); 18715 18716 pw.println(); 18717 pw.println("Package warning messages:"); 18718 BufferedReader in = null; 18719 String line = null; 18720 try { 18721 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18722 while ((line = in.readLine()) != null) { 18723 if (line.contains("ignored: updated version")) continue; 18724 pw.println(line); 18725 } 18726 } catch (IOException ignored) { 18727 } finally { 18728 IoUtils.closeQuietly(in); 18729 } 18730 } 18731 18732 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18733 BufferedReader in = null; 18734 String line = null; 18735 try { 18736 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18737 while ((line = in.readLine()) != null) { 18738 if (line.contains("ignored: updated version")) continue; 18739 pw.print("msg,"); 18740 pw.println(line); 18741 } 18742 } catch (IOException ignored) { 18743 } finally { 18744 IoUtils.closeQuietly(in); 18745 } 18746 } 18747 } 18748 } 18749 18750 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18751 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18752 ipw.println(); 18753 ipw.println("Dexopt state:"); 18754 ipw.increaseIndent(); 18755 Collection<PackageParser.Package> packages = null; 18756 if (packageName != null) { 18757 PackageParser.Package targetPackage = mPackages.get(packageName); 18758 if (targetPackage != null) { 18759 packages = Collections.singletonList(targetPackage); 18760 } else { 18761 ipw.println("Unable to find package: " + packageName); 18762 return; 18763 } 18764 } else { 18765 packages = mPackages.values(); 18766 } 18767 18768 for (PackageParser.Package pkg : packages) { 18769 ipw.println("[" + pkg.packageName + "]"); 18770 ipw.increaseIndent(); 18771 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18772 ipw.decreaseIndent(); 18773 } 18774 } 18775 18776 private String dumpDomainString(String packageName) { 18777 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18778 .getList(); 18779 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18780 18781 ArraySet<String> result = new ArraySet<>(); 18782 if (iviList.size() > 0) { 18783 for (IntentFilterVerificationInfo ivi : iviList) { 18784 for (String host : ivi.getDomains()) { 18785 result.add(host); 18786 } 18787 } 18788 } 18789 if (filters != null && filters.size() > 0) { 18790 for (IntentFilter filter : filters) { 18791 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18792 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18793 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18794 result.addAll(filter.getHostsList()); 18795 } 18796 } 18797 } 18798 18799 StringBuilder sb = new StringBuilder(result.size() * 16); 18800 for (String domain : result) { 18801 if (sb.length() > 0) sb.append(" "); 18802 sb.append(domain); 18803 } 18804 return sb.toString(); 18805 } 18806 18807 // ------- apps on sdcard specific code ------- 18808 static final boolean DEBUG_SD_INSTALL = false; 18809 18810 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18811 18812 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18813 18814 private boolean mMediaMounted = false; 18815 18816 static String getEncryptKey() { 18817 try { 18818 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18819 SD_ENCRYPTION_KEYSTORE_NAME); 18820 if (sdEncKey == null) { 18821 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18822 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18823 if (sdEncKey == null) { 18824 Slog.e(TAG, "Failed to create encryption keys"); 18825 return null; 18826 } 18827 } 18828 return sdEncKey; 18829 } catch (NoSuchAlgorithmException nsae) { 18830 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18831 return null; 18832 } catch (IOException ioe) { 18833 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18834 return null; 18835 } 18836 } 18837 18838 /* 18839 * Update media status on PackageManager. 18840 */ 18841 @Override 18842 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18843 int callingUid = Binder.getCallingUid(); 18844 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18845 throw new SecurityException("Media status can only be updated by the system"); 18846 } 18847 // reader; this apparently protects mMediaMounted, but should probably 18848 // be a different lock in that case. 18849 synchronized (mPackages) { 18850 Log.i(TAG, "Updating external media status from " 18851 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18852 + (mediaStatus ? "mounted" : "unmounted")); 18853 if (DEBUG_SD_INSTALL) 18854 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18855 + ", mMediaMounted=" + mMediaMounted); 18856 if (mediaStatus == mMediaMounted) { 18857 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18858 : 0, -1); 18859 mHandler.sendMessage(msg); 18860 return; 18861 } 18862 mMediaMounted = mediaStatus; 18863 } 18864 // Queue up an async operation since the package installation may take a 18865 // little while. 18866 mHandler.post(new Runnable() { 18867 public void run() { 18868 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18869 } 18870 }); 18871 } 18872 18873 /** 18874 * Called by MountService when the initial ASECs to scan are available. 18875 * Should block until all the ASEC containers are finished being scanned. 18876 */ 18877 public void scanAvailableAsecs() { 18878 updateExternalMediaStatusInner(true, false, false); 18879 } 18880 18881 /* 18882 * Collect information of applications on external media, map them against 18883 * existing containers and update information based on current mount status. 18884 * Please note that we always have to report status if reportStatus has been 18885 * set to true especially when unloading packages. 18886 */ 18887 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18888 boolean externalStorage) { 18889 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18890 int[] uidArr = EmptyArray.INT; 18891 18892 final String[] list = PackageHelper.getSecureContainerList(); 18893 if (ArrayUtils.isEmpty(list)) { 18894 Log.i(TAG, "No secure containers found"); 18895 } else { 18896 // Process list of secure containers and categorize them 18897 // as active or stale based on their package internal state. 18898 18899 // reader 18900 synchronized (mPackages) { 18901 for (String cid : list) { 18902 // Leave stages untouched for now; installer service owns them 18903 if (PackageInstallerService.isStageName(cid)) continue; 18904 18905 if (DEBUG_SD_INSTALL) 18906 Log.i(TAG, "Processing container " + cid); 18907 String pkgName = getAsecPackageName(cid); 18908 if (pkgName == null) { 18909 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18910 continue; 18911 } 18912 if (DEBUG_SD_INSTALL) 18913 Log.i(TAG, "Looking for pkg : " + pkgName); 18914 18915 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18916 if (ps == null) { 18917 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18918 continue; 18919 } 18920 18921 /* 18922 * Skip packages that are not external if we're unmounting 18923 * external storage. 18924 */ 18925 if (externalStorage && !isMounted && !isExternal(ps)) { 18926 continue; 18927 } 18928 18929 final AsecInstallArgs args = new AsecInstallArgs(cid, 18930 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18931 // The package status is changed only if the code path 18932 // matches between settings and the container id. 18933 if (ps.codePathString != null 18934 && ps.codePathString.startsWith(args.getCodePath())) { 18935 if (DEBUG_SD_INSTALL) { 18936 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18937 + " at code path: " + ps.codePathString); 18938 } 18939 18940 // We do have a valid package installed on sdcard 18941 processCids.put(args, ps.codePathString); 18942 final int uid = ps.appId; 18943 if (uid != -1) { 18944 uidArr = ArrayUtils.appendInt(uidArr, uid); 18945 } 18946 } else { 18947 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18948 + ps.codePathString); 18949 } 18950 } 18951 } 18952 18953 Arrays.sort(uidArr); 18954 } 18955 18956 // Process packages with valid entries. 18957 if (isMounted) { 18958 if (DEBUG_SD_INSTALL) 18959 Log.i(TAG, "Loading packages"); 18960 loadMediaPackages(processCids, uidArr, externalStorage); 18961 startCleaningPackages(); 18962 mInstallerService.onSecureContainersAvailable(); 18963 } else { 18964 if (DEBUG_SD_INSTALL) 18965 Log.i(TAG, "Unloading packages"); 18966 unloadMediaPackages(processCids, uidArr, reportStatus); 18967 } 18968 } 18969 18970 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18971 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18972 final int size = infos.size(); 18973 final String[] packageNames = new String[size]; 18974 final int[] packageUids = new int[size]; 18975 for (int i = 0; i < size; i++) { 18976 final ApplicationInfo info = infos.get(i); 18977 packageNames[i] = info.packageName; 18978 packageUids[i] = info.uid; 18979 } 18980 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18981 finishedReceiver); 18982 } 18983 18984 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18985 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18986 sendResourcesChangedBroadcast(mediaStatus, replacing, 18987 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18988 } 18989 18990 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18991 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18992 int size = pkgList.length; 18993 if (size > 0) { 18994 // Send broadcasts here 18995 Bundle extras = new Bundle(); 18996 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18997 if (uidArr != null) { 18998 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18999 } 19000 if (replacing) { 19001 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19002 } 19003 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19004 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19005 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19006 } 19007 } 19008 19009 /* 19010 * Look at potentially valid container ids from processCids If package 19011 * information doesn't match the one on record or package scanning fails, 19012 * the cid is added to list of removeCids. We currently don't delete stale 19013 * containers. 19014 */ 19015 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19016 boolean externalStorage) { 19017 ArrayList<String> pkgList = new ArrayList<String>(); 19018 Set<AsecInstallArgs> keys = processCids.keySet(); 19019 19020 for (AsecInstallArgs args : keys) { 19021 String codePath = processCids.get(args); 19022 if (DEBUG_SD_INSTALL) 19023 Log.i(TAG, "Loading container : " + args.cid); 19024 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19025 try { 19026 // Make sure there are no container errors first. 19027 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19028 Slog.e(TAG, "Failed to mount cid : " + args.cid 19029 + " when installing from sdcard"); 19030 continue; 19031 } 19032 // Check code path here. 19033 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19034 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19035 + " does not match one in settings " + codePath); 19036 continue; 19037 } 19038 // Parse package 19039 int parseFlags = mDefParseFlags; 19040 if (args.isExternalAsec()) { 19041 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19042 } 19043 if (args.isFwdLocked()) { 19044 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19045 } 19046 19047 synchronized (mInstallLock) { 19048 PackageParser.Package pkg = null; 19049 try { 19050 // Sadly we don't know the package name yet to freeze it 19051 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19052 SCAN_IGNORE_FROZEN, 0, null); 19053 } catch (PackageManagerException e) { 19054 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19055 } 19056 // Scan the package 19057 if (pkg != null) { 19058 /* 19059 * TODO why is the lock being held? doPostInstall is 19060 * called in other places without the lock. This needs 19061 * to be straightened out. 19062 */ 19063 // writer 19064 synchronized (mPackages) { 19065 retCode = PackageManager.INSTALL_SUCCEEDED; 19066 pkgList.add(pkg.packageName); 19067 // Post process args 19068 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19069 pkg.applicationInfo.uid); 19070 } 19071 } else { 19072 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19073 } 19074 } 19075 19076 } finally { 19077 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19078 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19079 } 19080 } 19081 } 19082 // writer 19083 synchronized (mPackages) { 19084 // If the platform SDK has changed since the last time we booted, 19085 // we need to re-grant app permission to catch any new ones that 19086 // appear. This is really a hack, and means that apps can in some 19087 // cases get permissions that the user didn't initially explicitly 19088 // allow... it would be nice to have some better way to handle 19089 // this situation. 19090 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19091 : mSettings.getInternalVersion(); 19092 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19093 : StorageManager.UUID_PRIVATE_INTERNAL; 19094 19095 int updateFlags = UPDATE_PERMISSIONS_ALL; 19096 if (ver.sdkVersion != mSdkVersion) { 19097 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19098 + mSdkVersion + "; regranting permissions for external"); 19099 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19100 } 19101 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19102 19103 // Yay, everything is now upgraded 19104 ver.forceCurrent(); 19105 19106 // can downgrade to reader 19107 // Persist settings 19108 mSettings.writeLPr(); 19109 } 19110 // Send a broadcast to let everyone know we are done processing 19111 if (pkgList.size() > 0) { 19112 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19113 } 19114 } 19115 19116 /* 19117 * Utility method to unload a list of specified containers 19118 */ 19119 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19120 // Just unmount all valid containers. 19121 for (AsecInstallArgs arg : cidArgs) { 19122 synchronized (mInstallLock) { 19123 arg.doPostDeleteLI(false); 19124 } 19125 } 19126 } 19127 19128 /* 19129 * Unload packages mounted on external media. This involves deleting package 19130 * data from internal structures, sending broadcasts about disabled packages, 19131 * gc'ing to free up references, unmounting all secure containers 19132 * corresponding to packages on external media, and posting a 19133 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19134 * that we always have to post this message if status has been requested no 19135 * matter what. 19136 */ 19137 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19138 final boolean reportStatus) { 19139 if (DEBUG_SD_INSTALL) 19140 Log.i(TAG, "unloading media packages"); 19141 ArrayList<String> pkgList = new ArrayList<String>(); 19142 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19143 final Set<AsecInstallArgs> keys = processCids.keySet(); 19144 for (AsecInstallArgs args : keys) { 19145 String pkgName = args.getPackageName(); 19146 if (DEBUG_SD_INSTALL) 19147 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19148 // Delete package internally 19149 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19150 synchronized (mInstallLock) { 19151 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19152 final boolean res; 19153 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19154 "unloadMediaPackages")) { 19155 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19156 null); 19157 } 19158 if (res) { 19159 pkgList.add(pkgName); 19160 } else { 19161 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19162 failedList.add(args); 19163 } 19164 } 19165 } 19166 19167 // reader 19168 synchronized (mPackages) { 19169 // We didn't update the settings after removing each package; 19170 // write them now for all packages. 19171 mSettings.writeLPr(); 19172 } 19173 19174 // We have to absolutely send UPDATED_MEDIA_STATUS only 19175 // after confirming that all the receivers processed the ordered 19176 // broadcast when packages get disabled, force a gc to clean things up. 19177 // and unload all the containers. 19178 if (pkgList.size() > 0) { 19179 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19180 new IIntentReceiver.Stub() { 19181 public void performReceive(Intent intent, int resultCode, String data, 19182 Bundle extras, boolean ordered, boolean sticky, 19183 int sendingUser) throws RemoteException { 19184 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19185 reportStatus ? 1 : 0, 1, keys); 19186 mHandler.sendMessage(msg); 19187 } 19188 }); 19189 } else { 19190 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19191 keys); 19192 mHandler.sendMessage(msg); 19193 } 19194 } 19195 19196 private void loadPrivatePackages(final VolumeInfo vol) { 19197 mHandler.post(new Runnable() { 19198 @Override 19199 public void run() { 19200 loadPrivatePackagesInner(vol); 19201 } 19202 }); 19203 } 19204 19205 private void loadPrivatePackagesInner(VolumeInfo vol) { 19206 final String volumeUuid = vol.fsUuid; 19207 if (TextUtils.isEmpty(volumeUuid)) { 19208 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19209 return; 19210 } 19211 19212 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19213 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19214 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19215 19216 final VersionInfo ver; 19217 final List<PackageSetting> packages; 19218 synchronized (mPackages) { 19219 ver = mSettings.findOrCreateVersion(volumeUuid); 19220 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19221 } 19222 19223 for (PackageSetting ps : packages) { 19224 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19225 synchronized (mInstallLock) { 19226 final PackageParser.Package pkg; 19227 try { 19228 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19229 loaded.add(pkg.applicationInfo); 19230 19231 } catch (PackageManagerException e) { 19232 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19233 } 19234 19235 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19236 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19237 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19238 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19239 } 19240 } 19241 } 19242 19243 // Reconcile app data for all started/unlocked users 19244 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19245 final UserManager um = mContext.getSystemService(UserManager.class); 19246 UserManagerInternal umInternal = getUserManagerInternal(); 19247 for (UserInfo user : um.getUsers()) { 19248 final int flags; 19249 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19250 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19251 } else if (umInternal.isUserRunning(user.id)) { 19252 flags = StorageManager.FLAG_STORAGE_DE; 19253 } else { 19254 continue; 19255 } 19256 19257 try { 19258 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19259 synchronized (mInstallLock) { 19260 reconcileAppsDataLI(volumeUuid, user.id, flags); 19261 } 19262 } catch (IllegalStateException e) { 19263 // Device was probably ejected, and we'll process that event momentarily 19264 Slog.w(TAG, "Failed to prepare storage: " + e); 19265 } 19266 } 19267 19268 synchronized (mPackages) { 19269 int updateFlags = UPDATE_PERMISSIONS_ALL; 19270 if (ver.sdkVersion != mSdkVersion) { 19271 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19272 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19273 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19274 } 19275 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19276 19277 // Yay, everything is now upgraded 19278 ver.forceCurrent(); 19279 19280 mSettings.writeLPr(); 19281 } 19282 19283 for (PackageFreezer freezer : freezers) { 19284 freezer.close(); 19285 } 19286 19287 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19288 sendResourcesChangedBroadcast(true, false, loaded, null); 19289 } 19290 19291 private void unloadPrivatePackages(final VolumeInfo vol) { 19292 mHandler.post(new Runnable() { 19293 @Override 19294 public void run() { 19295 unloadPrivatePackagesInner(vol); 19296 } 19297 }); 19298 } 19299 19300 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19301 final String volumeUuid = vol.fsUuid; 19302 if (TextUtils.isEmpty(volumeUuid)) { 19303 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19304 return; 19305 } 19306 19307 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19308 synchronized (mInstallLock) { 19309 synchronized (mPackages) { 19310 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19311 for (PackageSetting ps : packages) { 19312 if (ps.pkg == null) continue; 19313 19314 final ApplicationInfo info = ps.pkg.applicationInfo; 19315 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19316 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19317 19318 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19319 "unloadPrivatePackagesInner")) { 19320 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19321 false, null)) { 19322 unloaded.add(info); 19323 } else { 19324 Slog.w(TAG, "Failed to unload " + ps.codePath); 19325 } 19326 } 19327 19328 // Try very hard to release any references to this package 19329 // so we don't risk the system server being killed due to 19330 // open FDs 19331 AttributeCache.instance().removePackage(ps.name); 19332 } 19333 19334 mSettings.writeLPr(); 19335 } 19336 } 19337 19338 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19339 sendResourcesChangedBroadcast(false, false, unloaded, null); 19340 19341 // Try very hard to release any references to this path so we don't risk 19342 // the system server being killed due to open FDs 19343 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19344 19345 for (int i = 0; i < 3; i++) { 19346 System.gc(); 19347 System.runFinalization(); 19348 } 19349 } 19350 19351 /** 19352 * Prepare storage areas for given user on all mounted devices. 19353 */ 19354 void prepareUserData(int userId, int userSerial, int flags) { 19355 synchronized (mInstallLock) { 19356 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19357 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19358 final String volumeUuid = vol.getFsUuid(); 19359 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19360 } 19361 } 19362 } 19363 19364 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19365 boolean allowRecover) { 19366 // Prepare storage and verify that serial numbers are consistent; if 19367 // there's a mismatch we need to destroy to avoid leaking data 19368 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19369 try { 19370 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19371 19372 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19373 UserManagerService.enforceSerialNumber( 19374 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19375 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19376 UserManagerService.enforceSerialNumber( 19377 Environment.getDataSystemDeDirectory(userId), userSerial); 19378 } 19379 } 19380 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19381 UserManagerService.enforceSerialNumber( 19382 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19383 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19384 UserManagerService.enforceSerialNumber( 19385 Environment.getDataSystemCeDirectory(userId), userSerial); 19386 } 19387 } 19388 19389 synchronized (mInstallLock) { 19390 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19391 } 19392 } catch (Exception e) { 19393 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19394 + " because we failed to prepare: " + e); 19395 destroyUserDataLI(volumeUuid, userId, 19396 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19397 19398 if (allowRecover) { 19399 // Try one last time; if we fail again we're really in trouble 19400 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19401 } 19402 } 19403 } 19404 19405 /** 19406 * Destroy storage areas for given user on all mounted devices. 19407 */ 19408 void destroyUserData(int userId, int flags) { 19409 synchronized (mInstallLock) { 19410 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19411 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19412 final String volumeUuid = vol.getFsUuid(); 19413 destroyUserDataLI(volumeUuid, userId, flags); 19414 } 19415 } 19416 } 19417 19418 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19419 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19420 try { 19421 // Clean up app data, profile data, and media data 19422 mInstaller.destroyUserData(volumeUuid, userId, flags); 19423 19424 // Clean up system data 19425 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19426 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19427 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19428 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19429 } 19430 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19431 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19432 } 19433 } 19434 19435 // Data with special labels is now gone, so finish the job 19436 storage.destroyUserStorage(volumeUuid, userId, flags); 19437 19438 } catch (Exception e) { 19439 logCriticalInfo(Log.WARN, 19440 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19441 } 19442 } 19443 19444 /** 19445 * Examine all users present on given mounted volume, and destroy data 19446 * belonging to users that are no longer valid, or whose user ID has been 19447 * recycled. 19448 */ 19449 private void reconcileUsers(String volumeUuid) { 19450 final List<File> files = new ArrayList<>(); 19451 Collections.addAll(files, FileUtils 19452 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19453 Collections.addAll(files, FileUtils 19454 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19455 Collections.addAll(files, FileUtils 19456 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19457 Collections.addAll(files, FileUtils 19458 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19459 for (File file : files) { 19460 if (!file.isDirectory()) continue; 19461 19462 final int userId; 19463 final UserInfo info; 19464 try { 19465 userId = Integer.parseInt(file.getName()); 19466 info = sUserManager.getUserInfo(userId); 19467 } catch (NumberFormatException e) { 19468 Slog.w(TAG, "Invalid user directory " + file); 19469 continue; 19470 } 19471 19472 boolean destroyUser = false; 19473 if (info == null) { 19474 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19475 + " because no matching user was found"); 19476 destroyUser = true; 19477 } else if (!mOnlyCore) { 19478 try { 19479 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19480 } catch (IOException e) { 19481 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19482 + " because we failed to enforce serial number: " + e); 19483 destroyUser = true; 19484 } 19485 } 19486 19487 if (destroyUser) { 19488 synchronized (mInstallLock) { 19489 destroyUserDataLI(volumeUuid, userId, 19490 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19491 } 19492 } 19493 } 19494 } 19495 19496 private void assertPackageKnown(String volumeUuid, String packageName) 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 } 19507 } 19508 } 19509 19510 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19511 throws PackageManagerException { 19512 synchronized (mPackages) { 19513 final PackageSetting ps = mSettings.mPackages.get(packageName); 19514 if (ps == null) { 19515 throw new PackageManagerException("Package " + packageName + " is unknown"); 19516 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19517 throw new PackageManagerException( 19518 "Package " + packageName + " found on unknown volume " + volumeUuid 19519 + "; expected volume " + ps.volumeUuid); 19520 } else if (!ps.getInstalled(userId)) { 19521 throw new PackageManagerException( 19522 "Package " + packageName + " not installed for user " + userId); 19523 } 19524 } 19525 } 19526 19527 /** 19528 * Examine all apps present on given mounted volume, and destroy apps that 19529 * aren't expected, either due to uninstallation or reinstallation on 19530 * another volume. 19531 */ 19532 private void reconcileApps(String volumeUuid) { 19533 final File[] files = FileUtils 19534 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19535 for (File file : files) { 19536 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19537 && !PackageInstallerService.isStageName(file.getName()); 19538 if (!isPackage) { 19539 // Ignore entries which are not packages 19540 continue; 19541 } 19542 19543 try { 19544 final PackageLite pkg = PackageParser.parsePackageLite(file, 19545 PackageParser.PARSE_MUST_BE_APK); 19546 assertPackageKnown(volumeUuid, pkg.packageName); 19547 19548 } catch (PackageParserException | PackageManagerException e) { 19549 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19550 synchronized (mInstallLock) { 19551 removeCodePathLI(file); 19552 } 19553 } 19554 } 19555 } 19556 19557 /** 19558 * Reconcile all app data for the given user. 19559 * <p> 19560 * Verifies that directories exist and that ownership and labeling is 19561 * correct for all installed apps on all mounted volumes. 19562 */ 19563 void reconcileAppsData(int userId, int flags) { 19564 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19565 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19566 final String volumeUuid = vol.getFsUuid(); 19567 synchronized (mInstallLock) { 19568 reconcileAppsDataLI(volumeUuid, userId, flags); 19569 } 19570 } 19571 } 19572 19573 /** 19574 * Reconcile all app data on given mounted volume. 19575 * <p> 19576 * Destroys app data that isn't expected, either due to uninstallation or 19577 * reinstallation on another volume. 19578 * <p> 19579 * Verifies that directories exist and that ownership and labeling is 19580 * correct for all installed apps. 19581 */ 19582 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19583 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19584 + Integer.toHexString(flags)); 19585 19586 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19587 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19588 19589 boolean restoreconNeeded = false; 19590 19591 // First look for stale data that doesn't belong, and check if things 19592 // have changed since we did our last restorecon 19593 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19594 if (StorageManager.isFileEncryptedNativeOrEmulated() 19595 && !StorageManager.isUserKeyUnlocked(userId)) { 19596 throw new RuntimeException( 19597 "Yikes, someone asked us to reconcile CE storage while " + userId 19598 + " was still locked; this would have caused massive data loss!"); 19599 } 19600 19601 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19602 19603 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19604 for (File file : files) { 19605 final String packageName = file.getName(); 19606 try { 19607 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19608 } catch (PackageManagerException e) { 19609 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19610 try { 19611 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19612 StorageManager.FLAG_STORAGE_CE, 0); 19613 } catch (InstallerException e2) { 19614 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19615 } 19616 } 19617 } 19618 } 19619 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19620 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19621 19622 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19623 for (File file : files) { 19624 final String packageName = file.getName(); 19625 try { 19626 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19627 } catch (PackageManagerException e) { 19628 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19629 try { 19630 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19631 StorageManager.FLAG_STORAGE_DE, 0); 19632 } catch (InstallerException e2) { 19633 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19634 } 19635 } 19636 } 19637 } 19638 19639 // Ensure that data directories are ready to roll for all packages 19640 // installed for this volume and user 19641 final List<PackageSetting> packages; 19642 synchronized (mPackages) { 19643 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19644 } 19645 int preparedCount = 0; 19646 for (PackageSetting ps : packages) { 19647 final String packageName = ps.name; 19648 if (ps.pkg == null) { 19649 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19650 // TODO: might be due to legacy ASEC apps; we should circle back 19651 // and reconcile again once they're scanned 19652 continue; 19653 } 19654 19655 if (ps.getInstalled(userId)) { 19656 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19657 19658 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19659 // We may have just shuffled around app data directories, so 19660 // prepare them one more time 19661 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19662 } 19663 19664 preparedCount++; 19665 } 19666 } 19667 19668 if (restoreconNeeded) { 19669 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19670 SELinuxMMAC.setRestoreconDone(ceDir); 19671 } 19672 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19673 SELinuxMMAC.setRestoreconDone(deDir); 19674 } 19675 } 19676 19677 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19678 + " packages; restoreconNeeded was " + restoreconNeeded); 19679 } 19680 19681 /** 19682 * Prepare app data for the given app just after it was installed or 19683 * upgraded. This method carefully only touches users that it's installed 19684 * for, and it forces a restorecon to handle any seinfo changes. 19685 * <p> 19686 * Verifies that directories exist and that ownership and labeling is 19687 * correct for all installed apps. If there is an ownership mismatch, it 19688 * will try recovering system apps by wiping data; third-party app data is 19689 * left intact. 19690 * <p> 19691 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19692 */ 19693 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19694 final PackageSetting ps; 19695 synchronized (mPackages) { 19696 ps = mSettings.mPackages.get(pkg.packageName); 19697 mSettings.writeKernelMappingLPr(ps); 19698 } 19699 19700 final UserManager um = mContext.getSystemService(UserManager.class); 19701 UserManagerInternal umInternal = getUserManagerInternal(); 19702 for (UserInfo user : um.getUsers()) { 19703 final int flags; 19704 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19705 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19706 } else if (umInternal.isUserRunning(user.id)) { 19707 flags = StorageManager.FLAG_STORAGE_DE; 19708 } else { 19709 continue; 19710 } 19711 19712 if (ps.getInstalled(user.id)) { 19713 // Whenever an app changes, force a restorecon of its data 19714 // TODO: when user data is locked, mark that we're still dirty 19715 prepareAppDataLIF(pkg, user.id, flags, true); 19716 } 19717 } 19718 } 19719 19720 /** 19721 * Prepare app data for the given app. 19722 * <p> 19723 * Verifies that directories exist and that ownership and labeling is 19724 * correct for all installed apps. If there is an ownership mismatch, this 19725 * will try recovering system apps by wiping data; third-party app data is 19726 * left intact. 19727 */ 19728 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19729 boolean restoreconNeeded) { 19730 if (pkg == null) { 19731 Slog.wtf(TAG, "Package was null!", new Throwable()); 19732 return; 19733 } 19734 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19735 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19736 for (int i = 0; i < childCount; i++) { 19737 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19738 } 19739 } 19740 19741 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19742 boolean restoreconNeeded) { 19743 if (DEBUG_APP_DATA) { 19744 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19745 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19746 } 19747 19748 final String volumeUuid = pkg.volumeUuid; 19749 final String packageName = pkg.packageName; 19750 final ApplicationInfo app = pkg.applicationInfo; 19751 final int appId = UserHandle.getAppId(app.uid); 19752 19753 Preconditions.checkNotNull(app.seinfo); 19754 19755 try { 19756 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19757 appId, app.seinfo, app.targetSdkVersion); 19758 } catch (InstallerException e) { 19759 if (app.isSystemApp()) { 19760 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19761 + ", but trying to recover: " + e); 19762 destroyAppDataLeafLIF(pkg, userId, flags); 19763 try { 19764 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19765 appId, app.seinfo, app.targetSdkVersion); 19766 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19767 } catch (InstallerException e2) { 19768 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19769 } 19770 } else { 19771 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19772 } 19773 } 19774 19775 if (restoreconNeeded) { 19776 try { 19777 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19778 app.seinfo); 19779 } catch (InstallerException e) { 19780 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19781 } 19782 } 19783 19784 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19785 try { 19786 // CE storage is unlocked right now, so read out the inode and 19787 // remember for use later when it's locked 19788 // TODO: mark this structure as dirty so we persist it! 19789 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19790 StorageManager.FLAG_STORAGE_CE); 19791 synchronized (mPackages) { 19792 final PackageSetting ps = mSettings.mPackages.get(packageName); 19793 if (ps != null) { 19794 ps.setCeDataInode(ceDataInode, userId); 19795 } 19796 } 19797 } catch (InstallerException e) { 19798 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19799 } 19800 } 19801 19802 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19803 } 19804 19805 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19806 if (pkg == null) { 19807 Slog.wtf(TAG, "Package was null!", new Throwable()); 19808 return; 19809 } 19810 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19811 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19812 for (int i = 0; i < childCount; i++) { 19813 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19814 } 19815 } 19816 19817 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19818 final String volumeUuid = pkg.volumeUuid; 19819 final String packageName = pkg.packageName; 19820 final ApplicationInfo app = pkg.applicationInfo; 19821 19822 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19823 // Create a native library symlink only if we have native libraries 19824 // and if the native libraries are 32 bit libraries. We do not provide 19825 // this symlink for 64 bit libraries. 19826 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19827 final String nativeLibPath = app.nativeLibraryDir; 19828 try { 19829 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19830 nativeLibPath, userId); 19831 } catch (InstallerException e) { 19832 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19833 } 19834 } 19835 } 19836 } 19837 19838 /** 19839 * For system apps on non-FBE devices, this method migrates any existing 19840 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19841 * requested by the app. 19842 */ 19843 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19844 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19845 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19846 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19847 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19848 try { 19849 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19850 storageTarget); 19851 } catch (InstallerException e) { 19852 logCriticalInfo(Log.WARN, 19853 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19854 } 19855 return true; 19856 } else { 19857 return false; 19858 } 19859 } 19860 19861 public PackageFreezer freezePackage(String packageName, String killReason) { 19862 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19863 } 19864 19865 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19866 return new PackageFreezer(packageName, userId, killReason); 19867 } 19868 19869 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19870 String killReason) { 19871 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19872 } 19873 19874 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19875 String killReason) { 19876 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19877 return new PackageFreezer(); 19878 } else { 19879 return freezePackage(packageName, userId, killReason); 19880 } 19881 } 19882 19883 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19884 String killReason) { 19885 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19886 } 19887 19888 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19889 String killReason) { 19890 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19891 return new PackageFreezer(); 19892 } else { 19893 return freezePackage(packageName, userId, killReason); 19894 } 19895 } 19896 19897 /** 19898 * Class that freezes and kills the given package upon creation, and 19899 * unfreezes it upon closing. This is typically used when doing surgery on 19900 * app code/data to prevent the app from running while you're working. 19901 */ 19902 private class PackageFreezer implements AutoCloseable { 19903 private final String mPackageName; 19904 private final PackageFreezer[] mChildren; 19905 19906 private final boolean mWeFroze; 19907 19908 private final AtomicBoolean mClosed = new AtomicBoolean(); 19909 private final CloseGuard mCloseGuard = CloseGuard.get(); 19910 19911 /** 19912 * Create and return a stub freezer that doesn't actually do anything, 19913 * typically used when someone requested 19914 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19915 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19916 */ 19917 public PackageFreezer() { 19918 mPackageName = null; 19919 mChildren = null; 19920 mWeFroze = false; 19921 mCloseGuard.open("close"); 19922 } 19923 19924 public PackageFreezer(String packageName, int userId, String killReason) { 19925 synchronized (mPackages) { 19926 mPackageName = packageName; 19927 mWeFroze = mFrozenPackages.add(mPackageName); 19928 19929 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19930 if (ps != null) { 19931 killApplication(ps.name, ps.appId, userId, killReason); 19932 } 19933 19934 final PackageParser.Package p = mPackages.get(packageName); 19935 if (p != null && p.childPackages != null) { 19936 final int N = p.childPackages.size(); 19937 mChildren = new PackageFreezer[N]; 19938 for (int i = 0; i < N; i++) { 19939 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19940 userId, killReason); 19941 } 19942 } else { 19943 mChildren = null; 19944 } 19945 } 19946 mCloseGuard.open("close"); 19947 } 19948 19949 @Override 19950 protected void finalize() throws Throwable { 19951 try { 19952 mCloseGuard.warnIfOpen(); 19953 close(); 19954 } finally { 19955 super.finalize(); 19956 } 19957 } 19958 19959 @Override 19960 public void close() { 19961 mCloseGuard.close(); 19962 if (mClosed.compareAndSet(false, true)) { 19963 synchronized (mPackages) { 19964 if (mWeFroze) { 19965 mFrozenPackages.remove(mPackageName); 19966 } 19967 19968 if (mChildren != null) { 19969 for (PackageFreezer freezer : mChildren) { 19970 freezer.close(); 19971 } 19972 } 19973 } 19974 } 19975 } 19976 } 19977 19978 /** 19979 * Verify that given package is currently frozen. 19980 */ 19981 private void checkPackageFrozen(String packageName) { 19982 synchronized (mPackages) { 19983 if (!mFrozenPackages.contains(packageName)) { 19984 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19985 } 19986 } 19987 } 19988 19989 @Override 19990 public int movePackage(final String packageName, final String volumeUuid) { 19991 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19992 19993 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19994 final int moveId = mNextMoveId.getAndIncrement(); 19995 mHandler.post(new Runnable() { 19996 @Override 19997 public void run() { 19998 try { 19999 movePackageInternal(packageName, volumeUuid, moveId, user); 20000 } catch (PackageManagerException e) { 20001 Slog.w(TAG, "Failed to move " + packageName, e); 20002 mMoveCallbacks.notifyStatusChanged(moveId, 20003 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20004 } 20005 } 20006 }); 20007 return moveId; 20008 } 20009 20010 private void movePackageInternal(final String packageName, final String volumeUuid, 20011 final int moveId, UserHandle user) throws PackageManagerException { 20012 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20013 final PackageManager pm = mContext.getPackageManager(); 20014 20015 final boolean currentAsec; 20016 final String currentVolumeUuid; 20017 final File codeFile; 20018 final String installerPackageName; 20019 final String packageAbiOverride; 20020 final int appId; 20021 final String seinfo; 20022 final String label; 20023 final int targetSdkVersion; 20024 final PackageFreezer freezer; 20025 final int[] installedUserIds; 20026 20027 // reader 20028 synchronized (mPackages) { 20029 final PackageParser.Package pkg = mPackages.get(packageName); 20030 final PackageSetting ps = mSettings.mPackages.get(packageName); 20031 if (pkg == null || ps == null) { 20032 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20033 } 20034 20035 if (pkg.applicationInfo.isSystemApp()) { 20036 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20037 "Cannot move system application"); 20038 } 20039 20040 if (pkg.applicationInfo.isExternalAsec()) { 20041 currentAsec = true; 20042 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20043 } else if (pkg.applicationInfo.isForwardLocked()) { 20044 currentAsec = true; 20045 currentVolumeUuid = "forward_locked"; 20046 } else { 20047 currentAsec = false; 20048 currentVolumeUuid = ps.volumeUuid; 20049 20050 final File probe = new File(pkg.codePath); 20051 final File probeOat = new File(probe, "oat"); 20052 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20053 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20054 "Move only supported for modern cluster style installs"); 20055 } 20056 } 20057 20058 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20059 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20060 "Package already moved to " + volumeUuid); 20061 } 20062 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20063 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20064 "Device admin cannot be moved"); 20065 } 20066 20067 if (mFrozenPackages.contains(packageName)) { 20068 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20069 "Failed to move already frozen package"); 20070 } 20071 20072 codeFile = new File(pkg.codePath); 20073 installerPackageName = ps.installerPackageName; 20074 packageAbiOverride = ps.cpuAbiOverrideString; 20075 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20076 seinfo = pkg.applicationInfo.seinfo; 20077 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20078 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20079 freezer = freezePackage(packageName, "movePackageInternal"); 20080 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20081 } 20082 20083 final Bundle extras = new Bundle(); 20084 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20085 extras.putString(Intent.EXTRA_TITLE, label); 20086 mMoveCallbacks.notifyCreated(moveId, extras); 20087 20088 int installFlags; 20089 final boolean moveCompleteApp; 20090 final File measurePath; 20091 20092 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20093 installFlags = INSTALL_INTERNAL; 20094 moveCompleteApp = !currentAsec; 20095 measurePath = Environment.getDataAppDirectory(volumeUuid); 20096 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20097 installFlags = INSTALL_EXTERNAL; 20098 moveCompleteApp = false; 20099 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20100 } else { 20101 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20102 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20103 || !volume.isMountedWritable()) { 20104 freezer.close(); 20105 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20106 "Move location not mounted private volume"); 20107 } 20108 20109 Preconditions.checkState(!currentAsec); 20110 20111 installFlags = INSTALL_INTERNAL; 20112 moveCompleteApp = true; 20113 measurePath = Environment.getDataAppDirectory(volumeUuid); 20114 } 20115 20116 final PackageStats stats = new PackageStats(null, -1); 20117 synchronized (mInstaller) { 20118 for (int userId : installedUserIds) { 20119 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20120 freezer.close(); 20121 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20122 "Failed to measure package size"); 20123 } 20124 } 20125 } 20126 20127 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20128 + stats.dataSize); 20129 20130 final long startFreeBytes = measurePath.getFreeSpace(); 20131 final long sizeBytes; 20132 if (moveCompleteApp) { 20133 sizeBytes = stats.codeSize + stats.dataSize; 20134 } else { 20135 sizeBytes = stats.codeSize; 20136 } 20137 20138 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20139 freezer.close(); 20140 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20141 "Not enough free space to move"); 20142 } 20143 20144 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20145 20146 final CountDownLatch installedLatch = new CountDownLatch(1); 20147 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20148 @Override 20149 public void onUserActionRequired(Intent intent) throws RemoteException { 20150 throw new IllegalStateException(); 20151 } 20152 20153 @Override 20154 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20155 Bundle extras) throws RemoteException { 20156 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20157 + PackageManager.installStatusToString(returnCode, msg)); 20158 20159 installedLatch.countDown(); 20160 freezer.close(); 20161 20162 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20163 switch (status) { 20164 case PackageInstaller.STATUS_SUCCESS: 20165 mMoveCallbacks.notifyStatusChanged(moveId, 20166 PackageManager.MOVE_SUCCEEDED); 20167 break; 20168 case PackageInstaller.STATUS_FAILURE_STORAGE: 20169 mMoveCallbacks.notifyStatusChanged(moveId, 20170 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20171 break; 20172 default: 20173 mMoveCallbacks.notifyStatusChanged(moveId, 20174 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20175 break; 20176 } 20177 } 20178 }; 20179 20180 final MoveInfo move; 20181 if (moveCompleteApp) { 20182 // Kick off a thread to report progress estimates 20183 new Thread() { 20184 @Override 20185 public void run() { 20186 while (true) { 20187 try { 20188 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20189 break; 20190 } 20191 } catch (InterruptedException ignored) { 20192 } 20193 20194 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20195 final int progress = 10 + (int) MathUtils.constrain( 20196 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20197 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20198 } 20199 } 20200 }.start(); 20201 20202 final String dataAppName = codeFile.getName(); 20203 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20204 dataAppName, appId, seinfo, targetSdkVersion); 20205 } else { 20206 move = null; 20207 } 20208 20209 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20210 20211 final Message msg = mHandler.obtainMessage(INIT_COPY); 20212 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20213 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20214 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20215 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20216 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20217 msg.obj = params; 20218 20219 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20220 System.identityHashCode(msg.obj)); 20221 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20222 System.identityHashCode(msg.obj)); 20223 20224 mHandler.sendMessage(msg); 20225 } 20226 20227 @Override 20228 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20230 20231 final int realMoveId = mNextMoveId.getAndIncrement(); 20232 final Bundle extras = new Bundle(); 20233 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20234 mMoveCallbacks.notifyCreated(realMoveId, extras); 20235 20236 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20237 @Override 20238 public void onCreated(int moveId, Bundle extras) { 20239 // Ignored 20240 } 20241 20242 @Override 20243 public void onStatusChanged(int moveId, int status, long estMillis) { 20244 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20245 } 20246 }; 20247 20248 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20249 storage.setPrimaryStorageUuid(volumeUuid, callback); 20250 return realMoveId; 20251 } 20252 20253 @Override 20254 public int getMoveStatus(int moveId) { 20255 mContext.enforceCallingOrSelfPermission( 20256 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20257 return mMoveCallbacks.mLastStatus.get(moveId); 20258 } 20259 20260 @Override 20261 public void registerMoveCallback(IPackageMoveObserver callback) { 20262 mContext.enforceCallingOrSelfPermission( 20263 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20264 mMoveCallbacks.register(callback); 20265 } 20266 20267 @Override 20268 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20269 mContext.enforceCallingOrSelfPermission( 20270 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20271 mMoveCallbacks.unregister(callback); 20272 } 20273 20274 @Override 20275 public boolean setInstallLocation(int loc) { 20276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20277 null); 20278 if (getInstallLocation() == loc) { 20279 return true; 20280 } 20281 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20282 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20283 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20284 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20285 return true; 20286 } 20287 return false; 20288 } 20289 20290 @Override 20291 public int getInstallLocation() { 20292 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20293 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20294 PackageHelper.APP_INSTALL_AUTO); 20295 } 20296 20297 /** Called by UserManagerService */ 20298 void cleanUpUser(UserManagerService userManager, int userHandle) { 20299 synchronized (mPackages) { 20300 mDirtyUsers.remove(userHandle); 20301 mUserNeedsBadging.delete(userHandle); 20302 mSettings.removeUserLPw(userHandle); 20303 mPendingBroadcasts.remove(userHandle); 20304 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20305 removeUnusedPackagesLPw(userManager, userHandle); 20306 } 20307 } 20308 20309 /** 20310 * We're removing userHandle and would like to remove any downloaded packages 20311 * that are no longer in use by any other user. 20312 * @param userHandle the user being removed 20313 */ 20314 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20315 final boolean DEBUG_CLEAN_APKS = false; 20316 int [] users = userManager.getUserIds(); 20317 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20318 while (psit.hasNext()) { 20319 PackageSetting ps = psit.next(); 20320 if (ps.pkg == null) { 20321 continue; 20322 } 20323 final String packageName = ps.pkg.packageName; 20324 // Skip over if system app 20325 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20326 continue; 20327 } 20328 if (DEBUG_CLEAN_APKS) { 20329 Slog.i(TAG, "Checking package " + packageName); 20330 } 20331 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20332 if (keep) { 20333 if (DEBUG_CLEAN_APKS) { 20334 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20335 } 20336 } else { 20337 for (int i = 0; i < users.length; i++) { 20338 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20339 keep = true; 20340 if (DEBUG_CLEAN_APKS) { 20341 Slog.i(TAG, " Keeping package " + packageName + " for user " 20342 + users[i]); 20343 } 20344 break; 20345 } 20346 } 20347 } 20348 if (!keep) { 20349 if (DEBUG_CLEAN_APKS) { 20350 Slog.i(TAG, " Removing package " + packageName); 20351 } 20352 mHandler.post(new Runnable() { 20353 public void run() { 20354 deletePackageX(packageName, userHandle, 0); 20355 } //end run 20356 }); 20357 } 20358 } 20359 } 20360 20361 /** Called by UserManagerService */ 20362 void createNewUser(int userId) { 20363 synchronized (mInstallLock) { 20364 mSettings.createNewUserLI(this, mInstaller, userId); 20365 } 20366 synchronized (mPackages) { 20367 scheduleWritePackageRestrictionsLocked(userId); 20368 scheduleWritePackageListLocked(userId); 20369 applyFactoryDefaultBrowserLPw(userId); 20370 primeDomainVerificationsLPw(userId); 20371 } 20372 } 20373 20374 void onBeforeUserStartUninitialized(final int userId) { 20375 synchronized (mPackages) { 20376 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20377 return; 20378 } 20379 } 20380 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20381 // If permission review for legacy apps is required, we represent 20382 // dagerous permissions for such apps as always granted runtime 20383 // permissions to keep per user flag state whether review is needed. 20384 // Hence, if a new user is added we have to propagate dangerous 20385 // permission grants for these legacy apps. 20386 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20387 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20388 | UPDATE_PERMISSIONS_REPLACE_ALL); 20389 } 20390 } 20391 20392 @Override 20393 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20394 mContext.enforceCallingOrSelfPermission( 20395 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20396 "Only package verification agents can read the verifier device identity"); 20397 20398 synchronized (mPackages) { 20399 return mSettings.getVerifierDeviceIdentityLPw(); 20400 } 20401 } 20402 20403 @Override 20404 public void setPermissionEnforced(String permission, boolean enforced) { 20405 // TODO: Now that we no longer change GID for storage, this should to away. 20406 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20407 "setPermissionEnforced"); 20408 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20409 synchronized (mPackages) { 20410 if (mSettings.mReadExternalStorageEnforced == null 20411 || mSettings.mReadExternalStorageEnforced != enforced) { 20412 mSettings.mReadExternalStorageEnforced = enforced; 20413 mSettings.writeLPr(); 20414 } 20415 } 20416 // kill any non-foreground processes so we restart them and 20417 // grant/revoke the GID. 20418 final IActivityManager am = ActivityManagerNative.getDefault(); 20419 if (am != null) { 20420 final long token = Binder.clearCallingIdentity(); 20421 try { 20422 am.killProcessesBelowForeground("setPermissionEnforcement"); 20423 } catch (RemoteException e) { 20424 } finally { 20425 Binder.restoreCallingIdentity(token); 20426 } 20427 } 20428 } else { 20429 throw new IllegalArgumentException("No selective enforcement for " + permission); 20430 } 20431 } 20432 20433 @Override 20434 @Deprecated 20435 public boolean isPermissionEnforced(String permission) { 20436 return true; 20437 } 20438 20439 @Override 20440 public boolean isStorageLow() { 20441 final long token = Binder.clearCallingIdentity(); 20442 try { 20443 final DeviceStorageMonitorInternal 20444 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20445 if (dsm != null) { 20446 return dsm.isMemoryLow(); 20447 } else { 20448 return false; 20449 } 20450 } finally { 20451 Binder.restoreCallingIdentity(token); 20452 } 20453 } 20454 20455 @Override 20456 public IPackageInstaller getPackageInstaller() { 20457 return mInstallerService; 20458 } 20459 20460 private boolean userNeedsBadging(int userId) { 20461 int index = mUserNeedsBadging.indexOfKey(userId); 20462 if (index < 0) { 20463 final UserInfo userInfo; 20464 final long token = Binder.clearCallingIdentity(); 20465 try { 20466 userInfo = sUserManager.getUserInfo(userId); 20467 } finally { 20468 Binder.restoreCallingIdentity(token); 20469 } 20470 final boolean b; 20471 if (userInfo != null && userInfo.isManagedProfile()) { 20472 b = true; 20473 } else { 20474 b = false; 20475 } 20476 mUserNeedsBadging.put(userId, b); 20477 return b; 20478 } 20479 return mUserNeedsBadging.valueAt(index); 20480 } 20481 20482 @Override 20483 public KeySet getKeySetByAlias(String packageName, String alias) { 20484 if (packageName == null || alias == null) { 20485 return null; 20486 } 20487 synchronized(mPackages) { 20488 final PackageParser.Package pkg = mPackages.get(packageName); 20489 if (pkg == null) { 20490 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20491 throw new IllegalArgumentException("Unknown package: " + packageName); 20492 } 20493 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20494 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20495 } 20496 } 20497 20498 @Override 20499 public KeySet getSigningKeySet(String packageName) { 20500 if (packageName == null) { 20501 return null; 20502 } 20503 synchronized(mPackages) { 20504 final PackageParser.Package pkg = mPackages.get(packageName); 20505 if (pkg == null) { 20506 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20507 throw new IllegalArgumentException("Unknown package: " + packageName); 20508 } 20509 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20510 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20511 throw new SecurityException("May not access signing KeySet of other apps."); 20512 } 20513 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20514 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20515 } 20516 } 20517 20518 @Override 20519 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20520 if (packageName == null || ks == null) { 20521 return false; 20522 } 20523 synchronized(mPackages) { 20524 final PackageParser.Package pkg = mPackages.get(packageName); 20525 if (pkg == null) { 20526 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20527 throw new IllegalArgumentException("Unknown package: " + packageName); 20528 } 20529 IBinder ksh = ks.getToken(); 20530 if (ksh instanceof KeySetHandle) { 20531 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20532 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20533 } 20534 return false; 20535 } 20536 } 20537 20538 @Override 20539 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20540 if (packageName == null || ks == null) { 20541 return false; 20542 } 20543 synchronized(mPackages) { 20544 final PackageParser.Package pkg = mPackages.get(packageName); 20545 if (pkg == null) { 20546 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20547 throw new IllegalArgumentException("Unknown package: " + packageName); 20548 } 20549 IBinder ksh = ks.getToken(); 20550 if (ksh instanceof KeySetHandle) { 20551 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20552 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20553 } 20554 return false; 20555 } 20556 } 20557 20558 private void deletePackageIfUnusedLPr(final String packageName) { 20559 PackageSetting ps = mSettings.mPackages.get(packageName); 20560 if (ps == null) { 20561 return; 20562 } 20563 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20564 // TODO Implement atomic delete if package is unused 20565 // It is currently possible that the package will be deleted even if it is installed 20566 // after this method returns. 20567 mHandler.post(new Runnable() { 20568 public void run() { 20569 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20570 } 20571 }); 20572 } 20573 } 20574 20575 /** 20576 * Check and throw if the given before/after packages would be considered a 20577 * downgrade. 20578 */ 20579 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20580 throws PackageManagerException { 20581 if (after.versionCode < before.mVersionCode) { 20582 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20583 "Update version code " + after.versionCode + " is older than current " 20584 + before.mVersionCode); 20585 } else if (after.versionCode == before.mVersionCode) { 20586 if (after.baseRevisionCode < before.baseRevisionCode) { 20587 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20588 "Update base revision code " + after.baseRevisionCode 20589 + " is older than current " + before.baseRevisionCode); 20590 } 20591 20592 if (!ArrayUtils.isEmpty(after.splitNames)) { 20593 for (int i = 0; i < after.splitNames.length; i++) { 20594 final String splitName = after.splitNames[i]; 20595 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20596 if (j != -1) { 20597 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20598 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20599 "Update split " + splitName + " revision code " 20600 + after.splitRevisionCodes[i] + " is older than current " 20601 + before.splitRevisionCodes[j]); 20602 } 20603 } 20604 } 20605 } 20606 } 20607 } 20608 20609 private static class MoveCallbacks extends Handler { 20610 private static final int MSG_CREATED = 1; 20611 private static final int MSG_STATUS_CHANGED = 2; 20612 20613 private final RemoteCallbackList<IPackageMoveObserver> 20614 mCallbacks = new RemoteCallbackList<>(); 20615 20616 private final SparseIntArray mLastStatus = new SparseIntArray(); 20617 20618 public MoveCallbacks(Looper looper) { 20619 super(looper); 20620 } 20621 20622 public void register(IPackageMoveObserver callback) { 20623 mCallbacks.register(callback); 20624 } 20625 20626 public void unregister(IPackageMoveObserver callback) { 20627 mCallbacks.unregister(callback); 20628 } 20629 20630 @Override 20631 public void handleMessage(Message msg) { 20632 final SomeArgs args = (SomeArgs) msg.obj; 20633 final int n = mCallbacks.beginBroadcast(); 20634 for (int i = 0; i < n; i++) { 20635 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20636 try { 20637 invokeCallback(callback, msg.what, args); 20638 } catch (RemoteException ignored) { 20639 } 20640 } 20641 mCallbacks.finishBroadcast(); 20642 args.recycle(); 20643 } 20644 20645 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20646 throws RemoteException { 20647 switch (what) { 20648 case MSG_CREATED: { 20649 callback.onCreated(args.argi1, (Bundle) args.arg2); 20650 break; 20651 } 20652 case MSG_STATUS_CHANGED: { 20653 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20654 break; 20655 } 20656 } 20657 } 20658 20659 private void notifyCreated(int moveId, Bundle extras) { 20660 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20661 20662 final SomeArgs args = SomeArgs.obtain(); 20663 args.argi1 = moveId; 20664 args.arg2 = extras; 20665 obtainMessage(MSG_CREATED, args).sendToTarget(); 20666 } 20667 20668 private void notifyStatusChanged(int moveId, int status) { 20669 notifyStatusChanged(moveId, status, -1); 20670 } 20671 20672 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20673 Slog.v(TAG, "Move " + moveId + " status " + status); 20674 20675 final SomeArgs args = SomeArgs.obtain(); 20676 args.argi1 = moveId; 20677 args.argi2 = status; 20678 args.arg3 = estMillis; 20679 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20680 20681 synchronized (mLastStatus) { 20682 mLastStatus.put(moveId, status); 20683 } 20684 } 20685 } 20686 20687 private final static class OnPermissionChangeListeners extends Handler { 20688 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20689 20690 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20691 new RemoteCallbackList<>(); 20692 20693 public OnPermissionChangeListeners(Looper looper) { 20694 super(looper); 20695 } 20696 20697 @Override 20698 public void handleMessage(Message msg) { 20699 switch (msg.what) { 20700 case MSG_ON_PERMISSIONS_CHANGED: { 20701 final int uid = msg.arg1; 20702 handleOnPermissionsChanged(uid); 20703 } break; 20704 } 20705 } 20706 20707 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20708 mPermissionListeners.register(listener); 20709 20710 } 20711 20712 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20713 mPermissionListeners.unregister(listener); 20714 } 20715 20716 public void onPermissionsChanged(int uid) { 20717 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20718 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20719 } 20720 } 20721 20722 private void handleOnPermissionsChanged(int uid) { 20723 final int count = mPermissionListeners.beginBroadcast(); 20724 try { 20725 for (int i = 0; i < count; i++) { 20726 IOnPermissionsChangeListener callback = mPermissionListeners 20727 .getBroadcastItem(i); 20728 try { 20729 callback.onPermissionsChanged(uid); 20730 } catch (RemoteException e) { 20731 Log.e(TAG, "Permission listener is dead", e); 20732 } 20733 } 20734 } finally { 20735 mPermissionListeners.finishBroadcast(); 20736 } 20737 } 20738 } 20739 20740 private class PackageManagerInternalImpl extends PackageManagerInternal { 20741 @Override 20742 public void setLocationPackagesProvider(PackagesProvider provider) { 20743 synchronized (mPackages) { 20744 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20745 } 20746 } 20747 20748 @Override 20749 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20750 synchronized (mPackages) { 20751 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20752 } 20753 } 20754 20755 @Override 20756 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20757 synchronized (mPackages) { 20758 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20759 } 20760 } 20761 20762 @Override 20763 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20764 synchronized (mPackages) { 20765 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20766 } 20767 } 20768 20769 @Override 20770 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20771 synchronized (mPackages) { 20772 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20773 } 20774 } 20775 20776 @Override 20777 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20778 synchronized (mPackages) { 20779 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20780 } 20781 } 20782 20783 @Override 20784 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20785 synchronized (mPackages) { 20786 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20787 packageName, userId); 20788 } 20789 } 20790 20791 @Override 20792 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20793 synchronized (mPackages) { 20794 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20795 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20796 packageName, userId); 20797 } 20798 } 20799 20800 @Override 20801 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20802 synchronized (mPackages) { 20803 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20804 packageName, userId); 20805 } 20806 } 20807 20808 @Override 20809 public void setKeepUninstalledPackages(final List<String> packageList) { 20810 Preconditions.checkNotNull(packageList); 20811 List<String> removedFromList = null; 20812 synchronized (mPackages) { 20813 if (mKeepUninstalledPackages != null) { 20814 final int packagesCount = mKeepUninstalledPackages.size(); 20815 for (int i = 0; i < packagesCount; i++) { 20816 String oldPackage = mKeepUninstalledPackages.get(i); 20817 if (packageList != null && packageList.contains(oldPackage)) { 20818 continue; 20819 } 20820 if (removedFromList == null) { 20821 removedFromList = new ArrayList<>(); 20822 } 20823 removedFromList.add(oldPackage); 20824 } 20825 } 20826 mKeepUninstalledPackages = new ArrayList<>(packageList); 20827 if (removedFromList != null) { 20828 final int removedCount = removedFromList.size(); 20829 for (int i = 0; i < removedCount; i++) { 20830 deletePackageIfUnusedLPr(removedFromList.get(i)); 20831 } 20832 } 20833 } 20834 } 20835 20836 @Override 20837 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20838 synchronized (mPackages) { 20839 // If we do not support permission review, done. 20840 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20841 return false; 20842 } 20843 20844 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20845 if (packageSetting == null) { 20846 return false; 20847 } 20848 20849 // Permission review applies only to apps not supporting the new permission model. 20850 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20851 return false; 20852 } 20853 20854 // Legacy apps have the permission and get user consent on launch. 20855 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20856 return permissionsState.isPermissionReviewRequired(userId); 20857 } 20858 } 20859 20860 @Override 20861 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20862 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20863 } 20864 20865 @Override 20866 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20867 int userId) { 20868 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20869 } 20870 20871 @Override 20872 public void setDeviceAndProfileOwnerPackages( 20873 int deviceOwnerUserId, String deviceOwnerPackage, 20874 SparseArray<String> profileOwnerPackages) { 20875 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20876 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20877 } 20878 20879 @Override 20880 public boolean canPackageBeWiped(int userId, String packageName) { 20881 return mProtectedPackages.canPackageBeWiped(userId, 20882 packageName); 20883 } 20884 } 20885 20886 @Override 20887 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20888 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20889 synchronized (mPackages) { 20890 final long identity = Binder.clearCallingIdentity(); 20891 try { 20892 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20893 packageNames, userId); 20894 } finally { 20895 Binder.restoreCallingIdentity(identity); 20896 } 20897 } 20898 } 20899 20900 private static void enforceSystemOrPhoneCaller(String tag) { 20901 int callingUid = Binder.getCallingUid(); 20902 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20903 throw new SecurityException( 20904 "Cannot call " + tag + " from UID " + callingUid); 20905 } 20906 } 20907 20908 boolean isHistoricalPackageUsageAvailable() { 20909 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20910 } 20911 20912 /** 20913 * Return a <b>copy</b> of the collection of packages known to the package manager. 20914 * @return A copy of the values of mPackages. 20915 */ 20916 Collection<PackageParser.Package> getPackages() { 20917 synchronized (mPackages) { 20918 return new ArrayList<>(mPackages.values()); 20919 } 20920 } 20921 20922 /** 20923 * Logs process start information (including base APK hash) to the security log. 20924 * @hide 20925 */ 20926 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20927 String apkFile, int pid) { 20928 if (!SecurityLog.isLoggingEnabled()) { 20929 return; 20930 } 20931 Bundle data = new Bundle(); 20932 data.putLong("startTimestamp", System.currentTimeMillis()); 20933 data.putString("processName", processName); 20934 data.putInt("uid", uid); 20935 data.putString("seinfo", seinfo); 20936 data.putString("apkFile", apkFile); 20937 data.putInt("pid", pid); 20938 Message msg = mProcessLoggingHandler.obtainMessage( 20939 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20940 msg.setData(data); 20941 mProcessLoggingHandler.sendMessage(msg); 20942 } 20943} 20944