PackageManagerService.java revision 8051a0a3958f8ff75ce36cd5b4eb09dfc95662b1
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 long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6767 if (srcFile.isDirectory()) { 6768 final File baseFile = new File(pkg.baseCodePath); 6769 long maxModifiedTime = baseFile.lastModified(); 6770 if (pkg.splitCodePaths != null) { 6771 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6772 final File splitFile = new File(pkg.splitCodePaths[i]); 6773 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6774 } 6775 } 6776 return maxModifiedTime; 6777 } 6778 return srcFile.lastModified(); 6779 } 6780 6781 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6782 final int policyFlags) throws PackageManagerException { 6783 if (ps != null 6784 && ps.codePath.equals(srcFile) 6785 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6786 && !isCompatSignatureUpdateNeeded(pkg) 6787 && !isRecoverSignatureUpdateNeeded(pkg)) { 6788 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6789 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6790 ArraySet<PublicKey> signingKs; 6791 synchronized (mPackages) { 6792 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6793 } 6794 if (ps.signatures.mSignatures != null 6795 && ps.signatures.mSignatures.length != 0 6796 && signingKs != null) { 6797 // Optimization: reuse the existing cached certificates 6798 // if the package appears to be unchanged. 6799 pkg.mSignatures = ps.signatures.mSignatures; 6800 pkg.mSigningKeys = signingKs; 6801 return; 6802 } 6803 6804 Slog.w(TAG, "PackageSetting for " + ps.name 6805 + " is missing signatures. Collecting certs again to recover them."); 6806 } else { 6807 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6808 } 6809 6810 try { 6811 PackageParser.collectCertificates(pkg, policyFlags); 6812 } catch (PackageParserException e) { 6813 throw PackageManagerException.from(e); 6814 } 6815 } 6816 6817 /** 6818 * Traces a package scan. 6819 * @see #scanPackageLI(File, int, int, long, UserHandle) 6820 */ 6821 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6822 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6824 try { 6825 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6826 } finally { 6827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6828 } 6829 } 6830 6831 /** 6832 * Scans a package and returns the newly parsed package. 6833 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6834 */ 6835 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6836 long currentTime, UserHandle user) throws PackageManagerException { 6837 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6838 PackageParser pp = new PackageParser(); 6839 pp.setSeparateProcesses(mSeparateProcesses); 6840 pp.setOnlyCoreApps(mOnlyCore); 6841 pp.setDisplayMetrics(mMetrics); 6842 6843 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6844 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6845 } 6846 6847 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6848 final PackageParser.Package pkg; 6849 try { 6850 pkg = pp.parsePackage(scanFile, parseFlags); 6851 } catch (PackageParserException e) { 6852 throw PackageManagerException.from(e); 6853 } finally { 6854 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6855 } 6856 6857 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6858 } 6859 6860 /** 6861 * Scans a package and returns the newly parsed package. 6862 * @throws PackageManagerException on a parse error. 6863 */ 6864 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6865 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6866 throws PackageManagerException { 6867 // If the package has children and this is the first dive in the function 6868 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6869 // packages (parent and children) would be successfully scanned before the 6870 // actual scan since scanning mutates internal state and we want to atomically 6871 // install the package and its children. 6872 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6873 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6874 scanFlags |= SCAN_CHECK_ONLY; 6875 } 6876 } else { 6877 scanFlags &= ~SCAN_CHECK_ONLY; 6878 } 6879 6880 // Scan the parent 6881 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6882 scanFlags, currentTime, user); 6883 6884 // Scan the children 6885 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6886 for (int i = 0; i < childCount; i++) { 6887 PackageParser.Package childPackage = pkg.childPackages.get(i); 6888 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6889 currentTime, user); 6890 } 6891 6892 6893 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6894 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6895 } 6896 6897 return scannedPkg; 6898 } 6899 6900 /** 6901 * Scans a package and returns the newly parsed package. 6902 * @throws PackageManagerException on a parse error. 6903 */ 6904 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6905 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6906 throws PackageManagerException { 6907 PackageSetting ps = null; 6908 PackageSetting updatedPkg; 6909 // reader 6910 synchronized (mPackages) { 6911 // Look to see if we already know about this package. 6912 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6913 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6914 // This package has been renamed to its original name. Let's 6915 // use that. 6916 ps = mSettings.peekPackageLPr(oldName); 6917 } 6918 // If there was no original package, see one for the real package name. 6919 if (ps == null) { 6920 ps = mSettings.peekPackageLPr(pkg.packageName); 6921 } 6922 // Check to see if this package could be hiding/updating a system 6923 // package. Must look for it either under the original or real 6924 // package name depending on our state. 6925 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6926 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6927 6928 // If this is a package we don't know about on the system partition, we 6929 // may need to remove disabled child packages on the system partition 6930 // or may need to not add child packages if the parent apk is updated 6931 // on the data partition and no longer defines this child package. 6932 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6933 // If this is a parent package for an updated system app and this system 6934 // app got an OTA update which no longer defines some of the child packages 6935 // we have to prune them from the disabled system packages. 6936 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6937 if (disabledPs != null) { 6938 final int scannedChildCount = (pkg.childPackages != null) 6939 ? pkg.childPackages.size() : 0; 6940 final int disabledChildCount = disabledPs.childPackageNames != null 6941 ? disabledPs.childPackageNames.size() : 0; 6942 for (int i = 0; i < disabledChildCount; i++) { 6943 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6944 boolean disabledPackageAvailable = false; 6945 for (int j = 0; j < scannedChildCount; j++) { 6946 PackageParser.Package childPkg = pkg.childPackages.get(j); 6947 if (childPkg.packageName.equals(disabledChildPackageName)) { 6948 disabledPackageAvailable = true; 6949 break; 6950 } 6951 } 6952 if (!disabledPackageAvailable) { 6953 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6954 } 6955 } 6956 } 6957 } 6958 } 6959 6960 boolean updatedPkgBetter = false; 6961 // First check if this is a system package that may involve an update 6962 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6963 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6964 // it needs to drop FLAG_PRIVILEGED. 6965 if (locationIsPrivileged(scanFile)) { 6966 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6967 } else { 6968 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6969 } 6970 6971 if (ps != null && !ps.codePath.equals(scanFile)) { 6972 // The path has changed from what was last scanned... check the 6973 // version of the new path against what we have stored to determine 6974 // what to do. 6975 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6976 if (pkg.mVersionCode <= ps.versionCode) { 6977 // The system package has been updated and the code path does not match 6978 // Ignore entry. Skip it. 6979 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6980 + " ignored: updated version " + ps.versionCode 6981 + " better than this " + pkg.mVersionCode); 6982 if (!updatedPkg.codePath.equals(scanFile)) { 6983 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6984 + ps.name + " changing from " + updatedPkg.codePathString 6985 + " to " + scanFile); 6986 updatedPkg.codePath = scanFile; 6987 updatedPkg.codePathString = scanFile.toString(); 6988 updatedPkg.resourcePath = scanFile; 6989 updatedPkg.resourcePathString = scanFile.toString(); 6990 } 6991 updatedPkg.pkg = pkg; 6992 updatedPkg.versionCode = pkg.mVersionCode; 6993 6994 // Update the disabled system child packages to point to the package too. 6995 final int childCount = updatedPkg.childPackageNames != null 6996 ? updatedPkg.childPackageNames.size() : 0; 6997 for (int i = 0; i < childCount; i++) { 6998 String childPackageName = updatedPkg.childPackageNames.get(i); 6999 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7000 childPackageName); 7001 if (updatedChildPkg != null) { 7002 updatedChildPkg.pkg = pkg; 7003 updatedChildPkg.versionCode = pkg.mVersionCode; 7004 } 7005 } 7006 7007 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7008 + scanFile + " ignored: updated version " + ps.versionCode 7009 + " better than this " + pkg.mVersionCode); 7010 } else { 7011 // The current app on the system partition is better than 7012 // what we have updated to on the data partition; switch 7013 // back to the system partition version. 7014 // At this point, its safely assumed that package installation for 7015 // apps in system partition will go through. If not there won't be a working 7016 // version of the app 7017 // writer 7018 synchronized (mPackages) { 7019 // Just remove the loaded entries from package lists. 7020 mPackages.remove(ps.name); 7021 } 7022 7023 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7024 + " reverting from " + ps.codePathString 7025 + ": new version " + pkg.mVersionCode 7026 + " better than installed " + ps.versionCode); 7027 7028 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7029 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7030 synchronized (mInstallLock) { 7031 args.cleanUpResourcesLI(); 7032 } 7033 synchronized (mPackages) { 7034 mSettings.enableSystemPackageLPw(ps.name); 7035 } 7036 updatedPkgBetter = true; 7037 } 7038 } 7039 } 7040 7041 if (updatedPkg != null) { 7042 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7043 // initially 7044 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7045 7046 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7047 // flag set initially 7048 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7049 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7050 } 7051 } 7052 7053 // Verify certificates against what was last scanned 7054 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7055 7056 /* 7057 * A new system app appeared, but we already had a non-system one of the 7058 * same name installed earlier. 7059 */ 7060 boolean shouldHideSystemApp = false; 7061 if (updatedPkg == null && ps != null 7062 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7063 /* 7064 * Check to make sure the signatures match first. If they don't, 7065 * wipe the installed application and its data. 7066 */ 7067 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7068 != PackageManager.SIGNATURE_MATCH) { 7069 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7070 + " signatures don't match existing userdata copy; removing"); 7071 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7072 "scanPackageInternalLI")) { 7073 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7074 } 7075 ps = null; 7076 } else { 7077 /* 7078 * If the newly-added system app is an older version than the 7079 * already installed version, hide it. It will be scanned later 7080 * and re-added like an update. 7081 */ 7082 if (pkg.mVersionCode <= ps.versionCode) { 7083 shouldHideSystemApp = true; 7084 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7085 + " but new version " + pkg.mVersionCode + " better than installed " 7086 + ps.versionCode + "; hiding system"); 7087 } else { 7088 /* 7089 * The newly found system app is a newer version that the 7090 * one previously installed. Simply remove the 7091 * already-installed application and replace it with our own 7092 * while keeping the application data. 7093 */ 7094 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7095 + " reverting from " + ps.codePathString + ": new version " 7096 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7097 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7098 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7099 synchronized (mInstallLock) { 7100 args.cleanUpResourcesLI(); 7101 } 7102 } 7103 } 7104 } 7105 7106 // The apk is forward locked (not public) if its code and resources 7107 // are kept in different files. (except for app in either system or 7108 // vendor path). 7109 // TODO grab this value from PackageSettings 7110 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7111 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7112 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7113 } 7114 } 7115 7116 // TODO: extend to support forward-locked splits 7117 String resourcePath = null; 7118 String baseResourcePath = null; 7119 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7120 if (ps != null && ps.resourcePathString != null) { 7121 resourcePath = ps.resourcePathString; 7122 baseResourcePath = ps.resourcePathString; 7123 } else { 7124 // Should not happen at all. Just log an error. 7125 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7126 } 7127 } else { 7128 resourcePath = pkg.codePath; 7129 baseResourcePath = pkg.baseCodePath; 7130 } 7131 7132 // Set application objects path explicitly. 7133 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7134 pkg.setApplicationInfoCodePath(pkg.codePath); 7135 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7136 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7137 pkg.setApplicationInfoResourcePath(resourcePath); 7138 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7139 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7140 7141 // Note that we invoke the following method only if we are about to unpack an application 7142 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7143 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7144 7145 /* 7146 * If the system app should be overridden by a previously installed 7147 * data, hide the system app now and let the /data/app scan pick it up 7148 * again. 7149 */ 7150 if (shouldHideSystemApp) { 7151 synchronized (mPackages) { 7152 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7153 } 7154 } 7155 7156 return scannedPkg; 7157 } 7158 7159 private static String fixProcessName(String defProcessName, 7160 String processName, int uid) { 7161 if (processName == null) { 7162 return defProcessName; 7163 } 7164 return processName; 7165 } 7166 7167 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7168 throws PackageManagerException { 7169 if (pkgSetting.signatures.mSignatures != null) { 7170 // Already existing package. Make sure signatures match 7171 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7172 == PackageManager.SIGNATURE_MATCH; 7173 if (!match) { 7174 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7175 == PackageManager.SIGNATURE_MATCH; 7176 } 7177 if (!match) { 7178 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7179 == PackageManager.SIGNATURE_MATCH; 7180 } 7181 if (!match) { 7182 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7183 + pkg.packageName + " signatures do not match the " 7184 + "previously installed version; ignoring!"); 7185 } 7186 } 7187 7188 // Check for shared user signatures 7189 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7190 // Already existing package. Make sure signatures match 7191 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7192 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7193 if (!match) { 7194 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7195 == PackageManager.SIGNATURE_MATCH; 7196 } 7197 if (!match) { 7198 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7199 == PackageManager.SIGNATURE_MATCH; 7200 } 7201 if (!match) { 7202 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7203 "Package " + pkg.packageName 7204 + " has no signatures that match those in shared user " 7205 + pkgSetting.sharedUser.name + "; ignoring!"); 7206 } 7207 } 7208 } 7209 7210 /** 7211 * Enforces that only the system UID or root's UID can call a method exposed 7212 * via Binder. 7213 * 7214 * @param message used as message if SecurityException is thrown 7215 * @throws SecurityException if the caller is not system or root 7216 */ 7217 private static final void enforceSystemOrRoot(String message) { 7218 final int uid = Binder.getCallingUid(); 7219 if (uid != Process.SYSTEM_UID && uid != 0) { 7220 throw new SecurityException(message); 7221 } 7222 } 7223 7224 @Override 7225 public void performFstrimIfNeeded() { 7226 enforceSystemOrRoot("Only the system can request fstrim"); 7227 7228 // Before everything else, see whether we need to fstrim. 7229 try { 7230 IMountService ms = PackageHelper.getMountService(); 7231 if (ms != null) { 7232 final boolean isUpgrade = isUpgrade(); 7233 boolean doTrim = isUpgrade; 7234 if (doTrim) { 7235 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7236 } else { 7237 final long interval = android.provider.Settings.Global.getLong( 7238 mContext.getContentResolver(), 7239 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7240 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7241 if (interval > 0) { 7242 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7243 if (timeSinceLast > interval) { 7244 doTrim = true; 7245 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7246 + "; running immediately"); 7247 } 7248 } 7249 } 7250 if (doTrim) { 7251 if (!isFirstBoot()) { 7252 try { 7253 ActivityManagerNative.getDefault().showBootMessage( 7254 mContext.getResources().getString( 7255 R.string.android_upgrading_fstrim), true); 7256 } catch (RemoteException e) { 7257 } 7258 } 7259 ms.runMaintenance(); 7260 } 7261 } else { 7262 Slog.e(TAG, "Mount service unavailable!"); 7263 } 7264 } catch (RemoteException e) { 7265 // Can't happen; MountService is local 7266 } 7267 } 7268 7269 @Override 7270 public void updatePackagesIfNeeded() { 7271 enforceSystemOrRoot("Only the system can request package update"); 7272 7273 // We need to re-extract after an OTA. 7274 boolean causeUpgrade = isUpgrade(); 7275 7276 // First boot or factory reset. 7277 // Note: we also handle devices that are upgrading to N right now as if it is their 7278 // first boot, as they do not have profile data. 7279 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7280 7281 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7282 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7283 7284 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7285 return; 7286 } 7287 7288 List<PackageParser.Package> pkgs; 7289 synchronized (mPackages) { 7290 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7291 } 7292 7293 final long startTime = System.nanoTime(); 7294 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7295 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7296 7297 final int elapsedTimeSeconds = 7298 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7299 7300 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7301 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7302 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7303 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7304 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7305 } 7306 7307 /** 7308 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7309 * containing statistics about the invocation. The array consists of three elements, 7310 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7311 * and {@code numberOfPackagesFailed}. 7312 */ 7313 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7314 String compilerFilter) { 7315 7316 int numberOfPackagesVisited = 0; 7317 int numberOfPackagesOptimized = 0; 7318 int numberOfPackagesSkipped = 0; 7319 int numberOfPackagesFailed = 0; 7320 final int numberOfPackagesToDexopt = pkgs.size(); 7321 7322 for (PackageParser.Package pkg : pkgs) { 7323 numberOfPackagesVisited++; 7324 7325 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7326 if (DEBUG_DEXOPT) { 7327 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7328 } 7329 numberOfPackagesSkipped++; 7330 continue; 7331 } 7332 7333 if (DEBUG_DEXOPT) { 7334 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7335 numberOfPackagesToDexopt + ": " + pkg.packageName); 7336 } 7337 7338 if (showDialog) { 7339 try { 7340 ActivityManagerNative.getDefault().showBootMessage( 7341 mContext.getResources().getString(R.string.android_upgrading_apk, 7342 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7343 } catch (RemoteException e) { 7344 } 7345 } 7346 7347 // checkProfiles is false to avoid merging profiles during boot which 7348 // might interfere with background compilation (b/28612421). 7349 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7350 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7351 // trade-off worth doing to save boot time work. 7352 int dexOptStatus = performDexOptTraced(pkg.packageName, 7353 false /* checkProfiles */, 7354 compilerFilter, 7355 false /* force */); 7356 switch (dexOptStatus) { 7357 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7358 numberOfPackagesOptimized++; 7359 break; 7360 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7361 numberOfPackagesSkipped++; 7362 break; 7363 case PackageDexOptimizer.DEX_OPT_FAILED: 7364 numberOfPackagesFailed++; 7365 break; 7366 default: 7367 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7368 break; 7369 } 7370 } 7371 7372 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7373 numberOfPackagesFailed }; 7374 } 7375 7376 @Override 7377 public void notifyPackageUse(String packageName, int reason) { 7378 synchronized (mPackages) { 7379 PackageParser.Package p = mPackages.get(packageName); 7380 if (p == null) { 7381 return; 7382 } 7383 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7384 } 7385 } 7386 7387 // TODO: this is not used nor needed. Delete it. 7388 @Override 7389 public boolean performDexOptIfNeeded(String packageName) { 7390 int dexOptStatus = performDexOptTraced(packageName, 7391 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7392 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7393 } 7394 7395 @Override 7396 public boolean performDexOpt(String packageName, 7397 boolean checkProfiles, int compileReason, boolean force) { 7398 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7399 getCompilerFilterForReason(compileReason), force); 7400 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7401 } 7402 7403 @Override 7404 public boolean performDexOptMode(String packageName, 7405 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7406 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7407 targetCompilerFilter, force); 7408 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7409 } 7410 7411 private int performDexOptTraced(String packageName, 7412 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7413 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7414 try { 7415 return performDexOptInternal(packageName, checkProfiles, 7416 targetCompilerFilter, force); 7417 } finally { 7418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7419 } 7420 } 7421 7422 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7423 // if the package can now be considered up to date for the given filter. 7424 private int performDexOptInternal(String packageName, 7425 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7426 PackageParser.Package p; 7427 synchronized (mPackages) { 7428 p = mPackages.get(packageName); 7429 if (p == null) { 7430 // Package could not be found. Report failure. 7431 return PackageDexOptimizer.DEX_OPT_FAILED; 7432 } 7433 mPackageUsage.write(false); 7434 } 7435 long callingId = Binder.clearCallingIdentity(); 7436 try { 7437 synchronized (mInstallLock) { 7438 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7439 targetCompilerFilter, force); 7440 } 7441 } finally { 7442 Binder.restoreCallingIdentity(callingId); 7443 } 7444 } 7445 7446 public ArraySet<String> getOptimizablePackages() { 7447 ArraySet<String> pkgs = new ArraySet<String>(); 7448 synchronized (mPackages) { 7449 for (PackageParser.Package p : mPackages.values()) { 7450 if (PackageDexOptimizer.canOptimizePackage(p)) { 7451 pkgs.add(p.packageName); 7452 } 7453 } 7454 } 7455 return pkgs; 7456 } 7457 7458 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7459 boolean checkProfiles, String targetCompilerFilter, 7460 boolean force) { 7461 // Select the dex optimizer based on the force parameter. 7462 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7463 // allocate an object here. 7464 PackageDexOptimizer pdo = force 7465 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7466 : mPackageDexOptimizer; 7467 7468 // Optimize all dependencies first. Note: we ignore the return value and march on 7469 // on errors. 7470 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7471 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7472 if (!deps.isEmpty()) { 7473 for (PackageParser.Package depPackage : deps) { 7474 // TODO: Analyze and investigate if we (should) profile libraries. 7475 // Currently this will do a full compilation of the library by default. 7476 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7477 false /* checkProfiles */, 7478 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7479 } 7480 } 7481 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7482 targetCompilerFilter); 7483 } 7484 7485 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7486 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7487 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7488 Set<String> collectedNames = new HashSet<>(); 7489 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7490 7491 retValue.remove(p); 7492 7493 return retValue; 7494 } else { 7495 return Collections.emptyList(); 7496 } 7497 } 7498 7499 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7500 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7501 if (!collectedNames.contains(p.packageName)) { 7502 collectedNames.add(p.packageName); 7503 collected.add(p); 7504 7505 if (p.usesLibraries != null) { 7506 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7507 } 7508 if (p.usesOptionalLibraries != null) { 7509 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7510 collectedNames); 7511 } 7512 } 7513 } 7514 7515 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7516 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7517 for (String libName : libs) { 7518 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7519 if (libPkg != null) { 7520 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7521 } 7522 } 7523 } 7524 7525 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7526 synchronized (mPackages) { 7527 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7528 if (lib != null && lib.apk != null) { 7529 return mPackages.get(lib.apk); 7530 } 7531 } 7532 return null; 7533 } 7534 7535 public void shutdown() { 7536 mPackageUsage.write(true); 7537 } 7538 7539 @Override 7540 public void dumpProfiles(String packageName) { 7541 PackageParser.Package pkg; 7542 synchronized (mPackages) { 7543 pkg = mPackages.get(packageName); 7544 if (pkg == null) { 7545 throw new IllegalArgumentException("Unknown package: " + packageName); 7546 } 7547 } 7548 /* Only the shell, root, or the app user should be able to dump profiles. */ 7549 int callingUid = Binder.getCallingUid(); 7550 if (callingUid != Process.SHELL_UID && 7551 callingUid != Process.ROOT_UID && 7552 callingUid != pkg.applicationInfo.uid) { 7553 throw new SecurityException("dumpProfiles"); 7554 } 7555 7556 synchronized (mInstallLock) { 7557 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7558 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7559 try { 7560 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7561 String gid = Integer.toString(sharedGid); 7562 String codePaths = TextUtils.join(";", allCodePaths); 7563 mInstaller.dumpProfiles(gid, packageName, codePaths); 7564 } catch (InstallerException e) { 7565 Slog.w(TAG, "Failed to dump profiles", e); 7566 } 7567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7568 } 7569 } 7570 7571 @Override 7572 public void forceDexOpt(String packageName) { 7573 enforceSystemOrRoot("forceDexOpt"); 7574 7575 PackageParser.Package pkg; 7576 synchronized (mPackages) { 7577 pkg = mPackages.get(packageName); 7578 if (pkg == null) { 7579 throw new IllegalArgumentException("Unknown package: " + packageName); 7580 } 7581 } 7582 7583 synchronized (mInstallLock) { 7584 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7585 7586 // Whoever is calling forceDexOpt wants a fully compiled package. 7587 // Don't use profiles since that may cause compilation to be skipped. 7588 final int res = performDexOptInternalWithDependenciesLI(pkg, 7589 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7590 true /* force */); 7591 7592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7593 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7594 throw new IllegalStateException("Failed to dexopt: " + res); 7595 } 7596 } 7597 } 7598 7599 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7600 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7601 Slog.w(TAG, "Unable to update from " + oldPkg.name 7602 + " to " + newPkg.packageName 7603 + ": old package not in system partition"); 7604 return false; 7605 } else if (mPackages.get(oldPkg.name) != null) { 7606 Slog.w(TAG, "Unable to update from " + oldPkg.name 7607 + " to " + newPkg.packageName 7608 + ": old package still exists"); 7609 return false; 7610 } 7611 return true; 7612 } 7613 7614 void removeCodePathLI(File codePath) { 7615 if (codePath.isDirectory()) { 7616 try { 7617 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7618 } catch (InstallerException e) { 7619 Slog.w(TAG, "Failed to remove code path", e); 7620 } 7621 } else { 7622 codePath.delete(); 7623 } 7624 } 7625 7626 private int[] resolveUserIds(int userId) { 7627 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7628 } 7629 7630 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7631 if (pkg == null) { 7632 Slog.wtf(TAG, "Package was null!", new Throwable()); 7633 return; 7634 } 7635 clearAppDataLeafLIF(pkg, userId, flags); 7636 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7637 for (int i = 0; i < childCount; i++) { 7638 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7639 } 7640 } 7641 7642 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7643 final PackageSetting ps; 7644 synchronized (mPackages) { 7645 ps = mSettings.mPackages.get(pkg.packageName); 7646 } 7647 for (int realUserId : resolveUserIds(userId)) { 7648 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7649 try { 7650 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7651 ceDataInode); 7652 } catch (InstallerException e) { 7653 Slog.w(TAG, String.valueOf(e)); 7654 } 7655 } 7656 } 7657 7658 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7659 if (pkg == null) { 7660 Slog.wtf(TAG, "Package was null!", new Throwable()); 7661 return; 7662 } 7663 destroyAppDataLeafLIF(pkg, userId, flags); 7664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7665 for (int i = 0; i < childCount; i++) { 7666 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7667 } 7668 } 7669 7670 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7671 final PackageSetting ps; 7672 synchronized (mPackages) { 7673 ps = mSettings.mPackages.get(pkg.packageName); 7674 } 7675 for (int realUserId : resolveUserIds(userId)) { 7676 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7677 try { 7678 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7679 ceDataInode); 7680 } catch (InstallerException e) { 7681 Slog.w(TAG, String.valueOf(e)); 7682 } 7683 } 7684 } 7685 7686 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7687 if (pkg == null) { 7688 Slog.wtf(TAG, "Package was null!", new Throwable()); 7689 return; 7690 } 7691 destroyAppProfilesLeafLIF(pkg); 7692 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7693 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7694 for (int i = 0; i < childCount; i++) { 7695 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7696 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7697 true /* removeBaseMarker */); 7698 } 7699 } 7700 7701 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7702 boolean removeBaseMarker) { 7703 if (pkg.isForwardLocked()) { 7704 return; 7705 } 7706 7707 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7708 try { 7709 path = PackageManagerServiceUtils.realpath(new File(path)); 7710 } catch (IOException e) { 7711 // TODO: Should we return early here ? 7712 Slog.w(TAG, "Failed to get canonical path", e); 7713 continue; 7714 } 7715 7716 final String useMarker = path.replace('/', '@'); 7717 for (int realUserId : resolveUserIds(userId)) { 7718 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7719 if (removeBaseMarker) { 7720 File foreignUseMark = new File(profileDir, useMarker); 7721 if (foreignUseMark.exists()) { 7722 if (!foreignUseMark.delete()) { 7723 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7724 + pkg.packageName); 7725 } 7726 } 7727 } 7728 7729 File[] markers = profileDir.listFiles(); 7730 if (markers != null) { 7731 final String searchString = "@" + pkg.packageName + "@"; 7732 // We also delete all markers that contain the package name we're 7733 // uninstalling. These are associated with secondary dex-files belonging 7734 // to the package. Reconstructing the path of these dex files is messy 7735 // in general. 7736 for (File marker : markers) { 7737 if (marker.getName().indexOf(searchString) > 0) { 7738 if (!marker.delete()) { 7739 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7740 + pkg.packageName); 7741 } 7742 } 7743 } 7744 } 7745 } 7746 } 7747 } 7748 7749 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7750 try { 7751 mInstaller.destroyAppProfiles(pkg.packageName); 7752 } catch (InstallerException e) { 7753 Slog.w(TAG, String.valueOf(e)); 7754 } 7755 } 7756 7757 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7758 if (pkg == null) { 7759 Slog.wtf(TAG, "Package was null!", new Throwable()); 7760 return; 7761 } 7762 clearAppProfilesLeafLIF(pkg); 7763 // We don't remove the base foreign use marker when clearing profiles because 7764 // we will rename it when the app is updated. Unlike the actual profile contents, 7765 // the foreign use marker is good across installs. 7766 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7767 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7768 for (int i = 0; i < childCount; i++) { 7769 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7770 } 7771 } 7772 7773 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7774 try { 7775 mInstaller.clearAppProfiles(pkg.packageName); 7776 } catch (InstallerException e) { 7777 Slog.w(TAG, String.valueOf(e)); 7778 } 7779 } 7780 7781 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7782 long lastUpdateTime) { 7783 // Set parent install/update time 7784 PackageSetting ps = (PackageSetting) pkg.mExtras; 7785 if (ps != null) { 7786 ps.firstInstallTime = firstInstallTime; 7787 ps.lastUpdateTime = lastUpdateTime; 7788 } 7789 // Set children install/update time 7790 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7791 for (int i = 0; i < childCount; i++) { 7792 PackageParser.Package childPkg = pkg.childPackages.get(i); 7793 ps = (PackageSetting) childPkg.mExtras; 7794 if (ps != null) { 7795 ps.firstInstallTime = firstInstallTime; 7796 ps.lastUpdateTime = lastUpdateTime; 7797 } 7798 } 7799 } 7800 7801 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7802 PackageParser.Package changingLib) { 7803 if (file.path != null) { 7804 usesLibraryFiles.add(file.path); 7805 return; 7806 } 7807 PackageParser.Package p = mPackages.get(file.apk); 7808 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7809 // If we are doing this while in the middle of updating a library apk, 7810 // then we need to make sure to use that new apk for determining the 7811 // dependencies here. (We haven't yet finished committing the new apk 7812 // to the package manager state.) 7813 if (p == null || p.packageName.equals(changingLib.packageName)) { 7814 p = changingLib; 7815 } 7816 } 7817 if (p != null) { 7818 usesLibraryFiles.addAll(p.getAllCodePaths()); 7819 } 7820 } 7821 7822 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7823 PackageParser.Package changingLib) throws PackageManagerException { 7824 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7825 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7826 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7827 for (int i=0; i<N; i++) { 7828 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7829 if (file == null) { 7830 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7831 "Package " + pkg.packageName + " requires unavailable shared library " 7832 + pkg.usesLibraries.get(i) + "; failing!"); 7833 } 7834 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7835 } 7836 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7837 for (int i=0; i<N; i++) { 7838 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7839 if (file == null) { 7840 Slog.w(TAG, "Package " + pkg.packageName 7841 + " desires unavailable shared library " 7842 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7843 } else { 7844 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7845 } 7846 } 7847 N = usesLibraryFiles.size(); 7848 if (N > 0) { 7849 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7850 } else { 7851 pkg.usesLibraryFiles = null; 7852 } 7853 } 7854 } 7855 7856 private static boolean hasString(List<String> list, List<String> which) { 7857 if (list == null) { 7858 return false; 7859 } 7860 for (int i=list.size()-1; i>=0; i--) { 7861 for (int j=which.size()-1; j>=0; j--) { 7862 if (which.get(j).equals(list.get(i))) { 7863 return true; 7864 } 7865 } 7866 } 7867 return false; 7868 } 7869 7870 private void updateAllSharedLibrariesLPw() { 7871 for (PackageParser.Package pkg : mPackages.values()) { 7872 try { 7873 updateSharedLibrariesLPw(pkg, null); 7874 } catch (PackageManagerException e) { 7875 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7876 } 7877 } 7878 } 7879 7880 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7881 PackageParser.Package changingPkg) { 7882 ArrayList<PackageParser.Package> res = null; 7883 for (PackageParser.Package pkg : mPackages.values()) { 7884 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7885 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7886 if (res == null) { 7887 res = new ArrayList<PackageParser.Package>(); 7888 } 7889 res.add(pkg); 7890 try { 7891 updateSharedLibrariesLPw(pkg, changingPkg); 7892 } catch (PackageManagerException e) { 7893 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7894 } 7895 } 7896 } 7897 return res; 7898 } 7899 7900 /** 7901 * Derive the value of the {@code cpuAbiOverride} based on the provided 7902 * value and an optional stored value from the package settings. 7903 */ 7904 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7905 String cpuAbiOverride = null; 7906 7907 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7908 cpuAbiOverride = null; 7909 } else if (abiOverride != null) { 7910 cpuAbiOverride = abiOverride; 7911 } else if (settings != null) { 7912 cpuAbiOverride = settings.cpuAbiOverrideString; 7913 } 7914 7915 return cpuAbiOverride; 7916 } 7917 7918 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7919 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7920 throws PackageManagerException { 7921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7922 // If the package has children and this is the first dive in the function 7923 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7924 // whether all packages (parent and children) would be successfully scanned 7925 // before the actual scan since scanning mutates internal state and we want 7926 // to atomically install the package and its children. 7927 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7928 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7929 scanFlags |= SCAN_CHECK_ONLY; 7930 } 7931 } else { 7932 scanFlags &= ~SCAN_CHECK_ONLY; 7933 } 7934 7935 final PackageParser.Package scannedPkg; 7936 try { 7937 // Scan the parent 7938 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7939 // Scan the children 7940 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7941 for (int i = 0; i < childCount; i++) { 7942 PackageParser.Package childPkg = pkg.childPackages.get(i); 7943 scanPackageLI(childPkg, policyFlags, 7944 scanFlags, currentTime, user); 7945 } 7946 } finally { 7947 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7948 } 7949 7950 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7951 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7952 } 7953 7954 return scannedPkg; 7955 } 7956 7957 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7958 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7959 boolean success = false; 7960 try { 7961 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7962 currentTime, user); 7963 success = true; 7964 return res; 7965 } finally { 7966 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7967 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7968 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7969 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7970 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7971 } 7972 } 7973 } 7974 7975 /** 7976 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7977 */ 7978 private static boolean apkHasCode(String fileName) { 7979 StrictJarFile jarFile = null; 7980 try { 7981 jarFile = new StrictJarFile(fileName, 7982 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7983 return jarFile.findEntry("classes.dex") != null; 7984 } catch (IOException ignore) { 7985 } finally { 7986 try { 7987 jarFile.close(); 7988 } catch (IOException ignore) {} 7989 } 7990 return false; 7991 } 7992 7993 /** 7994 * Enforces code policy for the package. This ensures that if an APK has 7995 * declared hasCode="true" in its manifest that the APK actually contains 7996 * code. 7997 * 7998 * @throws PackageManagerException If bytecode could not be found when it should exist 7999 */ 8000 private static void enforceCodePolicy(PackageParser.Package pkg) 8001 throws PackageManagerException { 8002 final boolean shouldHaveCode = 8003 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8004 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8005 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8006 "Package " + pkg.baseCodePath + " code is missing"); 8007 } 8008 8009 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8010 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8011 final boolean splitShouldHaveCode = 8012 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8013 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8014 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8015 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8016 } 8017 } 8018 } 8019 } 8020 8021 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8022 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8023 throws PackageManagerException { 8024 final File scanFile = new File(pkg.codePath); 8025 if (pkg.applicationInfo.getCodePath() == null || 8026 pkg.applicationInfo.getResourcePath() == null) { 8027 // Bail out. The resource and code paths haven't been set. 8028 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8029 "Code and resource paths haven't been set correctly"); 8030 } 8031 8032 // Apply policy 8033 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8034 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8035 if (pkg.applicationInfo.isDirectBootAware()) { 8036 // we're direct boot aware; set for all components 8037 for (PackageParser.Service s : pkg.services) { 8038 s.info.encryptionAware = s.info.directBootAware = true; 8039 } 8040 for (PackageParser.Provider p : pkg.providers) { 8041 p.info.encryptionAware = p.info.directBootAware = true; 8042 } 8043 for (PackageParser.Activity a : pkg.activities) { 8044 a.info.encryptionAware = a.info.directBootAware = true; 8045 } 8046 for (PackageParser.Activity r : pkg.receivers) { 8047 r.info.encryptionAware = r.info.directBootAware = true; 8048 } 8049 } 8050 } else { 8051 // Only allow system apps to be flagged as core apps. 8052 pkg.coreApp = false; 8053 // clear flags not applicable to regular apps 8054 pkg.applicationInfo.privateFlags &= 8055 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8056 pkg.applicationInfo.privateFlags &= 8057 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8058 } 8059 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8060 8061 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8062 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8063 } 8064 8065 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8066 enforceCodePolicy(pkg); 8067 } 8068 8069 if (mCustomResolverComponentName != null && 8070 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8071 setUpCustomResolverActivity(pkg); 8072 } 8073 8074 if (pkg.packageName.equals("android")) { 8075 synchronized (mPackages) { 8076 if (mAndroidApplication != null) { 8077 Slog.w(TAG, "*************************************************"); 8078 Slog.w(TAG, "Core android package being redefined. Skipping."); 8079 Slog.w(TAG, " file=" + scanFile); 8080 Slog.w(TAG, "*************************************************"); 8081 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8082 "Core android package being redefined. Skipping."); 8083 } 8084 8085 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8086 // Set up information for our fall-back user intent resolution activity. 8087 mPlatformPackage = pkg; 8088 pkg.mVersionCode = mSdkVersion; 8089 mAndroidApplication = pkg.applicationInfo; 8090 8091 if (!mResolverReplaced) { 8092 mResolveActivity.applicationInfo = mAndroidApplication; 8093 mResolveActivity.name = ResolverActivity.class.getName(); 8094 mResolveActivity.packageName = mAndroidApplication.packageName; 8095 mResolveActivity.processName = "system:ui"; 8096 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8097 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8098 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8099 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8100 mResolveActivity.exported = true; 8101 mResolveActivity.enabled = true; 8102 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8103 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8104 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8105 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8106 | ActivityInfo.CONFIG_ORIENTATION 8107 | ActivityInfo.CONFIG_KEYBOARD 8108 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8109 mResolveInfo.activityInfo = mResolveActivity; 8110 mResolveInfo.priority = 0; 8111 mResolveInfo.preferredOrder = 0; 8112 mResolveInfo.match = 0; 8113 mResolveComponentName = new ComponentName( 8114 mAndroidApplication.packageName, mResolveActivity.name); 8115 } 8116 } 8117 } 8118 } 8119 8120 if (DEBUG_PACKAGE_SCANNING) { 8121 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8122 Log.d(TAG, "Scanning package " + pkg.packageName); 8123 } 8124 8125 synchronized (mPackages) { 8126 if (mPackages.containsKey(pkg.packageName) 8127 || mSharedLibraries.containsKey(pkg.packageName)) { 8128 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8129 "Application package " + pkg.packageName 8130 + " already installed. Skipping duplicate."); 8131 } 8132 8133 // If we're only installing presumed-existing packages, require that the 8134 // scanned APK is both already known and at the path previously established 8135 // for it. Previously unknown packages we pick up normally, but if we have an 8136 // a priori expectation about this package's install presence, enforce it. 8137 // With a singular exception for new system packages. When an OTA contains 8138 // a new system package, we allow the codepath to change from a system location 8139 // to the user-installed location. If we don't allow this change, any newer, 8140 // user-installed version of the application will be ignored. 8141 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8142 if (mExpectingBetter.containsKey(pkg.packageName)) { 8143 logCriticalInfo(Log.WARN, 8144 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8145 } else { 8146 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8147 if (known != null) { 8148 if (DEBUG_PACKAGE_SCANNING) { 8149 Log.d(TAG, "Examining " + pkg.codePath 8150 + " and requiring known paths " + known.codePathString 8151 + " & " + known.resourcePathString); 8152 } 8153 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8154 || !pkg.applicationInfo.getResourcePath().equals( 8155 known.resourcePathString)) { 8156 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8157 "Application package " + pkg.packageName 8158 + " found at " + pkg.applicationInfo.getCodePath() 8159 + " but expected at " + known.codePathString 8160 + "; ignoring."); 8161 } 8162 } 8163 } 8164 } 8165 } 8166 8167 // Initialize package source and resource directories 8168 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8169 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8170 8171 SharedUserSetting suid = null; 8172 PackageSetting pkgSetting = null; 8173 8174 if (!isSystemApp(pkg)) { 8175 // Only system apps can use these features. 8176 pkg.mOriginalPackages = null; 8177 pkg.mRealPackage = null; 8178 pkg.mAdoptPermissions = null; 8179 } 8180 8181 // Getting the package setting may have a side-effect, so if we 8182 // are only checking if scan would succeed, stash a copy of the 8183 // old setting to restore at the end. 8184 PackageSetting nonMutatedPs = null; 8185 8186 // writer 8187 synchronized (mPackages) { 8188 if (pkg.mSharedUserId != null) { 8189 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8190 if (suid == null) { 8191 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8192 "Creating application package " + pkg.packageName 8193 + " for shared user failed"); 8194 } 8195 if (DEBUG_PACKAGE_SCANNING) { 8196 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8197 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8198 + "): packages=" + suid.packages); 8199 } 8200 } 8201 8202 // Check if we are renaming from an original package name. 8203 PackageSetting origPackage = null; 8204 String realName = null; 8205 if (pkg.mOriginalPackages != null) { 8206 // This package may need to be renamed to a previously 8207 // installed name. Let's check on that... 8208 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8209 if (pkg.mOriginalPackages.contains(renamed)) { 8210 // This package had originally been installed as the 8211 // original name, and we have already taken care of 8212 // transitioning to the new one. Just update the new 8213 // one to continue using the old name. 8214 realName = pkg.mRealPackage; 8215 if (!pkg.packageName.equals(renamed)) { 8216 // Callers into this function may have already taken 8217 // care of renaming the package; only do it here if 8218 // it is not already done. 8219 pkg.setPackageName(renamed); 8220 } 8221 8222 } else { 8223 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8224 if ((origPackage = mSettings.peekPackageLPr( 8225 pkg.mOriginalPackages.get(i))) != null) { 8226 // We do have the package already installed under its 8227 // original name... should we use it? 8228 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8229 // New package is not compatible with original. 8230 origPackage = null; 8231 continue; 8232 } else if (origPackage.sharedUser != null) { 8233 // Make sure uid is compatible between packages. 8234 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8235 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8236 + " to " + pkg.packageName + ": old uid " 8237 + origPackage.sharedUser.name 8238 + " differs from " + pkg.mSharedUserId); 8239 origPackage = null; 8240 continue; 8241 } 8242 // TODO: Add case when shared user id is added [b/28144775] 8243 } else { 8244 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8245 + pkg.packageName + " to old name " + origPackage.name); 8246 } 8247 break; 8248 } 8249 } 8250 } 8251 } 8252 8253 if (mTransferedPackages.contains(pkg.packageName)) { 8254 Slog.w(TAG, "Package " + pkg.packageName 8255 + " was transferred to another, but its .apk remains"); 8256 } 8257 8258 // See comments in nonMutatedPs declaration 8259 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8260 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8261 if (foundPs != null) { 8262 nonMutatedPs = new PackageSetting(foundPs); 8263 } 8264 } 8265 8266 // Just create the setting, don't add it yet. For already existing packages 8267 // the PkgSetting exists already and doesn't have to be created. 8268 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8269 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8270 pkg.applicationInfo.primaryCpuAbi, 8271 pkg.applicationInfo.secondaryCpuAbi, 8272 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8273 user, false); 8274 if (pkgSetting == null) { 8275 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8276 "Creating application package " + pkg.packageName + " failed"); 8277 } 8278 8279 if (pkgSetting.origPackage != null) { 8280 // If we are first transitioning from an original package, 8281 // fix up the new package's name now. We need to do this after 8282 // looking up the package under its new name, so getPackageLP 8283 // can take care of fiddling things correctly. 8284 pkg.setPackageName(origPackage.name); 8285 8286 // File a report about this. 8287 String msg = "New package " + pkgSetting.realName 8288 + " renamed to replace old package " + pkgSetting.name; 8289 reportSettingsProblem(Log.WARN, msg); 8290 8291 // Make a note of it. 8292 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8293 mTransferedPackages.add(origPackage.name); 8294 } 8295 8296 // No longer need to retain this. 8297 pkgSetting.origPackage = null; 8298 } 8299 8300 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8301 // Make a note of it. 8302 mTransferedPackages.add(pkg.packageName); 8303 } 8304 8305 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8306 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8307 } 8308 8309 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8310 // Check all shared libraries and map to their actual file path. 8311 // We only do this here for apps not on a system dir, because those 8312 // are the only ones that can fail an install due to this. We 8313 // will take care of the system apps by updating all of their 8314 // library paths after the scan is done. 8315 updateSharedLibrariesLPw(pkg, null); 8316 } 8317 8318 if (mFoundPolicyFile) { 8319 SELinuxMMAC.assignSeinfoValue(pkg); 8320 } 8321 8322 pkg.applicationInfo.uid = pkgSetting.appId; 8323 pkg.mExtras = pkgSetting; 8324 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8325 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8326 // We just determined the app is signed correctly, so bring 8327 // over the latest parsed certs. 8328 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8329 } else { 8330 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8331 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8332 "Package " + pkg.packageName + " upgrade keys do not match the " 8333 + "previously installed version"); 8334 } else { 8335 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8336 String msg = "System package " + pkg.packageName 8337 + " signature changed; retaining data."; 8338 reportSettingsProblem(Log.WARN, msg); 8339 } 8340 } 8341 } else { 8342 try { 8343 verifySignaturesLP(pkgSetting, pkg); 8344 // We just determined the app is signed correctly, so bring 8345 // over the latest parsed certs. 8346 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8347 } catch (PackageManagerException e) { 8348 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8349 throw e; 8350 } 8351 // The signature has changed, but this package is in the system 8352 // image... let's recover! 8353 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8354 // However... if this package is part of a shared user, but it 8355 // doesn't match the signature of the shared user, let's fail. 8356 // What this means is that you can't change the signatures 8357 // associated with an overall shared user, which doesn't seem all 8358 // that unreasonable. 8359 if (pkgSetting.sharedUser != null) { 8360 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8361 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8362 throw new PackageManagerException( 8363 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8364 "Signature mismatch for shared user: " 8365 + pkgSetting.sharedUser); 8366 } 8367 } 8368 // File a report about this. 8369 String msg = "System package " + pkg.packageName 8370 + " signature changed; retaining data."; 8371 reportSettingsProblem(Log.WARN, msg); 8372 } 8373 } 8374 // Verify that this new package doesn't have any content providers 8375 // that conflict with existing packages. Only do this if the 8376 // package isn't already installed, since we don't want to break 8377 // things that are installed. 8378 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8379 final int N = pkg.providers.size(); 8380 int i; 8381 for (i=0; i<N; i++) { 8382 PackageParser.Provider p = pkg.providers.get(i); 8383 if (p.info.authority != null) { 8384 String names[] = p.info.authority.split(";"); 8385 for (int j = 0; j < names.length; j++) { 8386 if (mProvidersByAuthority.containsKey(names[j])) { 8387 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8388 final String otherPackageName = 8389 ((other != null && other.getComponentName() != null) ? 8390 other.getComponentName().getPackageName() : "?"); 8391 throw new PackageManagerException( 8392 INSTALL_FAILED_CONFLICTING_PROVIDER, 8393 "Can't install because provider name " + names[j] 8394 + " (in package " + pkg.applicationInfo.packageName 8395 + ") is already used by " + otherPackageName); 8396 } 8397 } 8398 } 8399 } 8400 } 8401 8402 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8403 // This package wants to adopt ownership of permissions from 8404 // another package. 8405 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8406 final String origName = pkg.mAdoptPermissions.get(i); 8407 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8408 if (orig != null) { 8409 if (verifyPackageUpdateLPr(orig, pkg)) { 8410 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8411 + pkg.packageName); 8412 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8413 } 8414 } 8415 } 8416 } 8417 } 8418 8419 final String pkgName = pkg.packageName; 8420 8421 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8422 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8423 pkg.applicationInfo.processName = fixProcessName( 8424 pkg.applicationInfo.packageName, 8425 pkg.applicationInfo.processName, 8426 pkg.applicationInfo.uid); 8427 8428 if (pkg != mPlatformPackage) { 8429 // Get all of our default paths setup 8430 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8431 } 8432 8433 final String path = scanFile.getPath(); 8434 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8435 8436 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8437 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8438 8439 // Some system apps still use directory structure for native libraries 8440 // in which case we might end up not detecting abi solely based on apk 8441 // structure. Try to detect abi based on directory structure. 8442 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8443 pkg.applicationInfo.primaryCpuAbi == null) { 8444 setBundledAppAbisAndRoots(pkg, pkgSetting); 8445 setNativeLibraryPaths(pkg); 8446 } 8447 8448 } else { 8449 if ((scanFlags & SCAN_MOVE) != 0) { 8450 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8451 // but we already have this packages package info in the PackageSetting. We just 8452 // use that and derive the native library path based on the new codepath. 8453 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8454 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8455 } 8456 8457 // Set native library paths again. For moves, the path will be updated based on the 8458 // ABIs we've determined above. For non-moves, the path will be updated based on the 8459 // ABIs we determined during compilation, but the path will depend on the final 8460 // package path (after the rename away from the stage path). 8461 setNativeLibraryPaths(pkg); 8462 } 8463 8464 // This is a special case for the "system" package, where the ABI is 8465 // dictated by the zygote configuration (and init.rc). We should keep track 8466 // of this ABI so that we can deal with "normal" applications that run under 8467 // the same UID correctly. 8468 if (mPlatformPackage == pkg) { 8469 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8470 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8471 } 8472 8473 // If there's a mismatch between the abi-override in the package setting 8474 // and the abiOverride specified for the install. Warn about this because we 8475 // would've already compiled the app without taking the package setting into 8476 // account. 8477 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8478 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8479 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8480 " for package " + pkg.packageName); 8481 } 8482 } 8483 8484 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8485 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8486 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8487 8488 // Copy the derived override back to the parsed package, so that we can 8489 // update the package settings accordingly. 8490 pkg.cpuAbiOverride = cpuAbiOverride; 8491 8492 if (DEBUG_ABI_SELECTION) { 8493 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8494 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8495 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8496 } 8497 8498 // Push the derived path down into PackageSettings so we know what to 8499 // clean up at uninstall time. 8500 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8501 8502 if (DEBUG_ABI_SELECTION) { 8503 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8504 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8505 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8506 } 8507 8508 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8509 // We don't do this here during boot because we can do it all 8510 // at once after scanning all existing packages. 8511 // 8512 // We also do this *before* we perform dexopt on this package, so that 8513 // we can avoid redundant dexopts, and also to make sure we've got the 8514 // code and package path correct. 8515 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8516 pkg, true /* boot complete */); 8517 } 8518 8519 if (mFactoryTest && pkg.requestedPermissions.contains( 8520 android.Manifest.permission.FACTORY_TEST)) { 8521 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8522 } 8523 8524 ArrayList<PackageParser.Package> clientLibPkgs = null; 8525 8526 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8527 if (nonMutatedPs != null) { 8528 synchronized (mPackages) { 8529 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8530 } 8531 } 8532 return pkg; 8533 } 8534 8535 // Only privileged apps and updated privileged apps can add child packages. 8536 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8537 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8538 throw new PackageManagerException("Only privileged apps and updated " 8539 + "privileged apps can add child packages. Ignoring package " 8540 + pkg.packageName); 8541 } 8542 final int childCount = pkg.childPackages.size(); 8543 for (int i = 0; i < childCount; i++) { 8544 PackageParser.Package childPkg = pkg.childPackages.get(i); 8545 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8546 childPkg.packageName)) { 8547 throw new PackageManagerException("Cannot override a child package of " 8548 + "another disabled system app. Ignoring package " + pkg.packageName); 8549 } 8550 } 8551 } 8552 8553 // writer 8554 synchronized (mPackages) { 8555 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8556 // Only system apps can add new shared libraries. 8557 if (pkg.libraryNames != null) { 8558 for (int i=0; i<pkg.libraryNames.size(); i++) { 8559 String name = pkg.libraryNames.get(i); 8560 boolean allowed = false; 8561 if (pkg.isUpdatedSystemApp()) { 8562 // New library entries can only be added through the 8563 // system image. This is important to get rid of a lot 8564 // of nasty edge cases: for example if we allowed a non- 8565 // system update of the app to add a library, then uninstalling 8566 // the update would make the library go away, and assumptions 8567 // we made such as through app install filtering would now 8568 // have allowed apps on the device which aren't compatible 8569 // with it. Better to just have the restriction here, be 8570 // conservative, and create many fewer cases that can negatively 8571 // impact the user experience. 8572 final PackageSetting sysPs = mSettings 8573 .getDisabledSystemPkgLPr(pkg.packageName); 8574 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8575 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8576 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8577 allowed = true; 8578 break; 8579 } 8580 } 8581 } 8582 } else { 8583 allowed = true; 8584 } 8585 if (allowed) { 8586 if (!mSharedLibraries.containsKey(name)) { 8587 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8588 } else if (!name.equals(pkg.packageName)) { 8589 Slog.w(TAG, "Package " + pkg.packageName + " library " 8590 + name + " already exists; skipping"); 8591 } 8592 } else { 8593 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8594 + name + " that is not declared on system image; skipping"); 8595 } 8596 } 8597 if ((scanFlags & SCAN_BOOTING) == 0) { 8598 // If we are not booting, we need to update any applications 8599 // that are clients of our shared library. If we are booting, 8600 // this will all be done once the scan is complete. 8601 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8602 } 8603 } 8604 } 8605 } 8606 8607 if ((scanFlags & SCAN_BOOTING) != 0) { 8608 // No apps can run during boot scan, so they don't need to be frozen 8609 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8610 // Caller asked to not kill app, so it's probably not frozen 8611 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8612 // Caller asked us to ignore frozen check for some reason; they 8613 // probably didn't know the package name 8614 } else { 8615 // We're doing major surgery on this package, so it better be frozen 8616 // right now to keep it from launching 8617 checkPackageFrozen(pkgName); 8618 } 8619 8620 // Also need to kill any apps that are dependent on the library. 8621 if (clientLibPkgs != null) { 8622 for (int i=0; i<clientLibPkgs.size(); i++) { 8623 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8624 killApplication(clientPkg.applicationInfo.packageName, 8625 clientPkg.applicationInfo.uid, "update lib"); 8626 } 8627 } 8628 8629 // Make sure we're not adding any bogus keyset info 8630 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8631 ksms.assertScannedPackageValid(pkg); 8632 8633 // writer 8634 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8635 8636 boolean createIdmapFailed = false; 8637 synchronized (mPackages) { 8638 // We don't expect installation to fail beyond this point 8639 8640 if (pkgSetting.pkg != null) { 8641 // Note that |user| might be null during the initial boot scan. If a codePath 8642 // for an app has changed during a boot scan, it's due to an app update that's 8643 // part of the system partition and marker changes must be applied to all users. 8644 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8645 (user != null) ? user : UserHandle.ALL); 8646 } 8647 8648 // Add the new setting to mSettings 8649 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8650 // Add the new setting to mPackages 8651 mPackages.put(pkg.applicationInfo.packageName, pkg); 8652 // Make sure we don't accidentally delete its data. 8653 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8654 while (iter.hasNext()) { 8655 PackageCleanItem item = iter.next(); 8656 if (pkgName.equals(item.packageName)) { 8657 iter.remove(); 8658 } 8659 } 8660 8661 // Take care of first install / last update times. 8662 if (currentTime != 0) { 8663 if (pkgSetting.firstInstallTime == 0) { 8664 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8665 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8666 pkgSetting.lastUpdateTime = currentTime; 8667 } 8668 } else if (pkgSetting.firstInstallTime == 0) { 8669 // We need *something*. Take time time stamp of the file. 8670 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8671 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8672 if (scanFileTime != pkgSetting.timeStamp) { 8673 // A package on the system image has changed; consider this 8674 // to be an update. 8675 pkgSetting.lastUpdateTime = scanFileTime; 8676 } 8677 } 8678 8679 // Add the package's KeySets to the global KeySetManagerService 8680 ksms.addScannedPackageLPw(pkg); 8681 8682 int N = pkg.providers.size(); 8683 StringBuilder r = null; 8684 int i; 8685 for (i=0; i<N; i++) { 8686 PackageParser.Provider p = pkg.providers.get(i); 8687 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8688 p.info.processName, pkg.applicationInfo.uid); 8689 mProviders.addProvider(p); 8690 p.syncable = p.info.isSyncable; 8691 if (p.info.authority != null) { 8692 String names[] = p.info.authority.split(";"); 8693 p.info.authority = null; 8694 for (int j = 0; j < names.length; j++) { 8695 if (j == 1 && p.syncable) { 8696 // We only want the first authority for a provider to possibly be 8697 // syncable, so if we already added this provider using a different 8698 // authority clear the syncable flag. We copy the provider before 8699 // changing it because the mProviders object contains a reference 8700 // to a provider that we don't want to change. 8701 // Only do this for the second authority since the resulting provider 8702 // object can be the same for all future authorities for this provider. 8703 p = new PackageParser.Provider(p); 8704 p.syncable = false; 8705 } 8706 if (!mProvidersByAuthority.containsKey(names[j])) { 8707 mProvidersByAuthority.put(names[j], p); 8708 if (p.info.authority == null) { 8709 p.info.authority = names[j]; 8710 } else { 8711 p.info.authority = p.info.authority + ";" + names[j]; 8712 } 8713 if (DEBUG_PACKAGE_SCANNING) { 8714 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8715 Log.d(TAG, "Registered content provider: " + names[j] 8716 + ", className = " + p.info.name + ", isSyncable = " 8717 + p.info.isSyncable); 8718 } 8719 } else { 8720 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8721 Slog.w(TAG, "Skipping provider name " + names[j] + 8722 " (in package " + pkg.applicationInfo.packageName + 8723 "): name already used by " 8724 + ((other != null && other.getComponentName() != null) 8725 ? other.getComponentName().getPackageName() : "?")); 8726 } 8727 } 8728 } 8729 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8730 if (r == null) { 8731 r = new StringBuilder(256); 8732 } else { 8733 r.append(' '); 8734 } 8735 r.append(p.info.name); 8736 } 8737 } 8738 if (r != null) { 8739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8740 } 8741 8742 N = pkg.services.size(); 8743 r = null; 8744 for (i=0; i<N; i++) { 8745 PackageParser.Service s = pkg.services.get(i); 8746 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8747 s.info.processName, pkg.applicationInfo.uid); 8748 mServices.addService(s); 8749 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8750 if (r == null) { 8751 r = new StringBuilder(256); 8752 } else { 8753 r.append(' '); 8754 } 8755 r.append(s.info.name); 8756 } 8757 } 8758 if (r != null) { 8759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8760 } 8761 8762 N = pkg.receivers.size(); 8763 r = null; 8764 for (i=0; i<N; i++) { 8765 PackageParser.Activity a = pkg.receivers.get(i); 8766 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8767 a.info.processName, pkg.applicationInfo.uid); 8768 mReceivers.addActivity(a, "receiver"); 8769 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8770 if (r == null) { 8771 r = new StringBuilder(256); 8772 } else { 8773 r.append(' '); 8774 } 8775 r.append(a.info.name); 8776 } 8777 } 8778 if (r != null) { 8779 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8780 } 8781 8782 N = pkg.activities.size(); 8783 r = null; 8784 for (i=0; i<N; i++) { 8785 PackageParser.Activity a = pkg.activities.get(i); 8786 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8787 a.info.processName, pkg.applicationInfo.uid); 8788 mActivities.addActivity(a, "activity"); 8789 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8790 if (r == null) { 8791 r = new StringBuilder(256); 8792 } else { 8793 r.append(' '); 8794 } 8795 r.append(a.info.name); 8796 } 8797 } 8798 if (r != null) { 8799 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8800 } 8801 8802 N = pkg.permissionGroups.size(); 8803 r = null; 8804 for (i=0; i<N; i++) { 8805 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8806 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8807 if (cur == null) { 8808 mPermissionGroups.put(pg.info.name, pg); 8809 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8810 if (r == null) { 8811 r = new StringBuilder(256); 8812 } else { 8813 r.append(' '); 8814 } 8815 r.append(pg.info.name); 8816 } 8817 } else { 8818 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8819 + pg.info.packageName + " ignored: original from " 8820 + cur.info.packageName); 8821 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8822 if (r == null) { 8823 r = new StringBuilder(256); 8824 } else { 8825 r.append(' '); 8826 } 8827 r.append("DUP:"); 8828 r.append(pg.info.name); 8829 } 8830 } 8831 } 8832 if (r != null) { 8833 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8834 } 8835 8836 N = pkg.permissions.size(); 8837 r = null; 8838 for (i=0; i<N; i++) { 8839 PackageParser.Permission p = pkg.permissions.get(i); 8840 8841 // Assume by default that we did not install this permission into the system. 8842 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8843 8844 // Now that permission groups have a special meaning, we ignore permission 8845 // groups for legacy apps to prevent unexpected behavior. In particular, 8846 // permissions for one app being granted to someone just becase they happen 8847 // to be in a group defined by another app (before this had no implications). 8848 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8849 p.group = mPermissionGroups.get(p.info.group); 8850 // Warn for a permission in an unknown group. 8851 if (p.info.group != null && p.group == null) { 8852 Slog.w(TAG, "Permission " + p.info.name + " from package " 8853 + p.info.packageName + " in an unknown group " + p.info.group); 8854 } 8855 } 8856 8857 ArrayMap<String, BasePermission> permissionMap = 8858 p.tree ? mSettings.mPermissionTrees 8859 : mSettings.mPermissions; 8860 BasePermission bp = permissionMap.get(p.info.name); 8861 8862 // Allow system apps to redefine non-system permissions 8863 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8864 final boolean currentOwnerIsSystem = (bp.perm != null 8865 && isSystemApp(bp.perm.owner)); 8866 if (isSystemApp(p.owner)) { 8867 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8868 // It's a built-in permission and no owner, take ownership now 8869 bp.packageSetting = pkgSetting; 8870 bp.perm = p; 8871 bp.uid = pkg.applicationInfo.uid; 8872 bp.sourcePackage = p.info.packageName; 8873 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8874 } else if (!currentOwnerIsSystem) { 8875 String msg = "New decl " + p.owner + " of permission " 8876 + p.info.name + " is system; overriding " + bp.sourcePackage; 8877 reportSettingsProblem(Log.WARN, msg); 8878 bp = null; 8879 } 8880 } 8881 } 8882 8883 if (bp == null) { 8884 bp = new BasePermission(p.info.name, p.info.packageName, 8885 BasePermission.TYPE_NORMAL); 8886 permissionMap.put(p.info.name, bp); 8887 } 8888 8889 if (bp.perm == null) { 8890 if (bp.sourcePackage == null 8891 || bp.sourcePackage.equals(p.info.packageName)) { 8892 BasePermission tree = findPermissionTreeLP(p.info.name); 8893 if (tree == null 8894 || tree.sourcePackage.equals(p.info.packageName)) { 8895 bp.packageSetting = pkgSetting; 8896 bp.perm = p; 8897 bp.uid = pkg.applicationInfo.uid; 8898 bp.sourcePackage = p.info.packageName; 8899 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8900 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8901 if (r == null) { 8902 r = new StringBuilder(256); 8903 } else { 8904 r.append(' '); 8905 } 8906 r.append(p.info.name); 8907 } 8908 } else { 8909 Slog.w(TAG, "Permission " + p.info.name + " from package " 8910 + p.info.packageName + " ignored: base tree " 8911 + tree.name + " is from package " 8912 + tree.sourcePackage); 8913 } 8914 } else { 8915 Slog.w(TAG, "Permission " + p.info.name + " from package " 8916 + p.info.packageName + " ignored: original from " 8917 + bp.sourcePackage); 8918 } 8919 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8920 if (r == null) { 8921 r = new StringBuilder(256); 8922 } else { 8923 r.append(' '); 8924 } 8925 r.append("DUP:"); 8926 r.append(p.info.name); 8927 } 8928 if (bp.perm == p) { 8929 bp.protectionLevel = p.info.protectionLevel; 8930 } 8931 } 8932 8933 if (r != null) { 8934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8935 } 8936 8937 N = pkg.instrumentation.size(); 8938 r = null; 8939 for (i=0; i<N; i++) { 8940 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8941 a.info.packageName = pkg.applicationInfo.packageName; 8942 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8943 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8944 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8945 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8946 a.info.dataDir = pkg.applicationInfo.dataDir; 8947 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8948 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8949 8950 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8951 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8952 mInstrumentation.put(a.getComponentName(), a); 8953 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8954 if (r == null) { 8955 r = new StringBuilder(256); 8956 } else { 8957 r.append(' '); 8958 } 8959 r.append(a.info.name); 8960 } 8961 } 8962 if (r != null) { 8963 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8964 } 8965 8966 if (pkg.protectedBroadcasts != null) { 8967 N = pkg.protectedBroadcasts.size(); 8968 for (i=0; i<N; i++) { 8969 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8970 } 8971 } 8972 8973 pkgSetting.setTimeStamp(scanFileTime); 8974 8975 // Create idmap files for pairs of (packages, overlay packages). 8976 // Note: "android", ie framework-res.apk, is handled by native layers. 8977 if (pkg.mOverlayTarget != null) { 8978 // This is an overlay package. 8979 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8980 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8981 mOverlays.put(pkg.mOverlayTarget, 8982 new ArrayMap<String, PackageParser.Package>()); 8983 } 8984 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8985 map.put(pkg.packageName, pkg); 8986 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8987 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8988 createIdmapFailed = true; 8989 } 8990 } 8991 } else if (mOverlays.containsKey(pkg.packageName) && 8992 !pkg.packageName.equals("android")) { 8993 // This is a regular package, with one or more known overlay packages. 8994 createIdmapsForPackageLI(pkg); 8995 } 8996 } 8997 8998 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8999 9000 if (createIdmapFailed) { 9001 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9002 "scanPackageLI failed to createIdmap"); 9003 } 9004 return pkg; 9005 } 9006 9007 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9008 PackageParser.Package update, UserHandle user) { 9009 if (existing.applicationInfo == null || update.applicationInfo == null) { 9010 // This isn't due to an app installation. 9011 return; 9012 } 9013 9014 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9015 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9016 9017 // The codePath hasn't changed, so there's nothing for us to do. 9018 if (Objects.equals(oldCodePath, newCodePath)) { 9019 return; 9020 } 9021 9022 File canonicalNewCodePath; 9023 try { 9024 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9025 } catch (IOException e) { 9026 Slog.w(TAG, "Failed to get canonical path.", e); 9027 return; 9028 } 9029 9030 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9031 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9032 // that the last component of the path (i.e, the name) doesn't need canonicalization 9033 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9034 // but may change in the future. Hopefully this function won't exist at that point. 9035 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9036 oldCodePath.getName()); 9037 9038 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9039 // with "@". 9040 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9041 if (!oldMarkerPrefix.endsWith("@")) { 9042 oldMarkerPrefix += "@"; 9043 } 9044 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9045 if (!newMarkerPrefix.endsWith("@")) { 9046 newMarkerPrefix += "@"; 9047 } 9048 9049 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9050 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9051 for (String updatedPath : updatedPaths) { 9052 String updatedPathName = new File(updatedPath).getName(); 9053 markerSuffixes.add(updatedPathName.replace('/', '@')); 9054 } 9055 9056 for (int userId : resolveUserIds(user.getIdentifier())) { 9057 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9058 9059 for (String markerSuffix : markerSuffixes) { 9060 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9061 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9062 if (oldForeignUseMark.exists()) { 9063 try { 9064 Os.rename(oldForeignUseMark.getAbsolutePath(), 9065 newForeignUseMark.getAbsolutePath()); 9066 } catch (ErrnoException e) { 9067 Slog.w(TAG, "Failed to rename foreign use marker", e); 9068 oldForeignUseMark.delete(); 9069 } 9070 } 9071 } 9072 } 9073 } 9074 9075 /** 9076 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9077 * is derived purely on the basis of the contents of {@code scanFile} and 9078 * {@code cpuAbiOverride}. 9079 * 9080 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9081 */ 9082 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9083 String cpuAbiOverride, boolean extractLibs) 9084 throws PackageManagerException { 9085 // TODO: We can probably be smarter about this stuff. For installed apps, 9086 // we can calculate this information at install time once and for all. For 9087 // system apps, we can probably assume that this information doesn't change 9088 // after the first boot scan. As things stand, we do lots of unnecessary work. 9089 9090 // Give ourselves some initial paths; we'll come back for another 9091 // pass once we've determined ABI below. 9092 setNativeLibraryPaths(pkg); 9093 9094 // We would never need to extract libs for forward-locked and external packages, 9095 // since the container service will do it for us. We shouldn't attempt to 9096 // extract libs from system app when it was not updated. 9097 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9098 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9099 extractLibs = false; 9100 } 9101 9102 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9103 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9104 9105 NativeLibraryHelper.Handle handle = null; 9106 try { 9107 handle = NativeLibraryHelper.Handle.create(pkg); 9108 // TODO(multiArch): This can be null for apps that didn't go through the 9109 // usual installation process. We can calculate it again, like we 9110 // do during install time. 9111 // 9112 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9113 // unnecessary. 9114 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9115 9116 // Null out the abis so that they can be recalculated. 9117 pkg.applicationInfo.primaryCpuAbi = null; 9118 pkg.applicationInfo.secondaryCpuAbi = null; 9119 if (isMultiArch(pkg.applicationInfo)) { 9120 // Warn if we've set an abiOverride for multi-lib packages.. 9121 // By definition, we need to copy both 32 and 64 bit libraries for 9122 // such packages. 9123 if (pkg.cpuAbiOverride != null 9124 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9125 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9126 } 9127 9128 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9129 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9130 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9131 if (extractLibs) { 9132 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9133 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9134 useIsaSpecificSubdirs); 9135 } else { 9136 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9137 } 9138 } 9139 9140 maybeThrowExceptionForMultiArchCopy( 9141 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9142 9143 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9144 if (extractLibs) { 9145 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9146 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9147 useIsaSpecificSubdirs); 9148 } else { 9149 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9150 } 9151 } 9152 9153 maybeThrowExceptionForMultiArchCopy( 9154 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9155 9156 if (abi64 >= 0) { 9157 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9158 } 9159 9160 if (abi32 >= 0) { 9161 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9162 if (abi64 >= 0) { 9163 if (pkg.use32bitAbi) { 9164 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9165 pkg.applicationInfo.primaryCpuAbi = abi; 9166 } else { 9167 pkg.applicationInfo.secondaryCpuAbi = abi; 9168 } 9169 } else { 9170 pkg.applicationInfo.primaryCpuAbi = abi; 9171 } 9172 } 9173 9174 } else { 9175 String[] abiList = (cpuAbiOverride != null) ? 9176 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9177 9178 // Enable gross and lame hacks for apps that are built with old 9179 // SDK tools. We must scan their APKs for renderscript bitcode and 9180 // not launch them if it's present. Don't bother checking on devices 9181 // that don't have 64 bit support. 9182 boolean needsRenderScriptOverride = false; 9183 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9184 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9185 abiList = Build.SUPPORTED_32_BIT_ABIS; 9186 needsRenderScriptOverride = true; 9187 } 9188 9189 final int copyRet; 9190 if (extractLibs) { 9191 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9192 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9193 } else { 9194 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9195 } 9196 9197 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9198 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9199 "Error unpackaging native libs for app, errorCode=" + copyRet); 9200 } 9201 9202 if (copyRet >= 0) { 9203 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9204 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9205 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9206 } else if (needsRenderScriptOverride) { 9207 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9208 } 9209 } 9210 } catch (IOException ioe) { 9211 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9212 } finally { 9213 IoUtils.closeQuietly(handle); 9214 } 9215 9216 // Now that we've calculated the ABIs and determined if it's an internal app, 9217 // we will go ahead and populate the nativeLibraryPath. 9218 setNativeLibraryPaths(pkg); 9219 } 9220 9221 /** 9222 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9223 * i.e, so that all packages can be run inside a single process if required. 9224 * 9225 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9226 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9227 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9228 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9229 * updating a package that belongs to a shared user. 9230 * 9231 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9232 * adds unnecessary complexity. 9233 */ 9234 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9235 PackageParser.Package scannedPackage, boolean bootComplete) { 9236 String requiredInstructionSet = null; 9237 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9238 requiredInstructionSet = VMRuntime.getInstructionSet( 9239 scannedPackage.applicationInfo.primaryCpuAbi); 9240 } 9241 9242 PackageSetting requirer = null; 9243 for (PackageSetting ps : packagesForUser) { 9244 // If packagesForUser contains scannedPackage, we skip it. This will happen 9245 // when scannedPackage is an update of an existing package. Without this check, 9246 // we will never be able to change the ABI of any package belonging to a shared 9247 // user, even if it's compatible with other packages. 9248 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9249 if (ps.primaryCpuAbiString == null) { 9250 continue; 9251 } 9252 9253 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9254 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9255 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9256 // this but there's not much we can do. 9257 String errorMessage = "Instruction set mismatch, " 9258 + ((requirer == null) ? "[caller]" : requirer) 9259 + " requires " + requiredInstructionSet + " whereas " + ps 9260 + " requires " + instructionSet; 9261 Slog.w(TAG, errorMessage); 9262 } 9263 9264 if (requiredInstructionSet == null) { 9265 requiredInstructionSet = instructionSet; 9266 requirer = ps; 9267 } 9268 } 9269 } 9270 9271 if (requiredInstructionSet != null) { 9272 String adjustedAbi; 9273 if (requirer != null) { 9274 // requirer != null implies that either scannedPackage was null or that scannedPackage 9275 // did not require an ABI, in which case we have to adjust scannedPackage to match 9276 // the ABI of the set (which is the same as requirer's ABI) 9277 adjustedAbi = requirer.primaryCpuAbiString; 9278 if (scannedPackage != null) { 9279 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9280 } 9281 } else { 9282 // requirer == null implies that we're updating all ABIs in the set to 9283 // match scannedPackage. 9284 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9285 } 9286 9287 for (PackageSetting ps : packagesForUser) { 9288 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9289 if (ps.primaryCpuAbiString != null) { 9290 continue; 9291 } 9292 9293 ps.primaryCpuAbiString = adjustedAbi; 9294 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9295 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9296 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9297 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9298 + " (requirer=" 9299 + (requirer == null ? "null" : requirer.pkg.packageName) 9300 + ", scannedPackage=" 9301 + (scannedPackage != null ? scannedPackage.packageName : "null") 9302 + ")"); 9303 try { 9304 mInstaller.rmdex(ps.codePathString, 9305 getDexCodeInstructionSet(getPreferredInstructionSet())); 9306 } catch (InstallerException ignored) { 9307 } 9308 } 9309 } 9310 } 9311 } 9312 } 9313 9314 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9315 synchronized (mPackages) { 9316 mResolverReplaced = true; 9317 // Set up information for custom user intent resolution activity. 9318 mResolveActivity.applicationInfo = pkg.applicationInfo; 9319 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9320 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9321 mResolveActivity.processName = pkg.applicationInfo.packageName; 9322 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9323 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9324 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9325 mResolveActivity.theme = 0; 9326 mResolveActivity.exported = true; 9327 mResolveActivity.enabled = true; 9328 mResolveInfo.activityInfo = mResolveActivity; 9329 mResolveInfo.priority = 0; 9330 mResolveInfo.preferredOrder = 0; 9331 mResolveInfo.match = 0; 9332 mResolveComponentName = mCustomResolverComponentName; 9333 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9334 mResolveComponentName); 9335 } 9336 } 9337 9338 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9339 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9340 9341 // Set up information for ephemeral installer activity 9342 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9343 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9344 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9345 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9346 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9347 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9348 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9349 mEphemeralInstallerActivity.theme = 0; 9350 mEphemeralInstallerActivity.exported = true; 9351 mEphemeralInstallerActivity.enabled = true; 9352 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9353 mEphemeralInstallerInfo.priority = 0; 9354 mEphemeralInstallerInfo.preferredOrder = 0; 9355 mEphemeralInstallerInfo.match = 0; 9356 9357 if (DEBUG_EPHEMERAL) { 9358 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9359 } 9360 } 9361 9362 private static String calculateBundledApkRoot(final String codePathString) { 9363 final File codePath = new File(codePathString); 9364 final File codeRoot; 9365 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9366 codeRoot = Environment.getRootDirectory(); 9367 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9368 codeRoot = Environment.getOemDirectory(); 9369 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9370 codeRoot = Environment.getVendorDirectory(); 9371 } else { 9372 // Unrecognized code path; take its top real segment as the apk root: 9373 // e.g. /something/app/blah.apk => /something 9374 try { 9375 File f = codePath.getCanonicalFile(); 9376 File parent = f.getParentFile(); // non-null because codePath is a file 9377 File tmp; 9378 while ((tmp = parent.getParentFile()) != null) { 9379 f = parent; 9380 parent = tmp; 9381 } 9382 codeRoot = f; 9383 Slog.w(TAG, "Unrecognized code path " 9384 + codePath + " - using " + codeRoot); 9385 } catch (IOException e) { 9386 // Can't canonicalize the code path -- shenanigans? 9387 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9388 return Environment.getRootDirectory().getPath(); 9389 } 9390 } 9391 return codeRoot.getPath(); 9392 } 9393 9394 /** 9395 * Derive and set the location of native libraries for the given package, 9396 * which varies depending on where and how the package was installed. 9397 */ 9398 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9399 final ApplicationInfo info = pkg.applicationInfo; 9400 final String codePath = pkg.codePath; 9401 final File codeFile = new File(codePath); 9402 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9403 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9404 9405 info.nativeLibraryRootDir = null; 9406 info.nativeLibraryRootRequiresIsa = false; 9407 info.nativeLibraryDir = null; 9408 info.secondaryNativeLibraryDir = null; 9409 9410 if (isApkFile(codeFile)) { 9411 // Monolithic install 9412 if (bundledApp) { 9413 // If "/system/lib64/apkname" exists, assume that is the per-package 9414 // native library directory to use; otherwise use "/system/lib/apkname". 9415 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9416 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9417 getPrimaryInstructionSet(info)); 9418 9419 // This is a bundled system app so choose the path based on the ABI. 9420 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9421 // is just the default path. 9422 final String apkName = deriveCodePathName(codePath); 9423 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9424 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9425 apkName).getAbsolutePath(); 9426 9427 if (info.secondaryCpuAbi != null) { 9428 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9429 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9430 secondaryLibDir, apkName).getAbsolutePath(); 9431 } 9432 } else if (asecApp) { 9433 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9434 .getAbsolutePath(); 9435 } else { 9436 final String apkName = deriveCodePathName(codePath); 9437 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9438 .getAbsolutePath(); 9439 } 9440 9441 info.nativeLibraryRootRequiresIsa = false; 9442 info.nativeLibraryDir = info.nativeLibraryRootDir; 9443 } else { 9444 // Cluster install 9445 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9446 info.nativeLibraryRootRequiresIsa = true; 9447 9448 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9449 getPrimaryInstructionSet(info)).getAbsolutePath(); 9450 9451 if (info.secondaryCpuAbi != null) { 9452 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9453 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9454 } 9455 } 9456 } 9457 9458 /** 9459 * Calculate the abis and roots for a bundled app. These can uniquely 9460 * be determined from the contents of the system partition, i.e whether 9461 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9462 * of this information, and instead assume that the system was built 9463 * sensibly. 9464 */ 9465 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9466 PackageSetting pkgSetting) { 9467 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9468 9469 // If "/system/lib64/apkname" exists, assume that is the per-package 9470 // native library directory to use; otherwise use "/system/lib/apkname". 9471 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9472 setBundledAppAbi(pkg, apkRoot, apkName); 9473 // pkgSetting might be null during rescan following uninstall of updates 9474 // to a bundled app, so accommodate that possibility. The settings in 9475 // that case will be established later from the parsed package. 9476 // 9477 // If the settings aren't null, sync them up with what we've just derived. 9478 // note that apkRoot isn't stored in the package settings. 9479 if (pkgSetting != null) { 9480 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9481 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9482 } 9483 } 9484 9485 /** 9486 * Deduces the ABI of a bundled app and sets the relevant fields on the 9487 * parsed pkg object. 9488 * 9489 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9490 * under which system libraries are installed. 9491 * @param apkName the name of the installed package. 9492 */ 9493 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9494 final File codeFile = new File(pkg.codePath); 9495 9496 final boolean has64BitLibs; 9497 final boolean has32BitLibs; 9498 if (isApkFile(codeFile)) { 9499 // Monolithic install 9500 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9501 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9502 } else { 9503 // Cluster install 9504 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9505 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9506 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9507 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9508 has64BitLibs = (new File(rootDir, isa)).exists(); 9509 } else { 9510 has64BitLibs = false; 9511 } 9512 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9513 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9514 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9515 has32BitLibs = (new File(rootDir, isa)).exists(); 9516 } else { 9517 has32BitLibs = false; 9518 } 9519 } 9520 9521 if (has64BitLibs && !has32BitLibs) { 9522 // The package has 64 bit libs, but not 32 bit libs. Its primary 9523 // ABI should be 64 bit. We can safely assume here that the bundled 9524 // native libraries correspond to the most preferred ABI in the list. 9525 9526 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9527 pkg.applicationInfo.secondaryCpuAbi = null; 9528 } else if (has32BitLibs && !has64BitLibs) { 9529 // The package has 32 bit libs but not 64 bit libs. Its primary 9530 // ABI should be 32 bit. 9531 9532 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9533 pkg.applicationInfo.secondaryCpuAbi = null; 9534 } else if (has32BitLibs && has64BitLibs) { 9535 // The application has both 64 and 32 bit bundled libraries. We check 9536 // here that the app declares multiArch support, and warn if it doesn't. 9537 // 9538 // We will be lenient here and record both ABIs. The primary will be the 9539 // ABI that's higher on the list, i.e, a device that's configured to prefer 9540 // 64 bit apps will see a 64 bit primary ABI, 9541 9542 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9543 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9544 } 9545 9546 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9547 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9548 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9549 } else { 9550 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9551 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9552 } 9553 } else { 9554 pkg.applicationInfo.primaryCpuAbi = null; 9555 pkg.applicationInfo.secondaryCpuAbi = null; 9556 } 9557 } 9558 9559 private void killApplication(String pkgName, int appId, String reason) { 9560 // Request the ActivityManager to kill the process(only for existing packages) 9561 // so that we do not end up in a confused state while the user is still using the older 9562 // version of the application while the new one gets installed. 9563 final long token = Binder.clearCallingIdentity(); 9564 try { 9565 IActivityManager am = ActivityManagerNative.getDefault(); 9566 if (am != null) { 9567 try { 9568 am.killApplicationWithAppId(pkgName, appId, reason); 9569 } catch (RemoteException e) { 9570 } 9571 } 9572 } finally { 9573 Binder.restoreCallingIdentity(token); 9574 } 9575 } 9576 9577 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9578 // Remove the parent package setting 9579 PackageSetting ps = (PackageSetting) pkg.mExtras; 9580 if (ps != null) { 9581 removePackageLI(ps, chatty); 9582 } 9583 // Remove the child package setting 9584 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9585 for (int i = 0; i < childCount; i++) { 9586 PackageParser.Package childPkg = pkg.childPackages.get(i); 9587 ps = (PackageSetting) childPkg.mExtras; 9588 if (ps != null) { 9589 removePackageLI(ps, chatty); 9590 } 9591 } 9592 } 9593 9594 void removePackageLI(PackageSetting ps, boolean chatty) { 9595 if (DEBUG_INSTALL) { 9596 if (chatty) 9597 Log.d(TAG, "Removing package " + ps.name); 9598 } 9599 9600 // writer 9601 synchronized (mPackages) { 9602 mPackages.remove(ps.name); 9603 final PackageParser.Package pkg = ps.pkg; 9604 if (pkg != null) { 9605 cleanPackageDataStructuresLILPw(pkg, chatty); 9606 } 9607 } 9608 } 9609 9610 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9611 if (DEBUG_INSTALL) { 9612 if (chatty) 9613 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9614 } 9615 9616 // writer 9617 synchronized (mPackages) { 9618 // Remove the parent package 9619 mPackages.remove(pkg.applicationInfo.packageName); 9620 cleanPackageDataStructuresLILPw(pkg, chatty); 9621 9622 // Remove the child packages 9623 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9624 for (int i = 0; i < childCount; i++) { 9625 PackageParser.Package childPkg = pkg.childPackages.get(i); 9626 mPackages.remove(childPkg.applicationInfo.packageName); 9627 cleanPackageDataStructuresLILPw(childPkg, chatty); 9628 } 9629 } 9630 } 9631 9632 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9633 int N = pkg.providers.size(); 9634 StringBuilder r = null; 9635 int i; 9636 for (i=0; i<N; i++) { 9637 PackageParser.Provider p = pkg.providers.get(i); 9638 mProviders.removeProvider(p); 9639 if (p.info.authority == null) { 9640 9641 /* There was another ContentProvider with this authority when 9642 * this app was installed so this authority is null, 9643 * Ignore it as we don't have to unregister the provider. 9644 */ 9645 continue; 9646 } 9647 String names[] = p.info.authority.split(";"); 9648 for (int j = 0; j < names.length; j++) { 9649 if (mProvidersByAuthority.get(names[j]) == p) { 9650 mProvidersByAuthority.remove(names[j]); 9651 if (DEBUG_REMOVE) { 9652 if (chatty) 9653 Log.d(TAG, "Unregistered content provider: " + names[j] 9654 + ", className = " + p.info.name + ", isSyncable = " 9655 + p.info.isSyncable); 9656 } 9657 } 9658 } 9659 if (DEBUG_REMOVE && chatty) { 9660 if (r == null) { 9661 r = new StringBuilder(256); 9662 } else { 9663 r.append(' '); 9664 } 9665 r.append(p.info.name); 9666 } 9667 } 9668 if (r != null) { 9669 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9670 } 9671 9672 N = pkg.services.size(); 9673 r = null; 9674 for (i=0; i<N; i++) { 9675 PackageParser.Service s = pkg.services.get(i); 9676 mServices.removeService(s); 9677 if (chatty) { 9678 if (r == null) { 9679 r = new StringBuilder(256); 9680 } else { 9681 r.append(' '); 9682 } 9683 r.append(s.info.name); 9684 } 9685 } 9686 if (r != null) { 9687 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9688 } 9689 9690 N = pkg.receivers.size(); 9691 r = null; 9692 for (i=0; i<N; i++) { 9693 PackageParser.Activity a = pkg.receivers.get(i); 9694 mReceivers.removeActivity(a, "receiver"); 9695 if (DEBUG_REMOVE && chatty) { 9696 if (r == null) { 9697 r = new StringBuilder(256); 9698 } else { 9699 r.append(' '); 9700 } 9701 r.append(a.info.name); 9702 } 9703 } 9704 if (r != null) { 9705 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9706 } 9707 9708 N = pkg.activities.size(); 9709 r = null; 9710 for (i=0; i<N; i++) { 9711 PackageParser.Activity a = pkg.activities.get(i); 9712 mActivities.removeActivity(a, "activity"); 9713 if (DEBUG_REMOVE && chatty) { 9714 if (r == null) { 9715 r = new StringBuilder(256); 9716 } else { 9717 r.append(' '); 9718 } 9719 r.append(a.info.name); 9720 } 9721 } 9722 if (r != null) { 9723 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9724 } 9725 9726 N = pkg.permissions.size(); 9727 r = null; 9728 for (i=0; i<N; i++) { 9729 PackageParser.Permission p = pkg.permissions.get(i); 9730 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9731 if (bp == null) { 9732 bp = mSettings.mPermissionTrees.get(p.info.name); 9733 } 9734 if (bp != null && bp.perm == p) { 9735 bp.perm = null; 9736 if (DEBUG_REMOVE && chatty) { 9737 if (r == null) { 9738 r = new StringBuilder(256); 9739 } else { 9740 r.append(' '); 9741 } 9742 r.append(p.info.name); 9743 } 9744 } 9745 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9746 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9747 if (appOpPkgs != null) { 9748 appOpPkgs.remove(pkg.packageName); 9749 } 9750 } 9751 } 9752 if (r != null) { 9753 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9754 } 9755 9756 N = pkg.requestedPermissions.size(); 9757 r = null; 9758 for (i=0; i<N; i++) { 9759 String perm = pkg.requestedPermissions.get(i); 9760 BasePermission bp = mSettings.mPermissions.get(perm); 9761 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9762 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9763 if (appOpPkgs != null) { 9764 appOpPkgs.remove(pkg.packageName); 9765 if (appOpPkgs.isEmpty()) { 9766 mAppOpPermissionPackages.remove(perm); 9767 } 9768 } 9769 } 9770 } 9771 if (r != null) { 9772 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9773 } 9774 9775 N = pkg.instrumentation.size(); 9776 r = null; 9777 for (i=0; i<N; i++) { 9778 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9779 mInstrumentation.remove(a.getComponentName()); 9780 if (DEBUG_REMOVE && chatty) { 9781 if (r == null) { 9782 r = new StringBuilder(256); 9783 } else { 9784 r.append(' '); 9785 } 9786 r.append(a.info.name); 9787 } 9788 } 9789 if (r != null) { 9790 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9791 } 9792 9793 r = null; 9794 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9795 // Only system apps can hold shared libraries. 9796 if (pkg.libraryNames != null) { 9797 for (i=0; i<pkg.libraryNames.size(); i++) { 9798 String name = pkg.libraryNames.get(i); 9799 SharedLibraryEntry cur = mSharedLibraries.get(name); 9800 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9801 mSharedLibraries.remove(name); 9802 if (DEBUG_REMOVE && chatty) { 9803 if (r == null) { 9804 r = new StringBuilder(256); 9805 } else { 9806 r.append(' '); 9807 } 9808 r.append(name); 9809 } 9810 } 9811 } 9812 } 9813 } 9814 if (r != null) { 9815 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9816 } 9817 } 9818 9819 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9820 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9821 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9822 return true; 9823 } 9824 } 9825 return false; 9826 } 9827 9828 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9829 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9830 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9831 9832 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9833 // Update the parent permissions 9834 updatePermissionsLPw(pkg.packageName, pkg, flags); 9835 // Update the child permissions 9836 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9837 for (int i = 0; i < childCount; i++) { 9838 PackageParser.Package childPkg = pkg.childPackages.get(i); 9839 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9840 } 9841 } 9842 9843 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9844 int flags) { 9845 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9846 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9847 } 9848 9849 private void updatePermissionsLPw(String changingPkg, 9850 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9851 // Make sure there are no dangling permission trees. 9852 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9853 while (it.hasNext()) { 9854 final BasePermission bp = it.next(); 9855 if (bp.packageSetting == null) { 9856 // We may not yet have parsed the package, so just see if 9857 // we still know about its settings. 9858 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9859 } 9860 if (bp.packageSetting == null) { 9861 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9862 + " from package " + bp.sourcePackage); 9863 it.remove(); 9864 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9865 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9866 Slog.i(TAG, "Removing old permission tree: " + bp.name 9867 + " from package " + bp.sourcePackage); 9868 flags |= UPDATE_PERMISSIONS_ALL; 9869 it.remove(); 9870 } 9871 } 9872 } 9873 9874 // Make sure all dynamic permissions have been assigned to a package, 9875 // and make sure there are no dangling permissions. 9876 it = mSettings.mPermissions.values().iterator(); 9877 while (it.hasNext()) { 9878 final BasePermission bp = it.next(); 9879 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9880 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9881 + bp.name + " pkg=" + bp.sourcePackage 9882 + " info=" + bp.pendingInfo); 9883 if (bp.packageSetting == null && bp.pendingInfo != null) { 9884 final BasePermission tree = findPermissionTreeLP(bp.name); 9885 if (tree != null && tree.perm != null) { 9886 bp.packageSetting = tree.packageSetting; 9887 bp.perm = new PackageParser.Permission(tree.perm.owner, 9888 new PermissionInfo(bp.pendingInfo)); 9889 bp.perm.info.packageName = tree.perm.info.packageName; 9890 bp.perm.info.name = bp.name; 9891 bp.uid = tree.uid; 9892 } 9893 } 9894 } 9895 if (bp.packageSetting == null) { 9896 // We may not yet have parsed the package, so just see if 9897 // we still know about its settings. 9898 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9899 } 9900 if (bp.packageSetting == null) { 9901 Slog.w(TAG, "Removing dangling permission: " + bp.name 9902 + " from package " + bp.sourcePackage); 9903 it.remove(); 9904 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9905 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9906 Slog.i(TAG, "Removing old permission: " + bp.name 9907 + " from package " + bp.sourcePackage); 9908 flags |= UPDATE_PERMISSIONS_ALL; 9909 it.remove(); 9910 } 9911 } 9912 } 9913 9914 // Now update the permissions for all packages, in particular 9915 // replace the granted permissions of the system packages. 9916 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9917 for (PackageParser.Package pkg : mPackages.values()) { 9918 if (pkg != pkgInfo) { 9919 // Only replace for packages on requested volume 9920 final String volumeUuid = getVolumeUuidForPackage(pkg); 9921 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9922 && Objects.equals(replaceVolumeUuid, volumeUuid); 9923 grantPermissionsLPw(pkg, replace, changingPkg); 9924 } 9925 } 9926 } 9927 9928 if (pkgInfo != null) { 9929 // Only replace for packages on requested volume 9930 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9931 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9932 && Objects.equals(replaceVolumeUuid, volumeUuid); 9933 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9934 } 9935 } 9936 9937 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9938 String packageOfInterest) { 9939 // IMPORTANT: There are two types of permissions: install and runtime. 9940 // Install time permissions are granted when the app is installed to 9941 // all device users and users added in the future. Runtime permissions 9942 // are granted at runtime explicitly to specific users. Normal and signature 9943 // protected permissions are install time permissions. Dangerous permissions 9944 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9945 // otherwise they are runtime permissions. This function does not manage 9946 // runtime permissions except for the case an app targeting Lollipop MR1 9947 // being upgraded to target a newer SDK, in which case dangerous permissions 9948 // are transformed from install time to runtime ones. 9949 9950 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9951 if (ps == null) { 9952 return; 9953 } 9954 9955 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9956 9957 PermissionsState permissionsState = ps.getPermissionsState(); 9958 PermissionsState origPermissions = permissionsState; 9959 9960 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9961 9962 boolean runtimePermissionsRevoked = false; 9963 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9964 9965 boolean changedInstallPermission = false; 9966 9967 if (replace) { 9968 ps.installPermissionsFixed = false; 9969 if (!ps.isSharedUser()) { 9970 origPermissions = new PermissionsState(permissionsState); 9971 permissionsState.reset(); 9972 } else { 9973 // We need to know only about runtime permission changes since the 9974 // calling code always writes the install permissions state but 9975 // the runtime ones are written only if changed. The only cases of 9976 // changed runtime permissions here are promotion of an install to 9977 // runtime and revocation of a runtime from a shared user. 9978 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9979 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9980 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9981 runtimePermissionsRevoked = true; 9982 } 9983 } 9984 } 9985 9986 permissionsState.setGlobalGids(mGlobalGids); 9987 9988 final int N = pkg.requestedPermissions.size(); 9989 for (int i=0; i<N; i++) { 9990 final String name = pkg.requestedPermissions.get(i); 9991 final BasePermission bp = mSettings.mPermissions.get(name); 9992 9993 if (DEBUG_INSTALL) { 9994 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9995 } 9996 9997 if (bp == null || bp.packageSetting == null) { 9998 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9999 Slog.w(TAG, "Unknown permission " + name 10000 + " in package " + pkg.packageName); 10001 } 10002 continue; 10003 } 10004 10005 final String perm = bp.name; 10006 boolean allowedSig = false; 10007 int grant = GRANT_DENIED; 10008 10009 // Keep track of app op permissions. 10010 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10011 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10012 if (pkgs == null) { 10013 pkgs = new ArraySet<>(); 10014 mAppOpPermissionPackages.put(bp.name, pkgs); 10015 } 10016 pkgs.add(pkg.packageName); 10017 } 10018 10019 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10020 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10021 >= Build.VERSION_CODES.M; 10022 switch (level) { 10023 case PermissionInfo.PROTECTION_NORMAL: { 10024 // For all apps normal permissions are install time ones. 10025 grant = GRANT_INSTALL; 10026 } break; 10027 10028 case PermissionInfo.PROTECTION_DANGEROUS: { 10029 // If a permission review is required for legacy apps we represent 10030 // their permissions as always granted runtime ones since we need 10031 // to keep the review required permission flag per user while an 10032 // install permission's state is shared across all users. 10033 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10034 // For legacy apps dangerous permissions are install time ones. 10035 grant = GRANT_INSTALL; 10036 } else if (origPermissions.hasInstallPermission(bp.name)) { 10037 // For legacy apps that became modern, install becomes runtime. 10038 grant = GRANT_UPGRADE; 10039 } else if (mPromoteSystemApps 10040 && isSystemApp(ps) 10041 && mExistingSystemPackages.contains(ps.name)) { 10042 // For legacy system apps, install becomes runtime. 10043 // We cannot check hasInstallPermission() for system apps since those 10044 // permissions were granted implicitly and not persisted pre-M. 10045 grant = GRANT_UPGRADE; 10046 } else { 10047 // For modern apps keep runtime permissions unchanged. 10048 grant = GRANT_RUNTIME; 10049 } 10050 } break; 10051 10052 case PermissionInfo.PROTECTION_SIGNATURE: { 10053 // For all apps signature permissions are install time ones. 10054 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10055 if (allowedSig) { 10056 grant = GRANT_INSTALL; 10057 } 10058 } break; 10059 } 10060 10061 if (DEBUG_INSTALL) { 10062 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10063 } 10064 10065 if (grant != GRANT_DENIED) { 10066 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10067 // If this is an existing, non-system package, then 10068 // we can't add any new permissions to it. 10069 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10070 // Except... if this is a permission that was added 10071 // to the platform (note: need to only do this when 10072 // updating the platform). 10073 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10074 grant = GRANT_DENIED; 10075 } 10076 } 10077 } 10078 10079 switch (grant) { 10080 case GRANT_INSTALL: { 10081 // Revoke this as runtime permission to handle the case of 10082 // a runtime permission being downgraded to an install one. 10083 // Also in permission review mode we keep dangerous permissions 10084 // for legacy apps 10085 for (int userId : UserManagerService.getInstance().getUserIds()) { 10086 if (origPermissions.getRuntimePermissionState( 10087 bp.name, userId) != null) { 10088 // Revoke the runtime permission and clear the flags. 10089 origPermissions.revokeRuntimePermission(bp, userId); 10090 origPermissions.updatePermissionFlags(bp, userId, 10091 PackageManager.MASK_PERMISSION_FLAGS, 0); 10092 // If we revoked a permission permission, we have to write. 10093 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10094 changedRuntimePermissionUserIds, userId); 10095 } 10096 } 10097 // Grant an install permission. 10098 if (permissionsState.grantInstallPermission(bp) != 10099 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10100 changedInstallPermission = true; 10101 } 10102 } break; 10103 10104 case GRANT_RUNTIME: { 10105 // Grant previously granted runtime permissions. 10106 for (int userId : UserManagerService.getInstance().getUserIds()) { 10107 PermissionState permissionState = origPermissions 10108 .getRuntimePermissionState(bp.name, userId); 10109 int flags = permissionState != null 10110 ? permissionState.getFlags() : 0; 10111 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10112 if (permissionsState.grantRuntimePermission(bp, userId) == 10113 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10114 // If we cannot put the permission as it was, we have to write. 10115 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10116 changedRuntimePermissionUserIds, userId); 10117 } 10118 // If the app supports runtime permissions no need for a review. 10119 if (Build.PERMISSIONS_REVIEW_REQUIRED 10120 && appSupportsRuntimePermissions 10121 && (flags & PackageManager 10122 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10123 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10124 // Since we changed the flags, we have to write. 10125 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10126 changedRuntimePermissionUserIds, userId); 10127 } 10128 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10129 && !appSupportsRuntimePermissions) { 10130 // For legacy apps that need a permission review, every new 10131 // runtime permission is granted but it is pending a review. 10132 // We also need to review only platform defined runtime 10133 // permissions as these are the only ones the platform knows 10134 // how to disable the API to simulate revocation as legacy 10135 // apps don't expect to run with revoked permissions. 10136 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10137 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10138 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10139 // We changed the flags, hence have to write. 10140 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10141 changedRuntimePermissionUserIds, userId); 10142 } 10143 } 10144 if (permissionsState.grantRuntimePermission(bp, userId) 10145 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10146 // We changed the permission, hence have to write. 10147 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10148 changedRuntimePermissionUserIds, userId); 10149 } 10150 } 10151 // Propagate the permission flags. 10152 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10153 } 10154 } break; 10155 10156 case GRANT_UPGRADE: { 10157 // Grant runtime permissions for a previously held install permission. 10158 PermissionState permissionState = origPermissions 10159 .getInstallPermissionState(bp.name); 10160 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10161 10162 if (origPermissions.revokeInstallPermission(bp) 10163 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10164 // We will be transferring the permission flags, so clear them. 10165 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10166 PackageManager.MASK_PERMISSION_FLAGS, 0); 10167 changedInstallPermission = true; 10168 } 10169 10170 // If the permission is not to be promoted to runtime we ignore it and 10171 // also its other flags as they are not applicable to install permissions. 10172 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10173 for (int userId : currentUserIds) { 10174 if (permissionsState.grantRuntimePermission(bp, userId) != 10175 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10176 // Transfer the permission flags. 10177 permissionsState.updatePermissionFlags(bp, userId, 10178 flags, flags); 10179 // If we granted the permission, we have to write. 10180 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10181 changedRuntimePermissionUserIds, userId); 10182 } 10183 } 10184 } 10185 } break; 10186 10187 default: { 10188 if (packageOfInterest == null 10189 || packageOfInterest.equals(pkg.packageName)) { 10190 Slog.w(TAG, "Not granting permission " + perm 10191 + " to package " + pkg.packageName 10192 + " because it was previously installed without"); 10193 } 10194 } break; 10195 } 10196 } else { 10197 if (permissionsState.revokeInstallPermission(bp) != 10198 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10199 // Also drop the permission flags. 10200 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10201 PackageManager.MASK_PERMISSION_FLAGS, 0); 10202 changedInstallPermission = true; 10203 Slog.i(TAG, "Un-granting permission " + perm 10204 + " from package " + pkg.packageName 10205 + " (protectionLevel=" + bp.protectionLevel 10206 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10207 + ")"); 10208 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10209 // Don't print warning for app op permissions, since it is fine for them 10210 // not to be granted, there is a UI for the user to decide. 10211 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10212 Slog.w(TAG, "Not granting permission " + perm 10213 + " to package " + pkg.packageName 10214 + " (protectionLevel=" + bp.protectionLevel 10215 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10216 + ")"); 10217 } 10218 } 10219 } 10220 } 10221 10222 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10223 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10224 // This is the first that we have heard about this package, so the 10225 // permissions we have now selected are fixed until explicitly 10226 // changed. 10227 ps.installPermissionsFixed = true; 10228 } 10229 10230 // Persist the runtime permissions state for users with changes. If permissions 10231 // were revoked because no app in the shared user declares them we have to 10232 // write synchronously to avoid losing runtime permissions state. 10233 for (int userId : changedRuntimePermissionUserIds) { 10234 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10235 } 10236 10237 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10238 } 10239 10240 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10241 boolean allowed = false; 10242 final int NP = PackageParser.NEW_PERMISSIONS.length; 10243 for (int ip=0; ip<NP; ip++) { 10244 final PackageParser.NewPermissionInfo npi 10245 = PackageParser.NEW_PERMISSIONS[ip]; 10246 if (npi.name.equals(perm) 10247 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10248 allowed = true; 10249 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10250 + pkg.packageName); 10251 break; 10252 } 10253 } 10254 return allowed; 10255 } 10256 10257 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10258 BasePermission bp, PermissionsState origPermissions) { 10259 boolean allowed; 10260 allowed = (compareSignatures( 10261 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10262 == PackageManager.SIGNATURE_MATCH) 10263 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10264 == PackageManager.SIGNATURE_MATCH); 10265 if (!allowed && (bp.protectionLevel 10266 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10267 if (isSystemApp(pkg)) { 10268 // For updated system applications, a system permission 10269 // is granted only if it had been defined by the original application. 10270 if (pkg.isUpdatedSystemApp()) { 10271 final PackageSetting sysPs = mSettings 10272 .getDisabledSystemPkgLPr(pkg.packageName); 10273 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10274 // If the original was granted this permission, we take 10275 // that grant decision as read and propagate it to the 10276 // update. 10277 if (sysPs.isPrivileged()) { 10278 allowed = true; 10279 } 10280 } else { 10281 // The system apk may have been updated with an older 10282 // version of the one on the data partition, but which 10283 // granted a new system permission that it didn't have 10284 // before. In this case we do want to allow the app to 10285 // now get the new permission if the ancestral apk is 10286 // privileged to get it. 10287 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10288 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10289 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10290 allowed = true; 10291 break; 10292 } 10293 } 10294 } 10295 // Also if a privileged parent package on the system image or any of 10296 // its children requested a privileged permission, the updated child 10297 // packages can also get the permission. 10298 if (pkg.parentPackage != null) { 10299 final PackageSetting disabledSysParentPs = mSettings 10300 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10301 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10302 && disabledSysParentPs.isPrivileged()) { 10303 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10304 allowed = true; 10305 } else if (disabledSysParentPs.pkg.childPackages != null) { 10306 final int count = disabledSysParentPs.pkg.childPackages.size(); 10307 for (int i = 0; i < count; i++) { 10308 PackageParser.Package disabledSysChildPkg = 10309 disabledSysParentPs.pkg.childPackages.get(i); 10310 if (isPackageRequestingPermission(disabledSysChildPkg, 10311 perm)) { 10312 allowed = true; 10313 break; 10314 } 10315 } 10316 } 10317 } 10318 } 10319 } 10320 } else { 10321 allowed = isPrivilegedApp(pkg); 10322 } 10323 } 10324 } 10325 if (!allowed) { 10326 if (!allowed && (bp.protectionLevel 10327 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10328 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10329 // If this was a previously normal/dangerous permission that got moved 10330 // to a system permission as part of the runtime permission redesign, then 10331 // we still want to blindly grant it to old apps. 10332 allowed = true; 10333 } 10334 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10335 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10336 // If this permission is to be granted to the system installer and 10337 // this app is an installer, then it gets the permission. 10338 allowed = true; 10339 } 10340 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10341 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10342 // If this permission is to be granted to the system verifier and 10343 // this app is a verifier, then it gets the permission. 10344 allowed = true; 10345 } 10346 if (!allowed && (bp.protectionLevel 10347 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10348 && isSystemApp(pkg)) { 10349 // Any pre-installed system app is allowed to get this permission. 10350 allowed = true; 10351 } 10352 if (!allowed && (bp.protectionLevel 10353 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10354 // For development permissions, a development permission 10355 // is granted only if it was already granted. 10356 allowed = origPermissions.hasInstallPermission(perm); 10357 } 10358 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10359 && pkg.packageName.equals(mSetupWizardPackage)) { 10360 // If this permission is to be granted to the system setup wizard and 10361 // this app is a setup wizard, then it gets the permission. 10362 allowed = true; 10363 } 10364 } 10365 return allowed; 10366 } 10367 10368 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10369 final int permCount = pkg.requestedPermissions.size(); 10370 for (int j = 0; j < permCount; j++) { 10371 String requestedPermission = pkg.requestedPermissions.get(j); 10372 if (permission.equals(requestedPermission)) { 10373 return true; 10374 } 10375 } 10376 return false; 10377 } 10378 10379 final class ActivityIntentResolver 10380 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10381 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10382 boolean defaultOnly, int userId) { 10383 if (!sUserManager.exists(userId)) return null; 10384 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10385 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10386 } 10387 10388 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10389 int userId) { 10390 if (!sUserManager.exists(userId)) return null; 10391 mFlags = flags; 10392 return super.queryIntent(intent, resolvedType, 10393 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10394 } 10395 10396 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10397 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10398 if (!sUserManager.exists(userId)) return null; 10399 if (packageActivities == null) { 10400 return null; 10401 } 10402 mFlags = flags; 10403 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10404 final int N = packageActivities.size(); 10405 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10406 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10407 10408 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10409 for (int i = 0; i < N; ++i) { 10410 intentFilters = packageActivities.get(i).intents; 10411 if (intentFilters != null && intentFilters.size() > 0) { 10412 PackageParser.ActivityIntentInfo[] array = 10413 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10414 intentFilters.toArray(array); 10415 listCut.add(array); 10416 } 10417 } 10418 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10419 } 10420 10421 /** 10422 * Finds a privileged activity that matches the specified activity names. 10423 */ 10424 private PackageParser.Activity findMatchingActivity( 10425 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10426 for (PackageParser.Activity sysActivity : activityList) { 10427 if (sysActivity.info.name.equals(activityInfo.name)) { 10428 return sysActivity; 10429 } 10430 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10431 return sysActivity; 10432 } 10433 if (sysActivity.info.targetActivity != null) { 10434 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10435 return sysActivity; 10436 } 10437 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10438 return sysActivity; 10439 } 10440 } 10441 } 10442 return null; 10443 } 10444 10445 public class IterGenerator<E> { 10446 public Iterator<E> generate(ActivityIntentInfo info) { 10447 return null; 10448 } 10449 } 10450 10451 public class ActionIterGenerator extends IterGenerator<String> { 10452 @Override 10453 public Iterator<String> generate(ActivityIntentInfo info) { 10454 return info.actionsIterator(); 10455 } 10456 } 10457 10458 public class CategoriesIterGenerator extends IterGenerator<String> { 10459 @Override 10460 public Iterator<String> generate(ActivityIntentInfo info) { 10461 return info.categoriesIterator(); 10462 } 10463 } 10464 10465 public class SchemesIterGenerator extends IterGenerator<String> { 10466 @Override 10467 public Iterator<String> generate(ActivityIntentInfo info) { 10468 return info.schemesIterator(); 10469 } 10470 } 10471 10472 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10473 @Override 10474 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10475 return info.authoritiesIterator(); 10476 } 10477 } 10478 10479 /** 10480 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10481 * MODIFIED. Do not pass in a list that should not be changed. 10482 */ 10483 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10484 IterGenerator<T> generator, Iterator<T> searchIterator) { 10485 // loop through the set of actions; every one must be found in the intent filter 10486 while (searchIterator.hasNext()) { 10487 // we must have at least one filter in the list to consider a match 10488 if (intentList.size() == 0) { 10489 break; 10490 } 10491 10492 final T searchAction = searchIterator.next(); 10493 10494 // loop through the set of intent filters 10495 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10496 while (intentIter.hasNext()) { 10497 final ActivityIntentInfo intentInfo = intentIter.next(); 10498 boolean selectionFound = false; 10499 10500 // loop through the intent filter's selection criteria; at least one 10501 // of them must match the searched criteria 10502 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10503 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10504 final T intentSelection = intentSelectionIter.next(); 10505 if (intentSelection != null && intentSelection.equals(searchAction)) { 10506 selectionFound = true; 10507 break; 10508 } 10509 } 10510 10511 // the selection criteria wasn't found in this filter's set; this filter 10512 // is not a potential match 10513 if (!selectionFound) { 10514 intentIter.remove(); 10515 } 10516 } 10517 } 10518 } 10519 10520 private boolean isProtectedAction(ActivityIntentInfo filter) { 10521 final Iterator<String> actionsIter = filter.actionsIterator(); 10522 while (actionsIter != null && actionsIter.hasNext()) { 10523 final String filterAction = actionsIter.next(); 10524 if (PROTECTED_ACTIONS.contains(filterAction)) { 10525 return true; 10526 } 10527 } 10528 return false; 10529 } 10530 10531 /** 10532 * Adjusts the priority of the given intent filter according to policy. 10533 * <p> 10534 * <ul> 10535 * <li>The priority for non privileged applications is capped to '0'</li> 10536 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10537 * <li>The priority for unbundled updates to privileged applications is capped to the 10538 * priority defined on the system partition</li> 10539 * </ul> 10540 * <p> 10541 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10542 * allowed to obtain any priority on any action. 10543 */ 10544 private void adjustPriority( 10545 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10546 // nothing to do; priority is fine as-is 10547 if (intent.getPriority() <= 0) { 10548 return; 10549 } 10550 10551 final ActivityInfo activityInfo = intent.activity.info; 10552 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10553 10554 final boolean privilegedApp = 10555 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10556 if (!privilegedApp) { 10557 // non-privileged applications can never define a priority >0 10558 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10559 + " package: " + applicationInfo.packageName 10560 + " activity: " + intent.activity.className 10561 + " origPrio: " + intent.getPriority()); 10562 intent.setPriority(0); 10563 return; 10564 } 10565 10566 if (systemActivities == null) { 10567 // the system package is not disabled; we're parsing the system partition 10568 if (isProtectedAction(intent)) { 10569 if (mDeferProtectedFilters) { 10570 // We can't deal with these just yet. No component should ever obtain a 10571 // >0 priority for a protected actions, with ONE exception -- the setup 10572 // wizard. The setup wizard, however, cannot be known until we're able to 10573 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10574 // until all intent filters have been processed. Chicken, meet egg. 10575 // Let the filter temporarily have a high priority and rectify the 10576 // priorities after all system packages have been scanned. 10577 mProtectedFilters.add(intent); 10578 if (DEBUG_FILTERS) { 10579 Slog.i(TAG, "Protected action; save for later;" 10580 + " package: " + applicationInfo.packageName 10581 + " activity: " + intent.activity.className 10582 + " origPrio: " + intent.getPriority()); 10583 } 10584 return; 10585 } else { 10586 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10587 Slog.i(TAG, "No setup wizard;" 10588 + " All protected intents capped to priority 0"); 10589 } 10590 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10591 if (DEBUG_FILTERS) { 10592 Slog.i(TAG, "Found setup wizard;" 10593 + " allow priority " + intent.getPriority() + ";" 10594 + " package: " + intent.activity.info.packageName 10595 + " activity: " + intent.activity.className 10596 + " priority: " + intent.getPriority()); 10597 } 10598 // setup wizard gets whatever it wants 10599 return; 10600 } 10601 Slog.w(TAG, "Protected action; cap priority to 0;" 10602 + " package: " + intent.activity.info.packageName 10603 + " activity: " + intent.activity.className 10604 + " origPrio: " + intent.getPriority()); 10605 intent.setPriority(0); 10606 return; 10607 } 10608 } 10609 // privileged apps on the system image get whatever priority they request 10610 return; 10611 } 10612 10613 // privileged app unbundled update ... try to find the same activity 10614 final PackageParser.Activity foundActivity = 10615 findMatchingActivity(systemActivities, activityInfo); 10616 if (foundActivity == null) { 10617 // this is a new activity; it cannot obtain >0 priority 10618 if (DEBUG_FILTERS) { 10619 Slog.i(TAG, "New activity; cap priority to 0;" 10620 + " package: " + applicationInfo.packageName 10621 + " activity: " + intent.activity.className 10622 + " origPrio: " + intent.getPriority()); 10623 } 10624 intent.setPriority(0); 10625 return; 10626 } 10627 10628 // found activity, now check for filter equivalence 10629 10630 // a shallow copy is enough; we modify the list, not its contents 10631 final List<ActivityIntentInfo> intentListCopy = 10632 new ArrayList<>(foundActivity.intents); 10633 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10634 10635 // find matching action subsets 10636 final Iterator<String> actionsIterator = intent.actionsIterator(); 10637 if (actionsIterator != null) { 10638 getIntentListSubset( 10639 intentListCopy, new ActionIterGenerator(), actionsIterator); 10640 if (intentListCopy.size() == 0) { 10641 // no more intents to match; we're not equivalent 10642 if (DEBUG_FILTERS) { 10643 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10644 + " package: " + applicationInfo.packageName 10645 + " activity: " + intent.activity.className 10646 + " origPrio: " + intent.getPriority()); 10647 } 10648 intent.setPriority(0); 10649 return; 10650 } 10651 } 10652 10653 // find matching category subsets 10654 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10655 if (categoriesIterator != null) { 10656 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10657 categoriesIterator); 10658 if (intentListCopy.size() == 0) { 10659 // no more intents to match; we're not equivalent 10660 if (DEBUG_FILTERS) { 10661 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10662 + " package: " + applicationInfo.packageName 10663 + " activity: " + intent.activity.className 10664 + " origPrio: " + intent.getPriority()); 10665 } 10666 intent.setPriority(0); 10667 return; 10668 } 10669 } 10670 10671 // find matching schemes subsets 10672 final Iterator<String> schemesIterator = intent.schemesIterator(); 10673 if (schemesIterator != null) { 10674 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10675 schemesIterator); 10676 if (intentListCopy.size() == 0) { 10677 // no more intents to match; we're not equivalent 10678 if (DEBUG_FILTERS) { 10679 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10680 + " package: " + applicationInfo.packageName 10681 + " activity: " + intent.activity.className 10682 + " origPrio: " + intent.getPriority()); 10683 } 10684 intent.setPriority(0); 10685 return; 10686 } 10687 } 10688 10689 // find matching authorities subsets 10690 final Iterator<IntentFilter.AuthorityEntry> 10691 authoritiesIterator = intent.authoritiesIterator(); 10692 if (authoritiesIterator != null) { 10693 getIntentListSubset(intentListCopy, 10694 new AuthoritiesIterGenerator(), 10695 authoritiesIterator); 10696 if (intentListCopy.size() == 0) { 10697 // no more intents to match; we're not equivalent 10698 if (DEBUG_FILTERS) { 10699 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10700 + " package: " + applicationInfo.packageName 10701 + " activity: " + intent.activity.className 10702 + " origPrio: " + intent.getPriority()); 10703 } 10704 intent.setPriority(0); 10705 return; 10706 } 10707 } 10708 10709 // we found matching filter(s); app gets the max priority of all intents 10710 int cappedPriority = 0; 10711 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10712 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10713 } 10714 if (intent.getPriority() > cappedPriority) { 10715 if (DEBUG_FILTERS) { 10716 Slog.i(TAG, "Found matching filter(s);" 10717 + " cap priority to " + cappedPriority + ";" 10718 + " package: " + applicationInfo.packageName 10719 + " activity: " + intent.activity.className 10720 + " origPrio: " + intent.getPriority()); 10721 } 10722 intent.setPriority(cappedPriority); 10723 return; 10724 } 10725 // all this for nothing; the requested priority was <= what was on the system 10726 } 10727 10728 public final void addActivity(PackageParser.Activity a, String type) { 10729 mActivities.put(a.getComponentName(), a); 10730 if (DEBUG_SHOW_INFO) 10731 Log.v( 10732 TAG, " " + type + " " + 10733 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10734 if (DEBUG_SHOW_INFO) 10735 Log.v(TAG, " Class=" + a.info.name); 10736 final int NI = a.intents.size(); 10737 for (int j=0; j<NI; j++) { 10738 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10739 if ("activity".equals(type)) { 10740 final PackageSetting ps = 10741 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10742 final List<PackageParser.Activity> systemActivities = 10743 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10744 adjustPriority(systemActivities, intent); 10745 } 10746 if (DEBUG_SHOW_INFO) { 10747 Log.v(TAG, " IntentFilter:"); 10748 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10749 } 10750 if (!intent.debugCheck()) { 10751 Log.w(TAG, "==> For Activity " + a.info.name); 10752 } 10753 addFilter(intent); 10754 } 10755 } 10756 10757 public final void removeActivity(PackageParser.Activity a, String type) { 10758 mActivities.remove(a.getComponentName()); 10759 if (DEBUG_SHOW_INFO) { 10760 Log.v(TAG, " " + type + " " 10761 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10762 : a.info.name) + ":"); 10763 Log.v(TAG, " Class=" + a.info.name); 10764 } 10765 final int NI = a.intents.size(); 10766 for (int j=0; j<NI; j++) { 10767 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10768 if (DEBUG_SHOW_INFO) { 10769 Log.v(TAG, " IntentFilter:"); 10770 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10771 } 10772 removeFilter(intent); 10773 } 10774 } 10775 10776 @Override 10777 protected boolean allowFilterResult( 10778 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10779 ActivityInfo filterAi = filter.activity.info; 10780 for (int i=dest.size()-1; i>=0; i--) { 10781 ActivityInfo destAi = dest.get(i).activityInfo; 10782 if (destAi.name == filterAi.name 10783 && destAi.packageName == filterAi.packageName) { 10784 return false; 10785 } 10786 } 10787 return true; 10788 } 10789 10790 @Override 10791 protected ActivityIntentInfo[] newArray(int size) { 10792 return new ActivityIntentInfo[size]; 10793 } 10794 10795 @Override 10796 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10797 if (!sUserManager.exists(userId)) return true; 10798 PackageParser.Package p = filter.activity.owner; 10799 if (p != null) { 10800 PackageSetting ps = (PackageSetting)p.mExtras; 10801 if (ps != null) { 10802 // System apps are never considered stopped for purposes of 10803 // filtering, because there may be no way for the user to 10804 // actually re-launch them. 10805 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10806 && ps.getStopped(userId); 10807 } 10808 } 10809 return false; 10810 } 10811 10812 @Override 10813 protected boolean isPackageForFilter(String packageName, 10814 PackageParser.ActivityIntentInfo info) { 10815 return packageName.equals(info.activity.owner.packageName); 10816 } 10817 10818 @Override 10819 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10820 int match, int userId) { 10821 if (!sUserManager.exists(userId)) return null; 10822 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10823 return null; 10824 } 10825 final PackageParser.Activity activity = info.activity; 10826 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10827 if (ps == null) { 10828 return null; 10829 } 10830 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10831 ps.readUserState(userId), userId); 10832 if (ai == null) { 10833 return null; 10834 } 10835 final ResolveInfo res = new ResolveInfo(); 10836 res.activityInfo = ai; 10837 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10838 res.filter = info; 10839 } 10840 if (info != null) { 10841 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10842 } 10843 res.priority = info.getPriority(); 10844 res.preferredOrder = activity.owner.mPreferredOrder; 10845 //System.out.println("Result: " + res.activityInfo.className + 10846 // " = " + res.priority); 10847 res.match = match; 10848 res.isDefault = info.hasDefault; 10849 res.labelRes = info.labelRes; 10850 res.nonLocalizedLabel = info.nonLocalizedLabel; 10851 if (userNeedsBadging(userId)) { 10852 res.noResourceId = true; 10853 } else { 10854 res.icon = info.icon; 10855 } 10856 res.iconResourceId = info.icon; 10857 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10858 return res; 10859 } 10860 10861 @Override 10862 protected void sortResults(List<ResolveInfo> results) { 10863 Collections.sort(results, mResolvePrioritySorter); 10864 } 10865 10866 @Override 10867 protected void dumpFilter(PrintWriter out, String prefix, 10868 PackageParser.ActivityIntentInfo filter) { 10869 out.print(prefix); out.print( 10870 Integer.toHexString(System.identityHashCode(filter.activity))); 10871 out.print(' '); 10872 filter.activity.printComponentShortName(out); 10873 out.print(" filter "); 10874 out.println(Integer.toHexString(System.identityHashCode(filter))); 10875 } 10876 10877 @Override 10878 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10879 return filter.activity; 10880 } 10881 10882 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10883 PackageParser.Activity activity = (PackageParser.Activity)label; 10884 out.print(prefix); out.print( 10885 Integer.toHexString(System.identityHashCode(activity))); 10886 out.print(' '); 10887 activity.printComponentShortName(out); 10888 if (count > 1) { 10889 out.print(" ("); out.print(count); out.print(" filters)"); 10890 } 10891 out.println(); 10892 } 10893 10894 // Keys are String (activity class name), values are Activity. 10895 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10896 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10897 private int mFlags; 10898 } 10899 10900 private final class ServiceIntentResolver 10901 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10902 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10903 boolean defaultOnly, int userId) { 10904 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10905 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10906 } 10907 10908 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10909 int userId) { 10910 if (!sUserManager.exists(userId)) return null; 10911 mFlags = flags; 10912 return super.queryIntent(intent, resolvedType, 10913 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10914 } 10915 10916 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10917 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10918 if (!sUserManager.exists(userId)) return null; 10919 if (packageServices == null) { 10920 return null; 10921 } 10922 mFlags = flags; 10923 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10924 final int N = packageServices.size(); 10925 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10926 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10927 10928 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10929 for (int i = 0; i < N; ++i) { 10930 intentFilters = packageServices.get(i).intents; 10931 if (intentFilters != null && intentFilters.size() > 0) { 10932 PackageParser.ServiceIntentInfo[] array = 10933 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10934 intentFilters.toArray(array); 10935 listCut.add(array); 10936 } 10937 } 10938 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10939 } 10940 10941 public final void addService(PackageParser.Service s) { 10942 mServices.put(s.getComponentName(), s); 10943 if (DEBUG_SHOW_INFO) { 10944 Log.v(TAG, " " 10945 + (s.info.nonLocalizedLabel != null 10946 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10947 Log.v(TAG, " Class=" + s.info.name); 10948 } 10949 final int NI = s.intents.size(); 10950 int j; 10951 for (j=0; j<NI; j++) { 10952 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10953 if (DEBUG_SHOW_INFO) { 10954 Log.v(TAG, " IntentFilter:"); 10955 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10956 } 10957 if (!intent.debugCheck()) { 10958 Log.w(TAG, "==> For Service " + s.info.name); 10959 } 10960 addFilter(intent); 10961 } 10962 } 10963 10964 public final void removeService(PackageParser.Service s) { 10965 mServices.remove(s.getComponentName()); 10966 if (DEBUG_SHOW_INFO) { 10967 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10968 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10969 Log.v(TAG, " Class=" + s.info.name); 10970 } 10971 final int NI = s.intents.size(); 10972 int j; 10973 for (j=0; j<NI; j++) { 10974 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10975 if (DEBUG_SHOW_INFO) { 10976 Log.v(TAG, " IntentFilter:"); 10977 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10978 } 10979 removeFilter(intent); 10980 } 10981 } 10982 10983 @Override 10984 protected boolean allowFilterResult( 10985 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10986 ServiceInfo filterSi = filter.service.info; 10987 for (int i=dest.size()-1; i>=0; i--) { 10988 ServiceInfo destAi = dest.get(i).serviceInfo; 10989 if (destAi.name == filterSi.name 10990 && destAi.packageName == filterSi.packageName) { 10991 return false; 10992 } 10993 } 10994 return true; 10995 } 10996 10997 @Override 10998 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10999 return new PackageParser.ServiceIntentInfo[size]; 11000 } 11001 11002 @Override 11003 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11004 if (!sUserManager.exists(userId)) return true; 11005 PackageParser.Package p = filter.service.owner; 11006 if (p != null) { 11007 PackageSetting ps = (PackageSetting)p.mExtras; 11008 if (ps != null) { 11009 // System apps are never considered stopped for purposes of 11010 // filtering, because there may be no way for the user to 11011 // actually re-launch them. 11012 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11013 && ps.getStopped(userId); 11014 } 11015 } 11016 return false; 11017 } 11018 11019 @Override 11020 protected boolean isPackageForFilter(String packageName, 11021 PackageParser.ServiceIntentInfo info) { 11022 return packageName.equals(info.service.owner.packageName); 11023 } 11024 11025 @Override 11026 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11027 int match, int userId) { 11028 if (!sUserManager.exists(userId)) return null; 11029 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11030 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11031 return null; 11032 } 11033 final PackageParser.Service service = info.service; 11034 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11035 if (ps == null) { 11036 return null; 11037 } 11038 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11039 ps.readUserState(userId), userId); 11040 if (si == null) { 11041 return null; 11042 } 11043 final ResolveInfo res = new ResolveInfo(); 11044 res.serviceInfo = si; 11045 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11046 res.filter = filter; 11047 } 11048 res.priority = info.getPriority(); 11049 res.preferredOrder = service.owner.mPreferredOrder; 11050 res.match = match; 11051 res.isDefault = info.hasDefault; 11052 res.labelRes = info.labelRes; 11053 res.nonLocalizedLabel = info.nonLocalizedLabel; 11054 res.icon = info.icon; 11055 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11056 return res; 11057 } 11058 11059 @Override 11060 protected void sortResults(List<ResolveInfo> results) { 11061 Collections.sort(results, mResolvePrioritySorter); 11062 } 11063 11064 @Override 11065 protected void dumpFilter(PrintWriter out, String prefix, 11066 PackageParser.ServiceIntentInfo filter) { 11067 out.print(prefix); out.print( 11068 Integer.toHexString(System.identityHashCode(filter.service))); 11069 out.print(' '); 11070 filter.service.printComponentShortName(out); 11071 out.print(" filter "); 11072 out.println(Integer.toHexString(System.identityHashCode(filter))); 11073 } 11074 11075 @Override 11076 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11077 return filter.service; 11078 } 11079 11080 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11081 PackageParser.Service service = (PackageParser.Service)label; 11082 out.print(prefix); out.print( 11083 Integer.toHexString(System.identityHashCode(service))); 11084 out.print(' '); 11085 service.printComponentShortName(out); 11086 if (count > 1) { 11087 out.print(" ("); out.print(count); out.print(" filters)"); 11088 } 11089 out.println(); 11090 } 11091 11092// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11093// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11094// final List<ResolveInfo> retList = Lists.newArrayList(); 11095// while (i.hasNext()) { 11096// final ResolveInfo resolveInfo = (ResolveInfo) i; 11097// if (isEnabledLP(resolveInfo.serviceInfo)) { 11098// retList.add(resolveInfo); 11099// } 11100// } 11101// return retList; 11102// } 11103 11104 // Keys are String (activity class name), values are Activity. 11105 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11106 = new ArrayMap<ComponentName, PackageParser.Service>(); 11107 private int mFlags; 11108 }; 11109 11110 private final class ProviderIntentResolver 11111 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11112 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11113 boolean defaultOnly, int userId) { 11114 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11115 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11116 } 11117 11118 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11119 int userId) { 11120 if (!sUserManager.exists(userId)) 11121 return null; 11122 mFlags = flags; 11123 return super.queryIntent(intent, resolvedType, 11124 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11125 } 11126 11127 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11128 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11129 if (!sUserManager.exists(userId)) 11130 return null; 11131 if (packageProviders == null) { 11132 return null; 11133 } 11134 mFlags = flags; 11135 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11136 final int N = packageProviders.size(); 11137 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11138 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11139 11140 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11141 for (int i = 0; i < N; ++i) { 11142 intentFilters = packageProviders.get(i).intents; 11143 if (intentFilters != null && intentFilters.size() > 0) { 11144 PackageParser.ProviderIntentInfo[] array = 11145 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11146 intentFilters.toArray(array); 11147 listCut.add(array); 11148 } 11149 } 11150 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11151 } 11152 11153 public final void addProvider(PackageParser.Provider p) { 11154 if (mProviders.containsKey(p.getComponentName())) { 11155 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11156 return; 11157 } 11158 11159 mProviders.put(p.getComponentName(), p); 11160 if (DEBUG_SHOW_INFO) { 11161 Log.v(TAG, " " 11162 + (p.info.nonLocalizedLabel != null 11163 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11164 Log.v(TAG, " Class=" + p.info.name); 11165 } 11166 final int NI = p.intents.size(); 11167 int j; 11168 for (j = 0; j < NI; j++) { 11169 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11170 if (DEBUG_SHOW_INFO) { 11171 Log.v(TAG, " IntentFilter:"); 11172 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11173 } 11174 if (!intent.debugCheck()) { 11175 Log.w(TAG, "==> For Provider " + p.info.name); 11176 } 11177 addFilter(intent); 11178 } 11179 } 11180 11181 public final void removeProvider(PackageParser.Provider p) { 11182 mProviders.remove(p.getComponentName()); 11183 if (DEBUG_SHOW_INFO) { 11184 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11185 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11186 Log.v(TAG, " Class=" + p.info.name); 11187 } 11188 final int NI = p.intents.size(); 11189 int j; 11190 for (j = 0; j < NI; j++) { 11191 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11192 if (DEBUG_SHOW_INFO) { 11193 Log.v(TAG, " IntentFilter:"); 11194 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11195 } 11196 removeFilter(intent); 11197 } 11198 } 11199 11200 @Override 11201 protected boolean allowFilterResult( 11202 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11203 ProviderInfo filterPi = filter.provider.info; 11204 for (int i = dest.size() - 1; i >= 0; i--) { 11205 ProviderInfo destPi = dest.get(i).providerInfo; 11206 if (destPi.name == filterPi.name 11207 && destPi.packageName == filterPi.packageName) { 11208 return false; 11209 } 11210 } 11211 return true; 11212 } 11213 11214 @Override 11215 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11216 return new PackageParser.ProviderIntentInfo[size]; 11217 } 11218 11219 @Override 11220 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11221 if (!sUserManager.exists(userId)) 11222 return true; 11223 PackageParser.Package p = filter.provider.owner; 11224 if (p != null) { 11225 PackageSetting ps = (PackageSetting) p.mExtras; 11226 if (ps != null) { 11227 // System apps are never considered stopped for purposes of 11228 // filtering, because there may be no way for the user to 11229 // actually re-launch them. 11230 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11231 && ps.getStopped(userId); 11232 } 11233 } 11234 return false; 11235 } 11236 11237 @Override 11238 protected boolean isPackageForFilter(String packageName, 11239 PackageParser.ProviderIntentInfo info) { 11240 return packageName.equals(info.provider.owner.packageName); 11241 } 11242 11243 @Override 11244 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11245 int match, int userId) { 11246 if (!sUserManager.exists(userId)) 11247 return null; 11248 final PackageParser.ProviderIntentInfo info = filter; 11249 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11250 return null; 11251 } 11252 final PackageParser.Provider provider = info.provider; 11253 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11254 if (ps == null) { 11255 return null; 11256 } 11257 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11258 ps.readUserState(userId), userId); 11259 if (pi == null) { 11260 return null; 11261 } 11262 final ResolveInfo res = new ResolveInfo(); 11263 res.providerInfo = pi; 11264 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11265 res.filter = filter; 11266 } 11267 res.priority = info.getPriority(); 11268 res.preferredOrder = provider.owner.mPreferredOrder; 11269 res.match = match; 11270 res.isDefault = info.hasDefault; 11271 res.labelRes = info.labelRes; 11272 res.nonLocalizedLabel = info.nonLocalizedLabel; 11273 res.icon = info.icon; 11274 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11275 return res; 11276 } 11277 11278 @Override 11279 protected void sortResults(List<ResolveInfo> results) { 11280 Collections.sort(results, mResolvePrioritySorter); 11281 } 11282 11283 @Override 11284 protected void dumpFilter(PrintWriter out, String prefix, 11285 PackageParser.ProviderIntentInfo filter) { 11286 out.print(prefix); 11287 out.print( 11288 Integer.toHexString(System.identityHashCode(filter.provider))); 11289 out.print(' '); 11290 filter.provider.printComponentShortName(out); 11291 out.print(" filter "); 11292 out.println(Integer.toHexString(System.identityHashCode(filter))); 11293 } 11294 11295 @Override 11296 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11297 return filter.provider; 11298 } 11299 11300 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11301 PackageParser.Provider provider = (PackageParser.Provider)label; 11302 out.print(prefix); out.print( 11303 Integer.toHexString(System.identityHashCode(provider))); 11304 out.print(' '); 11305 provider.printComponentShortName(out); 11306 if (count > 1) { 11307 out.print(" ("); out.print(count); out.print(" filters)"); 11308 } 11309 out.println(); 11310 } 11311 11312 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11313 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11314 private int mFlags; 11315 } 11316 11317 private static final class EphemeralIntentResolver 11318 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11319 @Override 11320 protected EphemeralResolveIntentInfo[] newArray(int size) { 11321 return new EphemeralResolveIntentInfo[size]; 11322 } 11323 11324 @Override 11325 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11326 return true; 11327 } 11328 11329 @Override 11330 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11331 int userId) { 11332 if (!sUserManager.exists(userId)) { 11333 return null; 11334 } 11335 return info.getEphemeralResolveInfo(); 11336 } 11337 } 11338 11339 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11340 new Comparator<ResolveInfo>() { 11341 public int compare(ResolveInfo r1, ResolveInfo r2) { 11342 int v1 = r1.priority; 11343 int v2 = r2.priority; 11344 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11345 if (v1 != v2) { 11346 return (v1 > v2) ? -1 : 1; 11347 } 11348 v1 = r1.preferredOrder; 11349 v2 = r2.preferredOrder; 11350 if (v1 != v2) { 11351 return (v1 > v2) ? -1 : 1; 11352 } 11353 if (r1.isDefault != r2.isDefault) { 11354 return r1.isDefault ? -1 : 1; 11355 } 11356 v1 = r1.match; 11357 v2 = r2.match; 11358 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11359 if (v1 != v2) { 11360 return (v1 > v2) ? -1 : 1; 11361 } 11362 if (r1.system != r2.system) { 11363 return r1.system ? -1 : 1; 11364 } 11365 if (r1.activityInfo != null) { 11366 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11367 } 11368 if (r1.serviceInfo != null) { 11369 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11370 } 11371 if (r1.providerInfo != null) { 11372 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11373 } 11374 return 0; 11375 } 11376 }; 11377 11378 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11379 new Comparator<ProviderInfo>() { 11380 public int compare(ProviderInfo p1, ProviderInfo p2) { 11381 final int v1 = p1.initOrder; 11382 final int v2 = p2.initOrder; 11383 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11384 } 11385 }; 11386 11387 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11388 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11389 final int[] userIds) { 11390 mHandler.post(new Runnable() { 11391 @Override 11392 public void run() { 11393 try { 11394 final IActivityManager am = ActivityManagerNative.getDefault(); 11395 if (am == null) return; 11396 final int[] resolvedUserIds; 11397 if (userIds == null) { 11398 resolvedUserIds = am.getRunningUserIds(); 11399 } else { 11400 resolvedUserIds = userIds; 11401 } 11402 for (int id : resolvedUserIds) { 11403 final Intent intent = new Intent(action, 11404 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11405 if (extras != null) { 11406 intent.putExtras(extras); 11407 } 11408 if (targetPkg != null) { 11409 intent.setPackage(targetPkg); 11410 } 11411 // Modify the UID when posting to other users 11412 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11413 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11414 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11415 intent.putExtra(Intent.EXTRA_UID, uid); 11416 } 11417 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11418 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11419 if (DEBUG_BROADCASTS) { 11420 RuntimeException here = new RuntimeException("here"); 11421 here.fillInStackTrace(); 11422 Slog.d(TAG, "Sending to user " + id + ": " 11423 + intent.toShortString(false, true, false, false) 11424 + " " + intent.getExtras(), here); 11425 } 11426 am.broadcastIntent(null, intent, null, finishedReceiver, 11427 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11428 null, finishedReceiver != null, false, id); 11429 } 11430 } catch (RemoteException ex) { 11431 } 11432 } 11433 }); 11434 } 11435 11436 /** 11437 * Check if the external storage media is available. This is true if there 11438 * is a mounted external storage medium or if the external storage is 11439 * emulated. 11440 */ 11441 private boolean isExternalMediaAvailable() { 11442 return mMediaMounted || Environment.isExternalStorageEmulated(); 11443 } 11444 11445 @Override 11446 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11447 // writer 11448 synchronized (mPackages) { 11449 if (!isExternalMediaAvailable()) { 11450 // If the external storage is no longer mounted at this point, 11451 // the caller may not have been able to delete all of this 11452 // packages files and can not delete any more. Bail. 11453 return null; 11454 } 11455 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11456 if (lastPackage != null) { 11457 pkgs.remove(lastPackage); 11458 } 11459 if (pkgs.size() > 0) { 11460 return pkgs.get(0); 11461 } 11462 } 11463 return null; 11464 } 11465 11466 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11467 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11468 userId, andCode ? 1 : 0, packageName); 11469 if (mSystemReady) { 11470 msg.sendToTarget(); 11471 } else { 11472 if (mPostSystemReadyMessages == null) { 11473 mPostSystemReadyMessages = new ArrayList<>(); 11474 } 11475 mPostSystemReadyMessages.add(msg); 11476 } 11477 } 11478 11479 void startCleaningPackages() { 11480 // reader 11481 if (!isExternalMediaAvailable()) { 11482 return; 11483 } 11484 synchronized (mPackages) { 11485 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11486 return; 11487 } 11488 } 11489 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11490 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11491 IActivityManager am = ActivityManagerNative.getDefault(); 11492 if (am != null) { 11493 try { 11494 am.startService(null, intent, null, mContext.getOpPackageName(), 11495 UserHandle.USER_SYSTEM); 11496 } catch (RemoteException e) { 11497 } 11498 } 11499 } 11500 11501 @Override 11502 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11503 int installFlags, String installerPackageName, int userId) { 11504 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11505 11506 final int callingUid = Binder.getCallingUid(); 11507 enforceCrossUserPermission(callingUid, userId, 11508 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11509 11510 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11511 try { 11512 if (observer != null) { 11513 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11514 } 11515 } catch (RemoteException re) { 11516 } 11517 return; 11518 } 11519 11520 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11521 installFlags |= PackageManager.INSTALL_FROM_ADB; 11522 11523 } else { 11524 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11525 // about installerPackageName. 11526 11527 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11528 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11529 } 11530 11531 UserHandle user; 11532 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11533 user = UserHandle.ALL; 11534 } else { 11535 user = new UserHandle(userId); 11536 } 11537 11538 // Only system components can circumvent runtime permissions when installing. 11539 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11540 && mContext.checkCallingOrSelfPermission(Manifest.permission 11541 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11542 throw new SecurityException("You need the " 11543 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11544 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11545 } 11546 11547 final File originFile = new File(originPath); 11548 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11549 11550 final Message msg = mHandler.obtainMessage(INIT_COPY); 11551 final VerificationInfo verificationInfo = new VerificationInfo( 11552 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11553 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11554 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11555 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11556 null /*certificates*/); 11557 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11558 msg.obj = params; 11559 11560 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11561 System.identityHashCode(msg.obj)); 11562 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11563 System.identityHashCode(msg.obj)); 11564 11565 mHandler.sendMessage(msg); 11566 } 11567 11568 void installStage(String packageName, File stagedDir, String stagedCid, 11569 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11570 String installerPackageName, int installerUid, UserHandle user, 11571 Certificate[][] certificates) { 11572 if (DEBUG_EPHEMERAL) { 11573 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11574 Slog.d(TAG, "Ephemeral install of " + packageName); 11575 } 11576 } 11577 final VerificationInfo verificationInfo = new VerificationInfo( 11578 sessionParams.originatingUri, sessionParams.referrerUri, 11579 sessionParams.originatingUid, installerUid); 11580 11581 final OriginInfo origin; 11582 if (stagedDir != null) { 11583 origin = OriginInfo.fromStagedFile(stagedDir); 11584 } else { 11585 origin = OriginInfo.fromStagedContainer(stagedCid); 11586 } 11587 11588 final Message msg = mHandler.obtainMessage(INIT_COPY); 11589 final InstallParams params = new InstallParams(origin, null, observer, 11590 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11591 verificationInfo, user, sessionParams.abiOverride, 11592 sessionParams.grantedRuntimePermissions, certificates); 11593 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11594 msg.obj = params; 11595 11596 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11597 System.identityHashCode(msg.obj)); 11598 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11599 System.identityHashCode(msg.obj)); 11600 11601 mHandler.sendMessage(msg); 11602 } 11603 11604 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11605 int userId) { 11606 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11607 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11608 } 11609 11610 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11611 int appId, int userId) { 11612 Bundle extras = new Bundle(1); 11613 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11614 11615 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11616 packageName, extras, 0, null, null, new int[] {userId}); 11617 try { 11618 IActivityManager am = ActivityManagerNative.getDefault(); 11619 if (isSystem && am.isUserRunning(userId, 0)) { 11620 // The just-installed/enabled app is bundled on the system, so presumed 11621 // to be able to run automatically without needing an explicit launch. 11622 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11623 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11624 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11625 .setPackage(packageName); 11626 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11627 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11628 } 11629 } catch (RemoteException e) { 11630 // shouldn't happen 11631 Slog.w(TAG, "Unable to bootstrap installed package", e); 11632 } 11633 } 11634 11635 @Override 11636 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11637 int userId) { 11638 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11639 PackageSetting pkgSetting; 11640 final int uid = Binder.getCallingUid(); 11641 enforceCrossUserPermission(uid, userId, 11642 true /* requireFullPermission */, true /* checkShell */, 11643 "setApplicationHiddenSetting for user " + userId); 11644 11645 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11646 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11647 return false; 11648 } 11649 11650 long callingId = Binder.clearCallingIdentity(); 11651 try { 11652 boolean sendAdded = false; 11653 boolean sendRemoved = false; 11654 // writer 11655 synchronized (mPackages) { 11656 pkgSetting = mSettings.mPackages.get(packageName); 11657 if (pkgSetting == null) { 11658 return false; 11659 } 11660 if (pkgSetting.getHidden(userId) != hidden) { 11661 pkgSetting.setHidden(hidden, userId); 11662 mSettings.writePackageRestrictionsLPr(userId); 11663 if (hidden) { 11664 sendRemoved = true; 11665 } else { 11666 sendAdded = true; 11667 } 11668 } 11669 } 11670 if (sendAdded) { 11671 sendPackageAddedForUser(packageName, pkgSetting, userId); 11672 return true; 11673 } 11674 if (sendRemoved) { 11675 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11676 "hiding pkg"); 11677 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11678 return true; 11679 } 11680 } finally { 11681 Binder.restoreCallingIdentity(callingId); 11682 } 11683 return false; 11684 } 11685 11686 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11687 int userId) { 11688 final PackageRemovedInfo info = new PackageRemovedInfo(); 11689 info.removedPackage = packageName; 11690 info.removedUsers = new int[] {userId}; 11691 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11692 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11693 } 11694 11695 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11696 if (pkgList.length > 0) { 11697 Bundle extras = new Bundle(1); 11698 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11699 11700 sendPackageBroadcast( 11701 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11702 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11703 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11704 new int[] {userId}); 11705 } 11706 } 11707 11708 /** 11709 * Returns true if application is not found or there was an error. Otherwise it returns 11710 * the hidden state of the package for the given user. 11711 */ 11712 @Override 11713 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11714 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11715 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11716 true /* requireFullPermission */, false /* checkShell */, 11717 "getApplicationHidden for user " + userId); 11718 PackageSetting pkgSetting; 11719 long callingId = Binder.clearCallingIdentity(); 11720 try { 11721 // writer 11722 synchronized (mPackages) { 11723 pkgSetting = mSettings.mPackages.get(packageName); 11724 if (pkgSetting == null) { 11725 return true; 11726 } 11727 return pkgSetting.getHidden(userId); 11728 } 11729 } finally { 11730 Binder.restoreCallingIdentity(callingId); 11731 } 11732 } 11733 11734 /** 11735 * @hide 11736 */ 11737 @Override 11738 public int installExistingPackageAsUser(String packageName, int userId) { 11739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11740 null); 11741 PackageSetting pkgSetting; 11742 final int uid = Binder.getCallingUid(); 11743 enforceCrossUserPermission(uid, userId, 11744 true /* requireFullPermission */, true /* checkShell */, 11745 "installExistingPackage for user " + userId); 11746 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11747 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11748 } 11749 11750 long callingId = Binder.clearCallingIdentity(); 11751 try { 11752 boolean installed = false; 11753 11754 // writer 11755 synchronized (mPackages) { 11756 pkgSetting = mSettings.mPackages.get(packageName); 11757 if (pkgSetting == null) { 11758 return PackageManager.INSTALL_FAILED_INVALID_URI; 11759 } 11760 if (!pkgSetting.getInstalled(userId)) { 11761 pkgSetting.setInstalled(true, userId); 11762 pkgSetting.setHidden(false, userId); 11763 mSettings.writePackageRestrictionsLPr(userId); 11764 installed = true; 11765 } 11766 } 11767 11768 if (installed) { 11769 if (pkgSetting.pkg != null) { 11770 synchronized (mInstallLock) { 11771 // We don't need to freeze for a brand new install 11772 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11773 } 11774 } 11775 sendPackageAddedForUser(packageName, pkgSetting, userId); 11776 } 11777 } finally { 11778 Binder.restoreCallingIdentity(callingId); 11779 } 11780 11781 return PackageManager.INSTALL_SUCCEEDED; 11782 } 11783 11784 boolean isUserRestricted(int userId, String restrictionKey) { 11785 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11786 if (restrictions.getBoolean(restrictionKey, false)) { 11787 Log.w(TAG, "User is restricted: " + restrictionKey); 11788 return true; 11789 } 11790 return false; 11791 } 11792 11793 @Override 11794 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11795 int userId) { 11796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11797 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11798 true /* requireFullPermission */, true /* checkShell */, 11799 "setPackagesSuspended for user " + userId); 11800 11801 if (ArrayUtils.isEmpty(packageNames)) { 11802 return packageNames; 11803 } 11804 11805 // List of package names for whom the suspended state has changed. 11806 List<String> changedPackages = new ArrayList<>(packageNames.length); 11807 // List of package names for whom the suspended state is not set as requested in this 11808 // method. 11809 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11810 long callingId = Binder.clearCallingIdentity(); 11811 try { 11812 for (int i = 0; i < packageNames.length; i++) { 11813 String packageName = packageNames[i]; 11814 boolean changed = false; 11815 final int appId; 11816 synchronized (mPackages) { 11817 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11818 if (pkgSetting == null) { 11819 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11820 + "\". Skipping suspending/un-suspending."); 11821 unactionedPackages.add(packageName); 11822 continue; 11823 } 11824 appId = pkgSetting.appId; 11825 if (pkgSetting.getSuspended(userId) != suspended) { 11826 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11827 unactionedPackages.add(packageName); 11828 continue; 11829 } 11830 pkgSetting.setSuspended(suspended, userId); 11831 mSettings.writePackageRestrictionsLPr(userId); 11832 changed = true; 11833 changedPackages.add(packageName); 11834 } 11835 } 11836 11837 if (changed && suspended) { 11838 killApplication(packageName, UserHandle.getUid(userId, appId), 11839 "suspending package"); 11840 } 11841 } 11842 } finally { 11843 Binder.restoreCallingIdentity(callingId); 11844 } 11845 11846 if (!changedPackages.isEmpty()) { 11847 sendPackagesSuspendedForUser(changedPackages.toArray( 11848 new String[changedPackages.size()]), userId, suspended); 11849 } 11850 11851 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11852 } 11853 11854 @Override 11855 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11856 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11857 true /* requireFullPermission */, false /* checkShell */, 11858 "isPackageSuspendedForUser for user " + userId); 11859 synchronized (mPackages) { 11860 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11861 if (pkgSetting == null) { 11862 throw new IllegalArgumentException("Unknown target package: " + packageName); 11863 } 11864 return pkgSetting.getSuspended(userId); 11865 } 11866 } 11867 11868 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11869 if (isPackageDeviceAdmin(packageName, userId)) { 11870 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11871 + "\": has an active device admin"); 11872 return false; 11873 } 11874 11875 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11876 if (packageName.equals(activeLauncherPackageName)) { 11877 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11878 + "\": contains the active launcher"); 11879 return false; 11880 } 11881 11882 if (packageName.equals(mRequiredInstallerPackage)) { 11883 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11884 + "\": required for package installation"); 11885 return false; 11886 } 11887 11888 if (packageName.equals(mRequiredVerifierPackage)) { 11889 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11890 + "\": required for package verification"); 11891 return false; 11892 } 11893 11894 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11895 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11896 + "\": is the default dialer"); 11897 return false; 11898 } 11899 11900 return true; 11901 } 11902 11903 private String getActiveLauncherPackageName(int userId) { 11904 Intent intent = new Intent(Intent.ACTION_MAIN); 11905 intent.addCategory(Intent.CATEGORY_HOME); 11906 ResolveInfo resolveInfo = resolveIntent( 11907 intent, 11908 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11909 PackageManager.MATCH_DEFAULT_ONLY, 11910 userId); 11911 11912 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11913 } 11914 11915 private String getDefaultDialerPackageName(int userId) { 11916 synchronized (mPackages) { 11917 return mSettings.getDefaultDialerPackageNameLPw(userId); 11918 } 11919 } 11920 11921 @Override 11922 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11923 mContext.enforceCallingOrSelfPermission( 11924 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11925 "Only package verification agents can verify applications"); 11926 11927 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11928 final PackageVerificationResponse response = new PackageVerificationResponse( 11929 verificationCode, Binder.getCallingUid()); 11930 msg.arg1 = id; 11931 msg.obj = response; 11932 mHandler.sendMessage(msg); 11933 } 11934 11935 @Override 11936 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11937 long millisecondsToDelay) { 11938 mContext.enforceCallingOrSelfPermission( 11939 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11940 "Only package verification agents can extend verification timeouts"); 11941 11942 final PackageVerificationState state = mPendingVerification.get(id); 11943 final PackageVerificationResponse response = new PackageVerificationResponse( 11944 verificationCodeAtTimeout, Binder.getCallingUid()); 11945 11946 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11947 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11948 } 11949 if (millisecondsToDelay < 0) { 11950 millisecondsToDelay = 0; 11951 } 11952 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11953 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11954 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11955 } 11956 11957 if ((state != null) && !state.timeoutExtended()) { 11958 state.extendTimeout(); 11959 11960 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11961 msg.arg1 = id; 11962 msg.obj = response; 11963 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11964 } 11965 } 11966 11967 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11968 int verificationCode, UserHandle user) { 11969 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11970 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11971 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11972 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11973 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11974 11975 mContext.sendBroadcastAsUser(intent, user, 11976 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11977 } 11978 11979 private ComponentName matchComponentForVerifier(String packageName, 11980 List<ResolveInfo> receivers) { 11981 ActivityInfo targetReceiver = null; 11982 11983 final int NR = receivers.size(); 11984 for (int i = 0; i < NR; i++) { 11985 final ResolveInfo info = receivers.get(i); 11986 if (info.activityInfo == null) { 11987 continue; 11988 } 11989 11990 if (packageName.equals(info.activityInfo.packageName)) { 11991 targetReceiver = info.activityInfo; 11992 break; 11993 } 11994 } 11995 11996 if (targetReceiver == null) { 11997 return null; 11998 } 11999 12000 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12001 } 12002 12003 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12004 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12005 if (pkgInfo.verifiers.length == 0) { 12006 return null; 12007 } 12008 12009 final int N = pkgInfo.verifiers.length; 12010 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12011 for (int i = 0; i < N; i++) { 12012 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12013 12014 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12015 receivers); 12016 if (comp == null) { 12017 continue; 12018 } 12019 12020 final int verifierUid = getUidForVerifier(verifierInfo); 12021 if (verifierUid == -1) { 12022 continue; 12023 } 12024 12025 if (DEBUG_VERIFY) { 12026 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12027 + " with the correct signature"); 12028 } 12029 sufficientVerifiers.add(comp); 12030 verificationState.addSufficientVerifier(verifierUid); 12031 } 12032 12033 return sufficientVerifiers; 12034 } 12035 12036 private int getUidForVerifier(VerifierInfo verifierInfo) { 12037 synchronized (mPackages) { 12038 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12039 if (pkg == null) { 12040 return -1; 12041 } else if (pkg.mSignatures.length != 1) { 12042 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12043 + " has more than one signature; ignoring"); 12044 return -1; 12045 } 12046 12047 /* 12048 * If the public key of the package's signature does not match 12049 * our expected public key, then this is a different package and 12050 * we should skip. 12051 */ 12052 12053 final byte[] expectedPublicKey; 12054 try { 12055 final Signature verifierSig = pkg.mSignatures[0]; 12056 final PublicKey publicKey = verifierSig.getPublicKey(); 12057 expectedPublicKey = publicKey.getEncoded(); 12058 } catch (CertificateException e) { 12059 return -1; 12060 } 12061 12062 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12063 12064 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12065 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12066 + " does not have the expected public key; ignoring"); 12067 return -1; 12068 } 12069 12070 return pkg.applicationInfo.uid; 12071 } 12072 } 12073 12074 @Override 12075 public void finishPackageInstall(int token, boolean didLaunch) { 12076 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12077 12078 if (DEBUG_INSTALL) { 12079 Slog.v(TAG, "BM finishing package install for " + token); 12080 } 12081 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12082 12083 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12084 mHandler.sendMessage(msg); 12085 } 12086 12087 /** 12088 * Get the verification agent timeout. 12089 * 12090 * @return verification timeout in milliseconds 12091 */ 12092 private long getVerificationTimeout() { 12093 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12094 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12095 DEFAULT_VERIFICATION_TIMEOUT); 12096 } 12097 12098 /** 12099 * Get the default verification agent response code. 12100 * 12101 * @return default verification response code 12102 */ 12103 private int getDefaultVerificationResponse() { 12104 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12105 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12106 DEFAULT_VERIFICATION_RESPONSE); 12107 } 12108 12109 /** 12110 * Check whether or not package verification has been enabled. 12111 * 12112 * @return true if verification should be performed 12113 */ 12114 private boolean isVerificationEnabled(int userId, int installFlags) { 12115 if (!DEFAULT_VERIFY_ENABLE) { 12116 return false; 12117 } 12118 // Ephemeral apps don't get the full verification treatment 12119 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12120 if (DEBUG_EPHEMERAL) { 12121 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12122 } 12123 return false; 12124 } 12125 12126 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12127 12128 // Check if installing from ADB 12129 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12130 // Do not run verification in a test harness environment 12131 if (ActivityManager.isRunningInTestHarness()) { 12132 return false; 12133 } 12134 if (ensureVerifyAppsEnabled) { 12135 return true; 12136 } 12137 // Check if the developer does not want package verification for ADB installs 12138 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12139 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12140 return false; 12141 } 12142 } 12143 12144 if (ensureVerifyAppsEnabled) { 12145 return true; 12146 } 12147 12148 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12149 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12150 } 12151 12152 @Override 12153 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12154 throws RemoteException { 12155 mContext.enforceCallingOrSelfPermission( 12156 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12157 "Only intentfilter verification agents can verify applications"); 12158 12159 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12160 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12161 Binder.getCallingUid(), verificationCode, failedDomains); 12162 msg.arg1 = id; 12163 msg.obj = response; 12164 mHandler.sendMessage(msg); 12165 } 12166 12167 @Override 12168 public int getIntentVerificationStatus(String packageName, int userId) { 12169 synchronized (mPackages) { 12170 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12171 } 12172 } 12173 12174 @Override 12175 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12176 mContext.enforceCallingOrSelfPermission( 12177 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12178 12179 boolean result = false; 12180 synchronized (mPackages) { 12181 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12182 } 12183 if (result) { 12184 scheduleWritePackageRestrictionsLocked(userId); 12185 } 12186 return result; 12187 } 12188 12189 @Override 12190 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12191 String packageName) { 12192 synchronized (mPackages) { 12193 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12194 } 12195 } 12196 12197 @Override 12198 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12199 if (TextUtils.isEmpty(packageName)) { 12200 return ParceledListSlice.emptyList(); 12201 } 12202 synchronized (mPackages) { 12203 PackageParser.Package pkg = mPackages.get(packageName); 12204 if (pkg == null || pkg.activities == null) { 12205 return ParceledListSlice.emptyList(); 12206 } 12207 final int count = pkg.activities.size(); 12208 ArrayList<IntentFilter> result = new ArrayList<>(); 12209 for (int n=0; n<count; n++) { 12210 PackageParser.Activity activity = pkg.activities.get(n); 12211 if (activity.intents != null && activity.intents.size() > 0) { 12212 result.addAll(activity.intents); 12213 } 12214 } 12215 return new ParceledListSlice<>(result); 12216 } 12217 } 12218 12219 @Override 12220 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12221 mContext.enforceCallingOrSelfPermission( 12222 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12223 12224 synchronized (mPackages) { 12225 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12226 if (packageName != null) { 12227 result |= updateIntentVerificationStatus(packageName, 12228 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12229 userId); 12230 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12231 packageName, userId); 12232 } 12233 return result; 12234 } 12235 } 12236 12237 @Override 12238 public String getDefaultBrowserPackageName(int userId) { 12239 synchronized (mPackages) { 12240 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12241 } 12242 } 12243 12244 /** 12245 * Get the "allow unknown sources" setting. 12246 * 12247 * @return the current "allow unknown sources" setting 12248 */ 12249 private int getUnknownSourcesSettings() { 12250 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12251 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12252 -1); 12253 } 12254 12255 @Override 12256 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12257 final int uid = Binder.getCallingUid(); 12258 // writer 12259 synchronized (mPackages) { 12260 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12261 if (targetPackageSetting == null) { 12262 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12263 } 12264 12265 PackageSetting installerPackageSetting; 12266 if (installerPackageName != null) { 12267 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12268 if (installerPackageSetting == null) { 12269 throw new IllegalArgumentException("Unknown installer package: " 12270 + installerPackageName); 12271 } 12272 } else { 12273 installerPackageSetting = null; 12274 } 12275 12276 Signature[] callerSignature; 12277 Object obj = mSettings.getUserIdLPr(uid); 12278 if (obj != null) { 12279 if (obj instanceof SharedUserSetting) { 12280 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12281 } else if (obj instanceof PackageSetting) { 12282 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12283 } else { 12284 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12285 } 12286 } else { 12287 throw new SecurityException("Unknown calling UID: " + uid); 12288 } 12289 12290 // Verify: can't set installerPackageName to a package that is 12291 // not signed with the same cert as the caller. 12292 if (installerPackageSetting != null) { 12293 if (compareSignatures(callerSignature, 12294 installerPackageSetting.signatures.mSignatures) 12295 != PackageManager.SIGNATURE_MATCH) { 12296 throw new SecurityException( 12297 "Caller does not have same cert as new installer package " 12298 + installerPackageName); 12299 } 12300 } 12301 12302 // Verify: if target already has an installer package, it must 12303 // be signed with the same cert as the caller. 12304 if (targetPackageSetting.installerPackageName != null) { 12305 PackageSetting setting = mSettings.mPackages.get( 12306 targetPackageSetting.installerPackageName); 12307 // If the currently set package isn't valid, then it's always 12308 // okay to change it. 12309 if (setting != null) { 12310 if (compareSignatures(callerSignature, 12311 setting.signatures.mSignatures) 12312 != PackageManager.SIGNATURE_MATCH) { 12313 throw new SecurityException( 12314 "Caller does not have same cert as old installer package " 12315 + targetPackageSetting.installerPackageName); 12316 } 12317 } 12318 } 12319 12320 // Okay! 12321 targetPackageSetting.installerPackageName = installerPackageName; 12322 if (installerPackageName != null) { 12323 mSettings.mInstallerPackages.add(installerPackageName); 12324 } 12325 scheduleWriteSettingsLocked(); 12326 } 12327 } 12328 12329 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12330 // Queue up an async operation since the package installation may take a little while. 12331 mHandler.post(new Runnable() { 12332 public void run() { 12333 mHandler.removeCallbacks(this); 12334 // Result object to be returned 12335 PackageInstalledInfo res = new PackageInstalledInfo(); 12336 res.setReturnCode(currentStatus); 12337 res.uid = -1; 12338 res.pkg = null; 12339 res.removedInfo = null; 12340 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12341 args.doPreInstall(res.returnCode); 12342 synchronized (mInstallLock) { 12343 installPackageTracedLI(args, res); 12344 } 12345 args.doPostInstall(res.returnCode, res.uid); 12346 } 12347 12348 // A restore should be performed at this point if (a) the install 12349 // succeeded, (b) the operation is not an update, and (c) the new 12350 // package has not opted out of backup participation. 12351 final boolean update = res.removedInfo != null 12352 && res.removedInfo.removedPackage != null; 12353 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12354 boolean doRestore = !update 12355 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12356 12357 // Set up the post-install work request bookkeeping. This will be used 12358 // and cleaned up by the post-install event handling regardless of whether 12359 // there's a restore pass performed. Token values are >= 1. 12360 int token; 12361 if (mNextInstallToken < 0) mNextInstallToken = 1; 12362 token = mNextInstallToken++; 12363 12364 PostInstallData data = new PostInstallData(args, res); 12365 mRunningInstalls.put(token, data); 12366 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12367 12368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12369 // Pass responsibility to the Backup Manager. It will perform a 12370 // restore if appropriate, then pass responsibility back to the 12371 // Package Manager to run the post-install observer callbacks 12372 // and broadcasts. 12373 IBackupManager bm = IBackupManager.Stub.asInterface( 12374 ServiceManager.getService(Context.BACKUP_SERVICE)); 12375 if (bm != null) { 12376 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12377 + " to BM for possible restore"); 12378 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12379 try { 12380 // TODO: http://b/22388012 12381 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12382 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12383 } else { 12384 doRestore = false; 12385 } 12386 } catch (RemoteException e) { 12387 // can't happen; the backup manager is local 12388 } catch (Exception e) { 12389 Slog.e(TAG, "Exception trying to enqueue restore", e); 12390 doRestore = false; 12391 } 12392 } else { 12393 Slog.e(TAG, "Backup Manager not found!"); 12394 doRestore = false; 12395 } 12396 } 12397 12398 if (!doRestore) { 12399 // No restore possible, or the Backup Manager was mysteriously not 12400 // available -- just fire the post-install work request directly. 12401 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12402 12403 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12404 12405 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12406 mHandler.sendMessage(msg); 12407 } 12408 } 12409 }); 12410 } 12411 12412 /** 12413 * Callback from PackageSettings whenever an app is first transitioned out of the 12414 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12415 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12416 * here whether the app is the target of an ongoing install, and only send the 12417 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12418 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12419 * handling. 12420 */ 12421 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12422 // Serialize this with the rest of the install-process message chain. In the 12423 // restore-at-install case, this Runnable will necessarily run before the 12424 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12425 // are coherent. In the non-restore case, the app has already completed install 12426 // and been launched through some other means, so it is not in a problematic 12427 // state for observers to see the FIRST_LAUNCH signal. 12428 mHandler.post(new Runnable() { 12429 @Override 12430 public void run() { 12431 for (int i = 0; i < mRunningInstalls.size(); i++) { 12432 final PostInstallData data = mRunningInstalls.valueAt(i); 12433 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12434 // right package; but is it for the right user? 12435 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12436 if (userId == data.res.newUsers[uIndex]) { 12437 if (DEBUG_BACKUP) { 12438 Slog.i(TAG, "Package " + pkgName 12439 + " being restored so deferring FIRST_LAUNCH"); 12440 } 12441 return; 12442 } 12443 } 12444 } 12445 } 12446 // didn't find it, so not being restored 12447 if (DEBUG_BACKUP) { 12448 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12449 } 12450 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12451 } 12452 }); 12453 } 12454 12455 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12456 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12457 installerPkg, null, userIds); 12458 } 12459 12460 private abstract class HandlerParams { 12461 private static final int MAX_RETRIES = 4; 12462 12463 /** 12464 * Number of times startCopy() has been attempted and had a non-fatal 12465 * error. 12466 */ 12467 private int mRetries = 0; 12468 12469 /** User handle for the user requesting the information or installation. */ 12470 private final UserHandle mUser; 12471 String traceMethod; 12472 int traceCookie; 12473 12474 HandlerParams(UserHandle user) { 12475 mUser = user; 12476 } 12477 12478 UserHandle getUser() { 12479 return mUser; 12480 } 12481 12482 HandlerParams setTraceMethod(String traceMethod) { 12483 this.traceMethod = traceMethod; 12484 return this; 12485 } 12486 12487 HandlerParams setTraceCookie(int traceCookie) { 12488 this.traceCookie = traceCookie; 12489 return this; 12490 } 12491 12492 final boolean startCopy() { 12493 boolean res; 12494 try { 12495 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12496 12497 if (++mRetries > MAX_RETRIES) { 12498 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12499 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12500 handleServiceError(); 12501 return false; 12502 } else { 12503 handleStartCopy(); 12504 res = true; 12505 } 12506 } catch (RemoteException e) { 12507 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12508 mHandler.sendEmptyMessage(MCS_RECONNECT); 12509 res = false; 12510 } 12511 handleReturnCode(); 12512 return res; 12513 } 12514 12515 final void serviceError() { 12516 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12517 handleServiceError(); 12518 handleReturnCode(); 12519 } 12520 12521 abstract void handleStartCopy() throws RemoteException; 12522 abstract void handleServiceError(); 12523 abstract void handleReturnCode(); 12524 } 12525 12526 class MeasureParams extends HandlerParams { 12527 private final PackageStats mStats; 12528 private boolean mSuccess; 12529 12530 private final IPackageStatsObserver mObserver; 12531 12532 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12533 super(new UserHandle(stats.userHandle)); 12534 mObserver = observer; 12535 mStats = stats; 12536 } 12537 12538 @Override 12539 public String toString() { 12540 return "MeasureParams{" 12541 + Integer.toHexString(System.identityHashCode(this)) 12542 + " " + mStats.packageName + "}"; 12543 } 12544 12545 @Override 12546 void handleStartCopy() throws RemoteException { 12547 synchronized (mInstallLock) { 12548 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12549 } 12550 12551 if (mSuccess) { 12552 boolean mounted = false; 12553 try { 12554 final String status = Environment.getExternalStorageState(); 12555 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12556 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12557 } catch (Exception e) { 12558 } 12559 12560 if (mounted) { 12561 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12562 12563 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12564 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12565 12566 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12567 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12568 12569 // Always subtract cache size, since it's a subdirectory 12570 mStats.externalDataSize -= mStats.externalCacheSize; 12571 12572 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12573 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12574 12575 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12576 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12577 } 12578 } 12579 } 12580 12581 @Override 12582 void handleReturnCode() { 12583 if (mObserver != null) { 12584 try { 12585 mObserver.onGetStatsCompleted(mStats, mSuccess); 12586 } catch (RemoteException e) { 12587 Slog.i(TAG, "Observer no longer exists."); 12588 } 12589 } 12590 } 12591 12592 @Override 12593 void handleServiceError() { 12594 Slog.e(TAG, "Could not measure application " + mStats.packageName 12595 + " external storage"); 12596 } 12597 } 12598 12599 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12600 throws RemoteException { 12601 long result = 0; 12602 for (File path : paths) { 12603 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12604 } 12605 return result; 12606 } 12607 12608 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12609 for (File path : paths) { 12610 try { 12611 mcs.clearDirectory(path.getAbsolutePath()); 12612 } catch (RemoteException e) { 12613 } 12614 } 12615 } 12616 12617 static class OriginInfo { 12618 /** 12619 * Location where install is coming from, before it has been 12620 * copied/renamed into place. This could be a single monolithic APK 12621 * file, or a cluster directory. This location may be untrusted. 12622 */ 12623 final File file; 12624 final String cid; 12625 12626 /** 12627 * Flag indicating that {@link #file} or {@link #cid} has already been 12628 * staged, meaning downstream users don't need to defensively copy the 12629 * contents. 12630 */ 12631 final boolean staged; 12632 12633 /** 12634 * Flag indicating that {@link #file} or {@link #cid} is an already 12635 * installed app that is being moved. 12636 */ 12637 final boolean existing; 12638 12639 final String resolvedPath; 12640 final File resolvedFile; 12641 12642 static OriginInfo fromNothing() { 12643 return new OriginInfo(null, null, false, false); 12644 } 12645 12646 static OriginInfo fromUntrustedFile(File file) { 12647 return new OriginInfo(file, null, false, false); 12648 } 12649 12650 static OriginInfo fromExistingFile(File file) { 12651 return new OriginInfo(file, null, false, true); 12652 } 12653 12654 static OriginInfo fromStagedFile(File file) { 12655 return new OriginInfo(file, null, true, false); 12656 } 12657 12658 static OriginInfo fromStagedContainer(String cid) { 12659 return new OriginInfo(null, cid, true, false); 12660 } 12661 12662 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12663 this.file = file; 12664 this.cid = cid; 12665 this.staged = staged; 12666 this.existing = existing; 12667 12668 if (cid != null) { 12669 resolvedPath = PackageHelper.getSdDir(cid); 12670 resolvedFile = new File(resolvedPath); 12671 } else if (file != null) { 12672 resolvedPath = file.getAbsolutePath(); 12673 resolvedFile = file; 12674 } else { 12675 resolvedPath = null; 12676 resolvedFile = null; 12677 } 12678 } 12679 } 12680 12681 static class MoveInfo { 12682 final int moveId; 12683 final String fromUuid; 12684 final String toUuid; 12685 final String packageName; 12686 final String dataAppName; 12687 final int appId; 12688 final String seinfo; 12689 final int targetSdkVersion; 12690 12691 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12692 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12693 this.moveId = moveId; 12694 this.fromUuid = fromUuid; 12695 this.toUuid = toUuid; 12696 this.packageName = packageName; 12697 this.dataAppName = dataAppName; 12698 this.appId = appId; 12699 this.seinfo = seinfo; 12700 this.targetSdkVersion = targetSdkVersion; 12701 } 12702 } 12703 12704 static class VerificationInfo { 12705 /** A constant used to indicate that a uid value is not present. */ 12706 public static final int NO_UID = -1; 12707 12708 /** URI referencing where the package was downloaded from. */ 12709 final Uri originatingUri; 12710 12711 /** HTTP referrer URI associated with the originatingURI. */ 12712 final Uri referrer; 12713 12714 /** UID of the application that the install request originated from. */ 12715 final int originatingUid; 12716 12717 /** UID of application requesting the install */ 12718 final int installerUid; 12719 12720 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12721 this.originatingUri = originatingUri; 12722 this.referrer = referrer; 12723 this.originatingUid = originatingUid; 12724 this.installerUid = installerUid; 12725 } 12726 } 12727 12728 class InstallParams extends HandlerParams { 12729 final OriginInfo origin; 12730 final MoveInfo move; 12731 final IPackageInstallObserver2 observer; 12732 int installFlags; 12733 final String installerPackageName; 12734 final String volumeUuid; 12735 private InstallArgs mArgs; 12736 private int mRet; 12737 final String packageAbiOverride; 12738 final String[] grantedRuntimePermissions; 12739 final VerificationInfo verificationInfo; 12740 final Certificate[][] certificates; 12741 12742 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12743 int installFlags, String installerPackageName, String volumeUuid, 12744 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12745 String[] grantedPermissions, Certificate[][] certificates) { 12746 super(user); 12747 this.origin = origin; 12748 this.move = move; 12749 this.observer = observer; 12750 this.installFlags = installFlags; 12751 this.installerPackageName = installerPackageName; 12752 this.volumeUuid = volumeUuid; 12753 this.verificationInfo = verificationInfo; 12754 this.packageAbiOverride = packageAbiOverride; 12755 this.grantedRuntimePermissions = grantedPermissions; 12756 this.certificates = certificates; 12757 } 12758 12759 @Override 12760 public String toString() { 12761 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12762 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12763 } 12764 12765 private int installLocationPolicy(PackageInfoLite pkgLite) { 12766 String packageName = pkgLite.packageName; 12767 int installLocation = pkgLite.installLocation; 12768 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12769 // reader 12770 synchronized (mPackages) { 12771 // Currently installed package which the new package is attempting to replace or 12772 // null if no such package is installed. 12773 PackageParser.Package installedPkg = mPackages.get(packageName); 12774 // Package which currently owns the data which the new package will own if installed. 12775 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12776 // will be null whereas dataOwnerPkg will contain information about the package 12777 // which was uninstalled while keeping its data. 12778 PackageParser.Package dataOwnerPkg = installedPkg; 12779 if (dataOwnerPkg == null) { 12780 PackageSetting ps = mSettings.mPackages.get(packageName); 12781 if (ps != null) { 12782 dataOwnerPkg = ps.pkg; 12783 } 12784 } 12785 12786 if (dataOwnerPkg != null) { 12787 // If installed, the package will get access to data left on the device by its 12788 // predecessor. As a security measure, this is permited only if this is not a 12789 // version downgrade or if the predecessor package is marked as debuggable and 12790 // a downgrade is explicitly requested. 12791 // 12792 // On debuggable platform builds, downgrades are permitted even for 12793 // non-debuggable packages to make testing easier. Debuggable platform builds do 12794 // not offer security guarantees and thus it's OK to disable some security 12795 // mechanisms to make debugging/testing easier on those builds. However, even on 12796 // debuggable builds downgrades of packages are permitted only if requested via 12797 // installFlags. This is because we aim to keep the behavior of debuggable 12798 // platform builds as close as possible to the behavior of non-debuggable 12799 // platform builds. 12800 final boolean downgradeRequested = 12801 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12802 final boolean packageDebuggable = 12803 (dataOwnerPkg.applicationInfo.flags 12804 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12805 final boolean downgradePermitted = 12806 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12807 if (!downgradePermitted) { 12808 try { 12809 checkDowngrade(dataOwnerPkg, pkgLite); 12810 } catch (PackageManagerException e) { 12811 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12812 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12813 } 12814 } 12815 } 12816 12817 if (installedPkg != null) { 12818 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12819 // Check for updated system application. 12820 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12821 if (onSd) { 12822 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12823 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12824 } 12825 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12826 } else { 12827 if (onSd) { 12828 // Install flag overrides everything. 12829 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12830 } 12831 // If current upgrade specifies particular preference 12832 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12833 // Application explicitly specified internal. 12834 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12835 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12836 // App explictly prefers external. Let policy decide 12837 } else { 12838 // Prefer previous location 12839 if (isExternal(installedPkg)) { 12840 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12841 } 12842 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12843 } 12844 } 12845 } else { 12846 // Invalid install. Return error code 12847 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12848 } 12849 } 12850 } 12851 // All the special cases have been taken care of. 12852 // Return result based on recommended install location. 12853 if (onSd) { 12854 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12855 } 12856 return pkgLite.recommendedInstallLocation; 12857 } 12858 12859 /* 12860 * Invoke remote method to get package information and install 12861 * location values. Override install location based on default 12862 * policy if needed and then create install arguments based 12863 * on the install location. 12864 */ 12865 public void handleStartCopy() throws RemoteException { 12866 int ret = PackageManager.INSTALL_SUCCEEDED; 12867 12868 // If we're already staged, we've firmly committed to an install location 12869 if (origin.staged) { 12870 if (origin.file != null) { 12871 installFlags |= PackageManager.INSTALL_INTERNAL; 12872 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12873 } else if (origin.cid != null) { 12874 installFlags |= PackageManager.INSTALL_EXTERNAL; 12875 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12876 } else { 12877 throw new IllegalStateException("Invalid stage location"); 12878 } 12879 } 12880 12881 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12882 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12883 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12884 PackageInfoLite pkgLite = null; 12885 12886 if (onInt && onSd) { 12887 // Check if both bits are set. 12888 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12889 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12890 } else if (onSd && ephemeral) { 12891 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12892 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12893 } else { 12894 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12895 packageAbiOverride); 12896 12897 if (DEBUG_EPHEMERAL && ephemeral) { 12898 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12899 } 12900 12901 /* 12902 * If we have too little free space, try to free cache 12903 * before giving up. 12904 */ 12905 if (!origin.staged && pkgLite.recommendedInstallLocation 12906 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12907 // TODO: focus freeing disk space on the target device 12908 final StorageManager storage = StorageManager.from(mContext); 12909 final long lowThreshold = storage.getStorageLowBytes( 12910 Environment.getDataDirectory()); 12911 12912 final long sizeBytes = mContainerService.calculateInstalledSize( 12913 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12914 12915 try { 12916 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12917 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12918 installFlags, packageAbiOverride); 12919 } catch (InstallerException e) { 12920 Slog.w(TAG, "Failed to free cache", e); 12921 } 12922 12923 /* 12924 * The cache free must have deleted the file we 12925 * downloaded to install. 12926 * 12927 * TODO: fix the "freeCache" call to not delete 12928 * the file we care about. 12929 */ 12930 if (pkgLite.recommendedInstallLocation 12931 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12932 pkgLite.recommendedInstallLocation 12933 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12934 } 12935 } 12936 } 12937 12938 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12939 int loc = pkgLite.recommendedInstallLocation; 12940 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12941 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12942 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12943 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12944 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12945 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12946 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12947 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12948 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12949 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12950 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12951 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12952 } else { 12953 // Override with defaults if needed. 12954 loc = installLocationPolicy(pkgLite); 12955 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12956 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12957 } else if (!onSd && !onInt) { 12958 // Override install location with flags 12959 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12960 // Set the flag to install on external media. 12961 installFlags |= PackageManager.INSTALL_EXTERNAL; 12962 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12963 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12964 if (DEBUG_EPHEMERAL) { 12965 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12966 } 12967 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12968 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12969 |PackageManager.INSTALL_INTERNAL); 12970 } else { 12971 // Make sure the flag for installing on external 12972 // media is unset 12973 installFlags |= PackageManager.INSTALL_INTERNAL; 12974 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12975 } 12976 } 12977 } 12978 } 12979 12980 final InstallArgs args = createInstallArgs(this); 12981 mArgs = args; 12982 12983 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12984 // TODO: http://b/22976637 12985 // Apps installed for "all" users use the device owner to verify the app 12986 UserHandle verifierUser = getUser(); 12987 if (verifierUser == UserHandle.ALL) { 12988 verifierUser = UserHandle.SYSTEM; 12989 } 12990 12991 /* 12992 * Determine if we have any installed package verifiers. If we 12993 * do, then we'll defer to them to verify the packages. 12994 */ 12995 final int requiredUid = mRequiredVerifierPackage == null ? -1 12996 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12997 verifierUser.getIdentifier()); 12998 if (!origin.existing && requiredUid != -1 12999 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13000 final Intent verification = new Intent( 13001 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13002 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13003 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13004 PACKAGE_MIME_TYPE); 13005 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13006 13007 // Query all live verifiers based on current user state 13008 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13009 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13010 13011 if (DEBUG_VERIFY) { 13012 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13013 + verification.toString() + " with " + pkgLite.verifiers.length 13014 + " optional verifiers"); 13015 } 13016 13017 final int verificationId = mPendingVerificationToken++; 13018 13019 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13020 13021 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13022 installerPackageName); 13023 13024 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13025 installFlags); 13026 13027 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13028 pkgLite.packageName); 13029 13030 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13031 pkgLite.versionCode); 13032 13033 if (verificationInfo != null) { 13034 if (verificationInfo.originatingUri != null) { 13035 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13036 verificationInfo.originatingUri); 13037 } 13038 if (verificationInfo.referrer != null) { 13039 verification.putExtra(Intent.EXTRA_REFERRER, 13040 verificationInfo.referrer); 13041 } 13042 if (verificationInfo.originatingUid >= 0) { 13043 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13044 verificationInfo.originatingUid); 13045 } 13046 if (verificationInfo.installerUid >= 0) { 13047 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13048 verificationInfo.installerUid); 13049 } 13050 } 13051 13052 final PackageVerificationState verificationState = new PackageVerificationState( 13053 requiredUid, args); 13054 13055 mPendingVerification.append(verificationId, verificationState); 13056 13057 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13058 receivers, verificationState); 13059 13060 /* 13061 * If any sufficient verifiers were listed in the package 13062 * manifest, attempt to ask them. 13063 */ 13064 if (sufficientVerifiers != null) { 13065 final int N = sufficientVerifiers.size(); 13066 if (N == 0) { 13067 Slog.i(TAG, "Additional verifiers required, but none installed."); 13068 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13069 } else { 13070 for (int i = 0; i < N; i++) { 13071 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13072 13073 final Intent sufficientIntent = new Intent(verification); 13074 sufficientIntent.setComponent(verifierComponent); 13075 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13076 } 13077 } 13078 } 13079 13080 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13081 mRequiredVerifierPackage, receivers); 13082 if (ret == PackageManager.INSTALL_SUCCEEDED 13083 && mRequiredVerifierPackage != null) { 13084 Trace.asyncTraceBegin( 13085 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13086 /* 13087 * Send the intent to the required verification agent, 13088 * but only start the verification timeout after the 13089 * target BroadcastReceivers have run. 13090 */ 13091 verification.setComponent(requiredVerifierComponent); 13092 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13093 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13094 new BroadcastReceiver() { 13095 @Override 13096 public void onReceive(Context context, Intent intent) { 13097 final Message msg = mHandler 13098 .obtainMessage(CHECK_PENDING_VERIFICATION); 13099 msg.arg1 = verificationId; 13100 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13101 } 13102 }, null, 0, null, null); 13103 13104 /* 13105 * We don't want the copy to proceed until verification 13106 * succeeds, so null out this field. 13107 */ 13108 mArgs = null; 13109 } 13110 } else { 13111 /* 13112 * No package verification is enabled, so immediately start 13113 * the remote call to initiate copy using temporary file. 13114 */ 13115 ret = args.copyApk(mContainerService, true); 13116 } 13117 } 13118 13119 mRet = ret; 13120 } 13121 13122 @Override 13123 void handleReturnCode() { 13124 // If mArgs is null, then MCS couldn't be reached. When it 13125 // reconnects, it will try again to install. At that point, this 13126 // will succeed. 13127 if (mArgs != null) { 13128 processPendingInstall(mArgs, mRet); 13129 } 13130 } 13131 13132 @Override 13133 void handleServiceError() { 13134 mArgs = createInstallArgs(this); 13135 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13136 } 13137 13138 public boolean isForwardLocked() { 13139 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13140 } 13141 } 13142 13143 /** 13144 * Used during creation of InstallArgs 13145 * 13146 * @param installFlags package installation flags 13147 * @return true if should be installed on external storage 13148 */ 13149 private static boolean installOnExternalAsec(int installFlags) { 13150 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13151 return false; 13152 } 13153 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13154 return true; 13155 } 13156 return false; 13157 } 13158 13159 /** 13160 * Used during creation of InstallArgs 13161 * 13162 * @param installFlags package installation flags 13163 * @return true if should be installed as forward locked 13164 */ 13165 private static boolean installForwardLocked(int installFlags) { 13166 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13167 } 13168 13169 private InstallArgs createInstallArgs(InstallParams params) { 13170 if (params.move != null) { 13171 return new MoveInstallArgs(params); 13172 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13173 return new AsecInstallArgs(params); 13174 } else { 13175 return new FileInstallArgs(params); 13176 } 13177 } 13178 13179 /** 13180 * Create args that describe an existing installed package. Typically used 13181 * when cleaning up old installs, or used as a move source. 13182 */ 13183 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13184 String resourcePath, String[] instructionSets) { 13185 final boolean isInAsec; 13186 if (installOnExternalAsec(installFlags)) { 13187 /* Apps on SD card are always in ASEC containers. */ 13188 isInAsec = true; 13189 } else if (installForwardLocked(installFlags) 13190 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13191 /* 13192 * Forward-locked apps are only in ASEC containers if they're the 13193 * new style 13194 */ 13195 isInAsec = true; 13196 } else { 13197 isInAsec = false; 13198 } 13199 13200 if (isInAsec) { 13201 return new AsecInstallArgs(codePath, instructionSets, 13202 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13203 } else { 13204 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13205 } 13206 } 13207 13208 static abstract class InstallArgs { 13209 /** @see InstallParams#origin */ 13210 final OriginInfo origin; 13211 /** @see InstallParams#move */ 13212 final MoveInfo move; 13213 13214 final IPackageInstallObserver2 observer; 13215 // Always refers to PackageManager flags only 13216 final int installFlags; 13217 final String installerPackageName; 13218 final String volumeUuid; 13219 final UserHandle user; 13220 final String abiOverride; 13221 final String[] installGrantPermissions; 13222 /** If non-null, drop an async trace when the install completes */ 13223 final String traceMethod; 13224 final int traceCookie; 13225 final Certificate[][] certificates; 13226 13227 // The list of instruction sets supported by this app. This is currently 13228 // only used during the rmdex() phase to clean up resources. We can get rid of this 13229 // if we move dex files under the common app path. 13230 /* nullable */ String[] instructionSets; 13231 13232 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13233 int installFlags, String installerPackageName, String volumeUuid, 13234 UserHandle user, String[] instructionSets, 13235 String abiOverride, String[] installGrantPermissions, 13236 String traceMethod, int traceCookie, Certificate[][] certificates) { 13237 this.origin = origin; 13238 this.move = move; 13239 this.installFlags = installFlags; 13240 this.observer = observer; 13241 this.installerPackageName = installerPackageName; 13242 this.volumeUuid = volumeUuid; 13243 this.user = user; 13244 this.instructionSets = instructionSets; 13245 this.abiOverride = abiOverride; 13246 this.installGrantPermissions = installGrantPermissions; 13247 this.traceMethod = traceMethod; 13248 this.traceCookie = traceCookie; 13249 this.certificates = certificates; 13250 } 13251 13252 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13253 abstract int doPreInstall(int status); 13254 13255 /** 13256 * Rename package into final resting place. All paths on the given 13257 * scanned package should be updated to reflect the rename. 13258 */ 13259 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13260 abstract int doPostInstall(int status, int uid); 13261 13262 /** @see PackageSettingBase#codePathString */ 13263 abstract String getCodePath(); 13264 /** @see PackageSettingBase#resourcePathString */ 13265 abstract String getResourcePath(); 13266 13267 // Need installer lock especially for dex file removal. 13268 abstract void cleanUpResourcesLI(); 13269 abstract boolean doPostDeleteLI(boolean delete); 13270 13271 /** 13272 * Called before the source arguments are copied. This is used mostly 13273 * for MoveParams when it needs to read the source file to put it in the 13274 * destination. 13275 */ 13276 int doPreCopy() { 13277 return PackageManager.INSTALL_SUCCEEDED; 13278 } 13279 13280 /** 13281 * Called after the source arguments are copied. This is used mostly for 13282 * MoveParams when it needs to read the source file to put it in the 13283 * destination. 13284 */ 13285 int doPostCopy(int uid) { 13286 return PackageManager.INSTALL_SUCCEEDED; 13287 } 13288 13289 protected boolean isFwdLocked() { 13290 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13291 } 13292 13293 protected boolean isExternalAsec() { 13294 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13295 } 13296 13297 protected boolean isEphemeral() { 13298 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13299 } 13300 13301 UserHandle getUser() { 13302 return user; 13303 } 13304 } 13305 13306 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13307 if (!allCodePaths.isEmpty()) { 13308 if (instructionSets == null) { 13309 throw new IllegalStateException("instructionSet == null"); 13310 } 13311 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13312 for (String codePath : allCodePaths) { 13313 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13314 try { 13315 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13316 } catch (InstallerException ignored) { 13317 } 13318 } 13319 } 13320 } 13321 } 13322 13323 /** 13324 * Logic to handle installation of non-ASEC applications, including copying 13325 * and renaming logic. 13326 */ 13327 class FileInstallArgs extends InstallArgs { 13328 private File codeFile; 13329 private File resourceFile; 13330 13331 // Example topology: 13332 // /data/app/com.example/base.apk 13333 // /data/app/com.example/split_foo.apk 13334 // /data/app/com.example/lib/arm/libfoo.so 13335 // /data/app/com.example/lib/arm64/libfoo.so 13336 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13337 13338 /** New install */ 13339 FileInstallArgs(InstallParams params) { 13340 super(params.origin, params.move, params.observer, params.installFlags, 13341 params.installerPackageName, params.volumeUuid, 13342 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13343 params.grantedRuntimePermissions, 13344 params.traceMethod, params.traceCookie, params.certificates); 13345 if (isFwdLocked()) { 13346 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13347 } 13348 } 13349 13350 /** Existing install */ 13351 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13352 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13353 null, null, null, 0, null /*certificates*/); 13354 this.codeFile = (codePath != null) ? new File(codePath) : null; 13355 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13356 } 13357 13358 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13360 try { 13361 return doCopyApk(imcs, temp); 13362 } finally { 13363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13364 } 13365 } 13366 13367 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13368 if (origin.staged) { 13369 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13370 codeFile = origin.file; 13371 resourceFile = origin.file; 13372 return PackageManager.INSTALL_SUCCEEDED; 13373 } 13374 13375 try { 13376 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13377 final File tempDir = 13378 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13379 codeFile = tempDir; 13380 resourceFile = tempDir; 13381 } catch (IOException e) { 13382 Slog.w(TAG, "Failed to create copy file: " + e); 13383 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13384 } 13385 13386 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13387 @Override 13388 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13389 if (!FileUtils.isValidExtFilename(name)) { 13390 throw new IllegalArgumentException("Invalid filename: " + name); 13391 } 13392 try { 13393 final File file = new File(codeFile, name); 13394 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13395 O_RDWR | O_CREAT, 0644); 13396 Os.chmod(file.getAbsolutePath(), 0644); 13397 return new ParcelFileDescriptor(fd); 13398 } catch (ErrnoException e) { 13399 throw new RemoteException("Failed to open: " + e.getMessage()); 13400 } 13401 } 13402 }; 13403 13404 int ret = PackageManager.INSTALL_SUCCEEDED; 13405 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13406 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13407 Slog.e(TAG, "Failed to copy package"); 13408 return ret; 13409 } 13410 13411 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13412 NativeLibraryHelper.Handle handle = null; 13413 try { 13414 handle = NativeLibraryHelper.Handle.create(codeFile); 13415 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13416 abiOverride); 13417 } catch (IOException e) { 13418 Slog.e(TAG, "Copying native libraries failed", e); 13419 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13420 } finally { 13421 IoUtils.closeQuietly(handle); 13422 } 13423 13424 return ret; 13425 } 13426 13427 int doPreInstall(int status) { 13428 if (status != PackageManager.INSTALL_SUCCEEDED) { 13429 cleanUp(); 13430 } 13431 return status; 13432 } 13433 13434 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13435 if (status != PackageManager.INSTALL_SUCCEEDED) { 13436 cleanUp(); 13437 return false; 13438 } 13439 13440 final File targetDir = codeFile.getParentFile(); 13441 final File beforeCodeFile = codeFile; 13442 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13443 13444 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13445 try { 13446 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13447 } catch (ErrnoException e) { 13448 Slog.w(TAG, "Failed to rename", e); 13449 return false; 13450 } 13451 13452 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13453 Slog.w(TAG, "Failed to restorecon"); 13454 return false; 13455 } 13456 13457 // Reflect the rename internally 13458 codeFile = afterCodeFile; 13459 resourceFile = afterCodeFile; 13460 13461 // Reflect the rename in scanned details 13462 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13463 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13464 afterCodeFile, pkg.baseCodePath)); 13465 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13466 afterCodeFile, pkg.splitCodePaths)); 13467 13468 // Reflect the rename in app info 13469 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13470 pkg.setApplicationInfoCodePath(pkg.codePath); 13471 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13472 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13473 pkg.setApplicationInfoResourcePath(pkg.codePath); 13474 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13475 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13476 13477 return true; 13478 } 13479 13480 int doPostInstall(int status, int uid) { 13481 if (status != PackageManager.INSTALL_SUCCEEDED) { 13482 cleanUp(); 13483 } 13484 return status; 13485 } 13486 13487 @Override 13488 String getCodePath() { 13489 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13490 } 13491 13492 @Override 13493 String getResourcePath() { 13494 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13495 } 13496 13497 private boolean cleanUp() { 13498 if (codeFile == null || !codeFile.exists()) { 13499 return false; 13500 } 13501 13502 removeCodePathLI(codeFile); 13503 13504 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13505 resourceFile.delete(); 13506 } 13507 13508 return true; 13509 } 13510 13511 void cleanUpResourcesLI() { 13512 // Try enumerating all code paths before deleting 13513 List<String> allCodePaths = Collections.EMPTY_LIST; 13514 if (codeFile != null && codeFile.exists()) { 13515 try { 13516 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13517 allCodePaths = pkg.getAllCodePaths(); 13518 } catch (PackageParserException e) { 13519 // Ignored; we tried our best 13520 } 13521 } 13522 13523 cleanUp(); 13524 removeDexFiles(allCodePaths, instructionSets); 13525 } 13526 13527 boolean doPostDeleteLI(boolean delete) { 13528 // XXX err, shouldn't we respect the delete flag? 13529 cleanUpResourcesLI(); 13530 return true; 13531 } 13532 } 13533 13534 private boolean isAsecExternal(String cid) { 13535 final String asecPath = PackageHelper.getSdFilesystem(cid); 13536 return !asecPath.startsWith(mAsecInternalPath); 13537 } 13538 13539 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13540 PackageManagerException { 13541 if (copyRet < 0) { 13542 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13543 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13544 throw new PackageManagerException(copyRet, message); 13545 } 13546 } 13547 } 13548 13549 /** 13550 * Extract the MountService "container ID" from the full code path of an 13551 * .apk. 13552 */ 13553 static String cidFromCodePath(String fullCodePath) { 13554 int eidx = fullCodePath.lastIndexOf("/"); 13555 String subStr1 = fullCodePath.substring(0, eidx); 13556 int sidx = subStr1.lastIndexOf("/"); 13557 return subStr1.substring(sidx+1, eidx); 13558 } 13559 13560 /** 13561 * Logic to handle installation of ASEC applications, including copying and 13562 * renaming logic. 13563 */ 13564 class AsecInstallArgs extends InstallArgs { 13565 static final String RES_FILE_NAME = "pkg.apk"; 13566 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13567 13568 String cid; 13569 String packagePath; 13570 String resourcePath; 13571 13572 /** New install */ 13573 AsecInstallArgs(InstallParams params) { 13574 super(params.origin, params.move, params.observer, params.installFlags, 13575 params.installerPackageName, params.volumeUuid, 13576 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13577 params.grantedRuntimePermissions, 13578 params.traceMethod, params.traceCookie, params.certificates); 13579 } 13580 13581 /** Existing install */ 13582 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13583 boolean isExternal, boolean isForwardLocked) { 13584 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13585 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13586 instructionSets, null, null, null, 0, null /*certificates*/); 13587 // Hackily pretend we're still looking at a full code path 13588 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13589 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13590 } 13591 13592 // Extract cid from fullCodePath 13593 int eidx = fullCodePath.lastIndexOf("/"); 13594 String subStr1 = fullCodePath.substring(0, eidx); 13595 int sidx = subStr1.lastIndexOf("/"); 13596 cid = subStr1.substring(sidx+1, eidx); 13597 setMountPath(subStr1); 13598 } 13599 13600 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13601 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13602 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13603 instructionSets, null, null, null, 0, null /*certificates*/); 13604 this.cid = cid; 13605 setMountPath(PackageHelper.getSdDir(cid)); 13606 } 13607 13608 void createCopyFile() { 13609 cid = mInstallerService.allocateExternalStageCidLegacy(); 13610 } 13611 13612 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13613 if (origin.staged && origin.cid != null) { 13614 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13615 cid = origin.cid; 13616 setMountPath(PackageHelper.getSdDir(cid)); 13617 return PackageManager.INSTALL_SUCCEEDED; 13618 } 13619 13620 if (temp) { 13621 createCopyFile(); 13622 } else { 13623 /* 13624 * Pre-emptively destroy the container since it's destroyed if 13625 * copying fails due to it existing anyway. 13626 */ 13627 PackageHelper.destroySdDir(cid); 13628 } 13629 13630 final String newMountPath = imcs.copyPackageToContainer( 13631 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13632 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13633 13634 if (newMountPath != null) { 13635 setMountPath(newMountPath); 13636 return PackageManager.INSTALL_SUCCEEDED; 13637 } else { 13638 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13639 } 13640 } 13641 13642 @Override 13643 String getCodePath() { 13644 return packagePath; 13645 } 13646 13647 @Override 13648 String getResourcePath() { 13649 return resourcePath; 13650 } 13651 13652 int doPreInstall(int status) { 13653 if (status != PackageManager.INSTALL_SUCCEEDED) { 13654 // Destroy container 13655 PackageHelper.destroySdDir(cid); 13656 } else { 13657 boolean mounted = PackageHelper.isContainerMounted(cid); 13658 if (!mounted) { 13659 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13660 Process.SYSTEM_UID); 13661 if (newMountPath != null) { 13662 setMountPath(newMountPath); 13663 } else { 13664 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13665 } 13666 } 13667 } 13668 return status; 13669 } 13670 13671 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13672 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13673 String newMountPath = null; 13674 if (PackageHelper.isContainerMounted(cid)) { 13675 // Unmount the container 13676 if (!PackageHelper.unMountSdDir(cid)) { 13677 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13678 return false; 13679 } 13680 } 13681 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13682 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13683 " which might be stale. Will try to clean up."); 13684 // Clean up the stale container and proceed to recreate. 13685 if (!PackageHelper.destroySdDir(newCacheId)) { 13686 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13687 return false; 13688 } 13689 // Successfully cleaned up stale container. Try to rename again. 13690 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13691 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13692 + " inspite of cleaning it up."); 13693 return false; 13694 } 13695 } 13696 if (!PackageHelper.isContainerMounted(newCacheId)) { 13697 Slog.w(TAG, "Mounting container " + newCacheId); 13698 newMountPath = PackageHelper.mountSdDir(newCacheId, 13699 getEncryptKey(), Process.SYSTEM_UID); 13700 } else { 13701 newMountPath = PackageHelper.getSdDir(newCacheId); 13702 } 13703 if (newMountPath == null) { 13704 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13705 return false; 13706 } 13707 Log.i(TAG, "Succesfully renamed " + cid + 13708 " to " + newCacheId + 13709 " at new path: " + newMountPath); 13710 cid = newCacheId; 13711 13712 final File beforeCodeFile = new File(packagePath); 13713 setMountPath(newMountPath); 13714 final File afterCodeFile = new File(packagePath); 13715 13716 // Reflect the rename in scanned details 13717 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13718 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13719 afterCodeFile, pkg.baseCodePath)); 13720 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13721 afterCodeFile, pkg.splitCodePaths)); 13722 13723 // Reflect the rename in app info 13724 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13725 pkg.setApplicationInfoCodePath(pkg.codePath); 13726 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13727 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13728 pkg.setApplicationInfoResourcePath(pkg.codePath); 13729 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13730 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13731 13732 return true; 13733 } 13734 13735 private void setMountPath(String mountPath) { 13736 final File mountFile = new File(mountPath); 13737 13738 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13739 if (monolithicFile.exists()) { 13740 packagePath = monolithicFile.getAbsolutePath(); 13741 if (isFwdLocked()) { 13742 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13743 } else { 13744 resourcePath = packagePath; 13745 } 13746 } else { 13747 packagePath = mountFile.getAbsolutePath(); 13748 resourcePath = packagePath; 13749 } 13750 } 13751 13752 int doPostInstall(int status, int uid) { 13753 if (status != PackageManager.INSTALL_SUCCEEDED) { 13754 cleanUp(); 13755 } else { 13756 final int groupOwner; 13757 final String protectedFile; 13758 if (isFwdLocked()) { 13759 groupOwner = UserHandle.getSharedAppGid(uid); 13760 protectedFile = RES_FILE_NAME; 13761 } else { 13762 groupOwner = -1; 13763 protectedFile = null; 13764 } 13765 13766 if (uid < Process.FIRST_APPLICATION_UID 13767 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13768 Slog.e(TAG, "Failed to finalize " + cid); 13769 PackageHelper.destroySdDir(cid); 13770 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13771 } 13772 13773 boolean mounted = PackageHelper.isContainerMounted(cid); 13774 if (!mounted) { 13775 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13776 } 13777 } 13778 return status; 13779 } 13780 13781 private void cleanUp() { 13782 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13783 13784 // Destroy secure container 13785 PackageHelper.destroySdDir(cid); 13786 } 13787 13788 private List<String> getAllCodePaths() { 13789 final File codeFile = new File(getCodePath()); 13790 if (codeFile != null && codeFile.exists()) { 13791 try { 13792 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13793 return pkg.getAllCodePaths(); 13794 } catch (PackageParserException e) { 13795 // Ignored; we tried our best 13796 } 13797 } 13798 return Collections.EMPTY_LIST; 13799 } 13800 13801 void cleanUpResourcesLI() { 13802 // Enumerate all code paths before deleting 13803 cleanUpResourcesLI(getAllCodePaths()); 13804 } 13805 13806 private void cleanUpResourcesLI(List<String> allCodePaths) { 13807 cleanUp(); 13808 removeDexFiles(allCodePaths, instructionSets); 13809 } 13810 13811 String getPackageName() { 13812 return getAsecPackageName(cid); 13813 } 13814 13815 boolean doPostDeleteLI(boolean delete) { 13816 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13817 final List<String> allCodePaths = getAllCodePaths(); 13818 boolean mounted = PackageHelper.isContainerMounted(cid); 13819 if (mounted) { 13820 // Unmount first 13821 if (PackageHelper.unMountSdDir(cid)) { 13822 mounted = false; 13823 } 13824 } 13825 if (!mounted && delete) { 13826 cleanUpResourcesLI(allCodePaths); 13827 } 13828 return !mounted; 13829 } 13830 13831 @Override 13832 int doPreCopy() { 13833 if (isFwdLocked()) { 13834 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13835 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13836 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13837 } 13838 } 13839 13840 return PackageManager.INSTALL_SUCCEEDED; 13841 } 13842 13843 @Override 13844 int doPostCopy(int uid) { 13845 if (isFwdLocked()) { 13846 if (uid < Process.FIRST_APPLICATION_UID 13847 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13848 RES_FILE_NAME)) { 13849 Slog.e(TAG, "Failed to finalize " + cid); 13850 PackageHelper.destroySdDir(cid); 13851 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13852 } 13853 } 13854 13855 return PackageManager.INSTALL_SUCCEEDED; 13856 } 13857 } 13858 13859 /** 13860 * Logic to handle movement of existing installed applications. 13861 */ 13862 class MoveInstallArgs extends InstallArgs { 13863 private File codeFile; 13864 private File resourceFile; 13865 13866 /** New install */ 13867 MoveInstallArgs(InstallParams params) { 13868 super(params.origin, params.move, params.observer, params.installFlags, 13869 params.installerPackageName, params.volumeUuid, 13870 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13871 params.grantedRuntimePermissions, 13872 params.traceMethod, params.traceCookie, params.certificates); 13873 } 13874 13875 int copyApk(IMediaContainerService imcs, boolean temp) { 13876 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13877 + move.fromUuid + " to " + move.toUuid); 13878 synchronized (mInstaller) { 13879 try { 13880 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13881 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13882 } catch (InstallerException e) { 13883 Slog.w(TAG, "Failed to move app", e); 13884 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13885 } 13886 } 13887 13888 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13889 resourceFile = codeFile; 13890 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13891 13892 return PackageManager.INSTALL_SUCCEEDED; 13893 } 13894 13895 int doPreInstall(int status) { 13896 if (status != PackageManager.INSTALL_SUCCEEDED) { 13897 cleanUp(move.toUuid); 13898 } 13899 return status; 13900 } 13901 13902 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13903 if (status != PackageManager.INSTALL_SUCCEEDED) { 13904 cleanUp(move.toUuid); 13905 return false; 13906 } 13907 13908 // Reflect the move in app info 13909 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13910 pkg.setApplicationInfoCodePath(pkg.codePath); 13911 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13912 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13913 pkg.setApplicationInfoResourcePath(pkg.codePath); 13914 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13915 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13916 13917 return true; 13918 } 13919 13920 int doPostInstall(int status, int uid) { 13921 if (status == PackageManager.INSTALL_SUCCEEDED) { 13922 cleanUp(move.fromUuid); 13923 } else { 13924 cleanUp(move.toUuid); 13925 } 13926 return status; 13927 } 13928 13929 @Override 13930 String getCodePath() { 13931 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13932 } 13933 13934 @Override 13935 String getResourcePath() { 13936 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13937 } 13938 13939 private boolean cleanUp(String volumeUuid) { 13940 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13941 move.dataAppName); 13942 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13943 final int[] userIds = sUserManager.getUserIds(); 13944 synchronized (mInstallLock) { 13945 // Clean up both app data and code 13946 // All package moves are frozen until finished 13947 for (int userId : userIds) { 13948 try { 13949 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13950 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13951 } catch (InstallerException e) { 13952 Slog.w(TAG, String.valueOf(e)); 13953 } 13954 } 13955 removeCodePathLI(codeFile); 13956 } 13957 return true; 13958 } 13959 13960 void cleanUpResourcesLI() { 13961 throw new UnsupportedOperationException(); 13962 } 13963 13964 boolean doPostDeleteLI(boolean delete) { 13965 throw new UnsupportedOperationException(); 13966 } 13967 } 13968 13969 static String getAsecPackageName(String packageCid) { 13970 int idx = packageCid.lastIndexOf("-"); 13971 if (idx == -1) { 13972 return packageCid; 13973 } 13974 return packageCid.substring(0, idx); 13975 } 13976 13977 // Utility method used to create code paths based on package name and available index. 13978 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13979 String idxStr = ""; 13980 int idx = 1; 13981 // Fall back to default value of idx=1 if prefix is not 13982 // part of oldCodePath 13983 if (oldCodePath != null) { 13984 String subStr = oldCodePath; 13985 // Drop the suffix right away 13986 if (suffix != null && subStr.endsWith(suffix)) { 13987 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13988 } 13989 // If oldCodePath already contains prefix find out the 13990 // ending index to either increment or decrement. 13991 int sidx = subStr.lastIndexOf(prefix); 13992 if (sidx != -1) { 13993 subStr = subStr.substring(sidx + prefix.length()); 13994 if (subStr != null) { 13995 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13996 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13997 } 13998 try { 13999 idx = Integer.parseInt(subStr); 14000 if (idx <= 1) { 14001 idx++; 14002 } else { 14003 idx--; 14004 } 14005 } catch(NumberFormatException e) { 14006 } 14007 } 14008 } 14009 } 14010 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14011 return prefix + idxStr; 14012 } 14013 14014 private File getNextCodePath(File targetDir, String packageName) { 14015 int suffix = 1; 14016 File result; 14017 do { 14018 result = new File(targetDir, packageName + "-" + suffix); 14019 suffix++; 14020 } while (result.exists()); 14021 return result; 14022 } 14023 14024 // Utility method that returns the relative package path with respect 14025 // to the installation directory. Like say for /data/data/com.test-1.apk 14026 // string com.test-1 is returned. 14027 static String deriveCodePathName(String codePath) { 14028 if (codePath == null) { 14029 return null; 14030 } 14031 final File codeFile = new File(codePath); 14032 final String name = codeFile.getName(); 14033 if (codeFile.isDirectory()) { 14034 return name; 14035 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14036 final int lastDot = name.lastIndexOf('.'); 14037 return name.substring(0, lastDot); 14038 } else { 14039 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14040 return null; 14041 } 14042 } 14043 14044 static class PackageInstalledInfo { 14045 String name; 14046 int uid; 14047 // The set of users that originally had this package installed. 14048 int[] origUsers; 14049 // The set of users that now have this package installed. 14050 int[] newUsers; 14051 PackageParser.Package pkg; 14052 int returnCode; 14053 String returnMsg; 14054 PackageRemovedInfo removedInfo; 14055 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14056 14057 public void setError(int code, String msg) { 14058 setReturnCode(code); 14059 setReturnMessage(msg); 14060 Slog.w(TAG, msg); 14061 } 14062 14063 public void setError(String msg, PackageParserException e) { 14064 setReturnCode(e.error); 14065 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14066 Slog.w(TAG, msg, e); 14067 } 14068 14069 public void setError(String msg, PackageManagerException e) { 14070 returnCode = e.error; 14071 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14072 Slog.w(TAG, msg, e); 14073 } 14074 14075 public void setReturnCode(int returnCode) { 14076 this.returnCode = returnCode; 14077 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14078 for (int i = 0; i < childCount; i++) { 14079 addedChildPackages.valueAt(i).returnCode = returnCode; 14080 } 14081 } 14082 14083 private void setReturnMessage(String returnMsg) { 14084 this.returnMsg = returnMsg; 14085 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14086 for (int i = 0; i < childCount; i++) { 14087 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14088 } 14089 } 14090 14091 // In some error cases we want to convey more info back to the observer 14092 String origPackage; 14093 String origPermission; 14094 } 14095 14096 /* 14097 * Install a non-existing package. 14098 */ 14099 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14100 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14101 PackageInstalledInfo res) { 14102 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14103 14104 // Remember this for later, in case we need to rollback this install 14105 String pkgName = pkg.packageName; 14106 14107 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14108 14109 synchronized(mPackages) { 14110 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14111 // A package with the same name is already installed, though 14112 // it has been renamed to an older name. The package we 14113 // are trying to install should be installed as an update to 14114 // the existing one, but that has not been requested, so bail. 14115 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14116 + " without first uninstalling package running as " 14117 + mSettings.mRenamedPackages.get(pkgName)); 14118 return; 14119 } 14120 if (mPackages.containsKey(pkgName)) { 14121 // Don't allow installation over an existing package with the same name. 14122 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14123 + " without first uninstalling."); 14124 return; 14125 } 14126 } 14127 14128 try { 14129 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14130 System.currentTimeMillis(), user); 14131 14132 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14133 14134 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14135 prepareAppDataAfterInstallLIF(newPackage); 14136 14137 } else { 14138 // Remove package from internal structures, but keep around any 14139 // data that might have already existed 14140 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14141 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14142 } 14143 } catch (PackageManagerException e) { 14144 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14145 } 14146 14147 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14148 } 14149 14150 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14151 // Can't rotate keys during boot or if sharedUser. 14152 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14153 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14154 return false; 14155 } 14156 // app is using upgradeKeySets; make sure all are valid 14157 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14158 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14159 for (int i = 0; i < upgradeKeySets.length; i++) { 14160 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14161 Slog.wtf(TAG, "Package " 14162 + (oldPs.name != null ? oldPs.name : "<null>") 14163 + " contains upgrade-key-set reference to unknown key-set: " 14164 + upgradeKeySets[i] 14165 + " reverting to signatures check."); 14166 return false; 14167 } 14168 } 14169 return true; 14170 } 14171 14172 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14173 // Upgrade keysets are being used. Determine if new package has a superset of the 14174 // required keys. 14175 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14176 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14177 for (int i = 0; i < upgradeKeySets.length; i++) { 14178 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14179 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14180 return true; 14181 } 14182 } 14183 return false; 14184 } 14185 14186 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14187 try (DigestInputStream digestStream = 14188 new DigestInputStream(new FileInputStream(file), digest)) { 14189 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14190 } 14191 } 14192 14193 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14194 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14195 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14196 14197 final PackageParser.Package oldPackage; 14198 final String pkgName = pkg.packageName; 14199 final int[] allUsers; 14200 final int[] installedUsers; 14201 14202 synchronized(mPackages) { 14203 oldPackage = mPackages.get(pkgName); 14204 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14205 14206 // don't allow upgrade to target a release SDK from a pre-release SDK 14207 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14208 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14209 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14210 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14211 if (oldTargetsPreRelease 14212 && !newTargetsPreRelease 14213 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14214 Slog.w(TAG, "Can't install package targeting released sdk"); 14215 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14216 return; 14217 } 14218 14219 // don't allow an upgrade from full to ephemeral 14220 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14221 if (isEphemeral && !oldIsEphemeral) { 14222 // can't downgrade from full to ephemeral 14223 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14224 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14225 return; 14226 } 14227 14228 // verify signatures are valid 14229 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14230 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14231 if (!checkUpgradeKeySetLP(ps, pkg)) { 14232 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14233 "New package not signed by keys specified by upgrade-keysets: " 14234 + pkgName); 14235 return; 14236 } 14237 } else { 14238 // default to original signature matching 14239 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14240 != PackageManager.SIGNATURE_MATCH) { 14241 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14242 "New package has a different signature: " + pkgName); 14243 return; 14244 } 14245 } 14246 14247 // don't allow a system upgrade unless the upgrade hash matches 14248 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14249 byte[] digestBytes = null; 14250 try { 14251 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14252 updateDigest(digest, new File(pkg.baseCodePath)); 14253 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14254 for (String path : pkg.splitCodePaths) { 14255 updateDigest(digest, new File(path)); 14256 } 14257 } 14258 digestBytes = digest.digest(); 14259 } catch (NoSuchAlgorithmException | IOException e) { 14260 res.setError(INSTALL_FAILED_INVALID_APK, 14261 "Could not compute hash: " + pkgName); 14262 return; 14263 } 14264 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14265 res.setError(INSTALL_FAILED_INVALID_APK, 14266 "New package fails restrict-update check: " + pkgName); 14267 return; 14268 } 14269 // retain upgrade restriction 14270 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14271 } 14272 14273 // Check for shared user id changes 14274 String invalidPackageName = 14275 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14276 if (invalidPackageName != null) { 14277 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14278 "Package " + invalidPackageName + " tried to change user " 14279 + oldPackage.mSharedUserId); 14280 return; 14281 } 14282 14283 // In case of rollback, remember per-user/profile install state 14284 allUsers = sUserManager.getUserIds(); 14285 installedUsers = ps.queryInstalledUsers(allUsers, true); 14286 } 14287 14288 // Update what is removed 14289 res.removedInfo = new PackageRemovedInfo(); 14290 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14291 res.removedInfo.removedPackage = oldPackage.packageName; 14292 res.removedInfo.isUpdate = true; 14293 res.removedInfo.origUsers = installedUsers; 14294 final int childCount = (oldPackage.childPackages != null) 14295 ? oldPackage.childPackages.size() : 0; 14296 for (int i = 0; i < childCount; i++) { 14297 boolean childPackageUpdated = false; 14298 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14299 if (res.addedChildPackages != null) { 14300 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14301 if (childRes != null) { 14302 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14303 childRes.removedInfo.removedPackage = childPkg.packageName; 14304 childRes.removedInfo.isUpdate = true; 14305 childPackageUpdated = true; 14306 } 14307 } 14308 if (!childPackageUpdated) { 14309 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14310 childRemovedRes.removedPackage = childPkg.packageName; 14311 childRemovedRes.isUpdate = false; 14312 childRemovedRes.dataRemoved = true; 14313 synchronized (mPackages) { 14314 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14315 if (childPs != null) { 14316 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14317 } 14318 } 14319 if (res.removedInfo.removedChildPackages == null) { 14320 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14321 } 14322 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14323 } 14324 } 14325 14326 boolean sysPkg = (isSystemApp(oldPackage)); 14327 if (sysPkg) { 14328 // Set the system/privileged flags as needed 14329 final boolean privileged = 14330 (oldPackage.applicationInfo.privateFlags 14331 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14332 final int systemPolicyFlags = policyFlags 14333 | PackageParser.PARSE_IS_SYSTEM 14334 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14335 14336 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14337 user, allUsers, installerPackageName, res); 14338 } else { 14339 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14340 user, allUsers, installerPackageName, res); 14341 } 14342 } 14343 14344 public List<String> getPreviousCodePaths(String packageName) { 14345 final PackageSetting ps = mSettings.mPackages.get(packageName); 14346 final List<String> result = new ArrayList<String>(); 14347 if (ps != null && ps.oldCodePaths != null) { 14348 result.addAll(ps.oldCodePaths); 14349 } 14350 return result; 14351 } 14352 14353 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14354 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14355 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14356 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14357 + deletedPackage); 14358 14359 String pkgName = deletedPackage.packageName; 14360 boolean deletedPkg = true; 14361 boolean addedPkg = false; 14362 boolean updatedSettings = false; 14363 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14364 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14365 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14366 14367 final long origUpdateTime = (pkg.mExtras != null) 14368 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14369 14370 // First delete the existing package while retaining the data directory 14371 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14372 res.removedInfo, true, pkg)) { 14373 // If the existing package wasn't successfully deleted 14374 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14375 deletedPkg = false; 14376 } else { 14377 // Successfully deleted the old package; proceed with replace. 14378 14379 // If deleted package lived in a container, give users a chance to 14380 // relinquish resources before killing. 14381 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14382 if (DEBUG_INSTALL) { 14383 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14384 } 14385 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14386 final ArrayList<String> pkgList = new ArrayList<String>(1); 14387 pkgList.add(deletedPackage.applicationInfo.packageName); 14388 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14389 } 14390 14391 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14392 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14393 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14394 14395 try { 14396 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14397 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14398 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14399 14400 // Update the in-memory copy of the previous code paths. 14401 PackageSetting ps = mSettings.mPackages.get(pkgName); 14402 if (!killApp) { 14403 if (ps.oldCodePaths == null) { 14404 ps.oldCodePaths = new ArraySet<>(); 14405 } 14406 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14407 if (deletedPackage.splitCodePaths != null) { 14408 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14409 } 14410 } else { 14411 ps.oldCodePaths = null; 14412 } 14413 if (ps.childPackageNames != null) { 14414 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14415 final String childPkgName = ps.childPackageNames.get(i); 14416 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14417 childPs.oldCodePaths = ps.oldCodePaths; 14418 } 14419 } 14420 prepareAppDataAfterInstallLIF(newPackage); 14421 addedPkg = true; 14422 } catch (PackageManagerException e) { 14423 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14424 } 14425 } 14426 14427 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14428 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14429 14430 // Revert all internal state mutations and added folders for the failed install 14431 if (addedPkg) { 14432 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14433 res.removedInfo, true, null); 14434 } 14435 14436 // Restore the old package 14437 if (deletedPkg) { 14438 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14439 File restoreFile = new File(deletedPackage.codePath); 14440 // Parse old package 14441 boolean oldExternal = isExternal(deletedPackage); 14442 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14443 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14444 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14445 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14446 try { 14447 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14448 null); 14449 } catch (PackageManagerException e) { 14450 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14451 + e.getMessage()); 14452 return; 14453 } 14454 14455 synchronized (mPackages) { 14456 // Ensure the installer package name up to date 14457 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14458 14459 // Update permissions for restored package 14460 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14461 14462 mSettings.writeLPr(); 14463 } 14464 14465 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14466 } 14467 } else { 14468 synchronized (mPackages) { 14469 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14470 if (ps != null) { 14471 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14472 if (res.removedInfo.removedChildPackages != null) { 14473 final int childCount = res.removedInfo.removedChildPackages.size(); 14474 // Iterate in reverse as we may modify the collection 14475 for (int i = childCount - 1; i >= 0; i--) { 14476 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14477 if (res.addedChildPackages.containsKey(childPackageName)) { 14478 res.removedInfo.removedChildPackages.removeAt(i); 14479 } else { 14480 PackageRemovedInfo childInfo = res.removedInfo 14481 .removedChildPackages.valueAt(i); 14482 childInfo.removedForAllUsers = mPackages.get( 14483 childInfo.removedPackage) == null; 14484 } 14485 } 14486 } 14487 } 14488 } 14489 } 14490 } 14491 14492 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14493 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14494 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14495 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14496 + ", old=" + deletedPackage); 14497 14498 final boolean disabledSystem; 14499 14500 // Remove existing system package 14501 removePackageLI(deletedPackage, true); 14502 14503 synchronized (mPackages) { 14504 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14505 } 14506 if (!disabledSystem) { 14507 // We didn't need to disable the .apk as a current system package, 14508 // which means we are replacing another update that is already 14509 // installed. We need to make sure to delete the older one's .apk. 14510 res.removedInfo.args = createInstallArgsForExisting(0, 14511 deletedPackage.applicationInfo.getCodePath(), 14512 deletedPackage.applicationInfo.getResourcePath(), 14513 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14514 } else { 14515 res.removedInfo.args = null; 14516 } 14517 14518 // Successfully disabled the old package. Now proceed with re-installation 14519 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14520 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14521 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14522 14523 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14524 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14525 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14526 14527 PackageParser.Package newPackage = null; 14528 try { 14529 // Add the package to the internal data structures 14530 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14531 14532 // Set the update and install times 14533 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14534 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14535 System.currentTimeMillis()); 14536 14537 // Update the package dynamic state if succeeded 14538 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14539 // Now that the install succeeded make sure we remove data 14540 // directories for any child package the update removed. 14541 final int deletedChildCount = (deletedPackage.childPackages != null) 14542 ? deletedPackage.childPackages.size() : 0; 14543 final int newChildCount = (newPackage.childPackages != null) 14544 ? newPackage.childPackages.size() : 0; 14545 for (int i = 0; i < deletedChildCount; i++) { 14546 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14547 boolean childPackageDeleted = true; 14548 for (int j = 0; j < newChildCount; j++) { 14549 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14550 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14551 childPackageDeleted = false; 14552 break; 14553 } 14554 } 14555 if (childPackageDeleted) { 14556 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14557 deletedChildPkg.packageName); 14558 if (ps != null && res.removedInfo.removedChildPackages != null) { 14559 PackageRemovedInfo removedChildRes = res.removedInfo 14560 .removedChildPackages.get(deletedChildPkg.packageName); 14561 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14562 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14563 } 14564 } 14565 } 14566 14567 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14568 prepareAppDataAfterInstallLIF(newPackage); 14569 } 14570 } catch (PackageManagerException e) { 14571 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14572 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14573 } 14574 14575 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14576 // Re installation failed. Restore old information 14577 // Remove new pkg information 14578 if (newPackage != null) { 14579 removeInstalledPackageLI(newPackage, true); 14580 } 14581 // Add back the old system package 14582 try { 14583 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14584 } catch (PackageManagerException e) { 14585 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14586 } 14587 14588 synchronized (mPackages) { 14589 if (disabledSystem) { 14590 enableSystemPackageLPw(deletedPackage); 14591 } 14592 14593 // Ensure the installer package name up to date 14594 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14595 14596 // Update permissions for restored package 14597 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14598 14599 mSettings.writeLPr(); 14600 } 14601 14602 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14603 + " after failed upgrade"); 14604 } 14605 } 14606 14607 /** 14608 * Checks whether the parent or any of the child packages have a change shared 14609 * user. For a package to be a valid update the shred users of the parent and 14610 * the children should match. We may later support changing child shared users. 14611 * @param oldPkg The updated package. 14612 * @param newPkg The update package. 14613 * @return The shared user that change between the versions. 14614 */ 14615 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14616 PackageParser.Package newPkg) { 14617 // Check parent shared user 14618 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14619 return newPkg.packageName; 14620 } 14621 // Check child shared users 14622 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14623 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14624 for (int i = 0; i < newChildCount; i++) { 14625 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14626 // If this child was present, did it have the same shared user? 14627 for (int j = 0; j < oldChildCount; j++) { 14628 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14629 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14630 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14631 return newChildPkg.packageName; 14632 } 14633 } 14634 } 14635 return null; 14636 } 14637 14638 private void removeNativeBinariesLI(PackageSetting ps) { 14639 // Remove the lib path for the parent package 14640 if (ps != null) { 14641 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14642 // Remove the lib path for the child packages 14643 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14644 for (int i = 0; i < childCount; i++) { 14645 PackageSetting childPs = null; 14646 synchronized (mPackages) { 14647 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14648 } 14649 if (childPs != null) { 14650 NativeLibraryHelper.removeNativeBinariesLI(childPs 14651 .legacyNativeLibraryPathString); 14652 } 14653 } 14654 } 14655 } 14656 14657 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14658 // Enable the parent package 14659 mSettings.enableSystemPackageLPw(pkg.packageName); 14660 // Enable the child packages 14661 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14662 for (int i = 0; i < childCount; i++) { 14663 PackageParser.Package childPkg = pkg.childPackages.get(i); 14664 mSettings.enableSystemPackageLPw(childPkg.packageName); 14665 } 14666 } 14667 14668 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14669 PackageParser.Package newPkg) { 14670 // Disable the parent package (parent always replaced) 14671 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14672 // Disable the child packages 14673 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14674 for (int i = 0; i < childCount; i++) { 14675 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14676 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14677 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14678 } 14679 return disabled; 14680 } 14681 14682 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14683 String installerPackageName) { 14684 // Enable the parent package 14685 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14686 // Enable the child packages 14687 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14688 for (int i = 0; i < childCount; i++) { 14689 PackageParser.Package childPkg = pkg.childPackages.get(i); 14690 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14691 } 14692 } 14693 14694 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14695 // Collect all used permissions in the UID 14696 ArraySet<String> usedPermissions = new ArraySet<>(); 14697 final int packageCount = su.packages.size(); 14698 for (int i = 0; i < packageCount; i++) { 14699 PackageSetting ps = su.packages.valueAt(i); 14700 if (ps.pkg == null) { 14701 continue; 14702 } 14703 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14704 for (int j = 0; j < requestedPermCount; j++) { 14705 String permission = ps.pkg.requestedPermissions.get(j); 14706 BasePermission bp = mSettings.mPermissions.get(permission); 14707 if (bp != null) { 14708 usedPermissions.add(permission); 14709 } 14710 } 14711 } 14712 14713 PermissionsState permissionsState = su.getPermissionsState(); 14714 // Prune install permissions 14715 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14716 final int installPermCount = installPermStates.size(); 14717 for (int i = installPermCount - 1; i >= 0; i--) { 14718 PermissionState permissionState = installPermStates.get(i); 14719 if (!usedPermissions.contains(permissionState.getName())) { 14720 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14721 if (bp != null) { 14722 permissionsState.revokeInstallPermission(bp); 14723 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14724 PackageManager.MASK_PERMISSION_FLAGS, 0); 14725 } 14726 } 14727 } 14728 14729 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14730 14731 // Prune runtime permissions 14732 for (int userId : allUserIds) { 14733 List<PermissionState> runtimePermStates = permissionsState 14734 .getRuntimePermissionStates(userId); 14735 final int runtimePermCount = runtimePermStates.size(); 14736 for (int i = runtimePermCount - 1; i >= 0; i--) { 14737 PermissionState permissionState = runtimePermStates.get(i); 14738 if (!usedPermissions.contains(permissionState.getName())) { 14739 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14740 if (bp != null) { 14741 permissionsState.revokeRuntimePermission(bp, userId); 14742 permissionsState.updatePermissionFlags(bp, userId, 14743 PackageManager.MASK_PERMISSION_FLAGS, 0); 14744 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14745 runtimePermissionChangedUserIds, userId); 14746 } 14747 } 14748 } 14749 } 14750 14751 return runtimePermissionChangedUserIds; 14752 } 14753 14754 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14755 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14756 // Update the parent package setting 14757 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14758 res, user); 14759 // Update the child packages setting 14760 final int childCount = (newPackage.childPackages != null) 14761 ? newPackage.childPackages.size() : 0; 14762 for (int i = 0; i < childCount; i++) { 14763 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14764 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14765 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14766 childRes.origUsers, childRes, user); 14767 } 14768 } 14769 14770 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14771 String installerPackageName, int[] allUsers, int[] installedForUsers, 14772 PackageInstalledInfo res, UserHandle user) { 14773 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14774 14775 String pkgName = newPackage.packageName; 14776 synchronized (mPackages) { 14777 //write settings. the installStatus will be incomplete at this stage. 14778 //note that the new package setting would have already been 14779 //added to mPackages. It hasn't been persisted yet. 14780 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14782 mSettings.writeLPr(); 14783 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14784 } 14785 14786 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14787 synchronized (mPackages) { 14788 updatePermissionsLPw(newPackage.packageName, newPackage, 14789 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14790 ? UPDATE_PERMISSIONS_ALL : 0)); 14791 // For system-bundled packages, we assume that installing an upgraded version 14792 // of the package implies that the user actually wants to run that new code, 14793 // so we enable the package. 14794 PackageSetting ps = mSettings.mPackages.get(pkgName); 14795 final int userId = user.getIdentifier(); 14796 if (ps != null) { 14797 if (isSystemApp(newPackage)) { 14798 if (DEBUG_INSTALL) { 14799 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14800 } 14801 // Enable system package for requested users 14802 if (res.origUsers != null) { 14803 for (int origUserId : res.origUsers) { 14804 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14805 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14806 origUserId, installerPackageName); 14807 } 14808 } 14809 } 14810 // Also convey the prior install/uninstall state 14811 if (allUsers != null && installedForUsers != null) { 14812 for (int currentUserId : allUsers) { 14813 final boolean installed = ArrayUtils.contains( 14814 installedForUsers, currentUserId); 14815 if (DEBUG_INSTALL) { 14816 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14817 } 14818 ps.setInstalled(installed, currentUserId); 14819 } 14820 // these install state changes will be persisted in the 14821 // upcoming call to mSettings.writeLPr(). 14822 } 14823 } 14824 // It's implied that when a user requests installation, they want the app to be 14825 // installed and enabled. 14826 if (userId != UserHandle.USER_ALL) { 14827 ps.setInstalled(true, userId); 14828 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14829 } 14830 } 14831 res.name = pkgName; 14832 res.uid = newPackage.applicationInfo.uid; 14833 res.pkg = newPackage; 14834 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14835 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14836 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14837 //to update install status 14838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14839 mSettings.writeLPr(); 14840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14841 } 14842 14843 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14844 } 14845 14846 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14847 try { 14848 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14849 installPackageLI(args, res); 14850 } finally { 14851 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14852 } 14853 } 14854 14855 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14856 final int installFlags = args.installFlags; 14857 final String installerPackageName = args.installerPackageName; 14858 final String volumeUuid = args.volumeUuid; 14859 final File tmpPackageFile = new File(args.getCodePath()); 14860 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14861 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14862 || (args.volumeUuid != null)); 14863 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14864 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14865 boolean replace = false; 14866 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14867 if (args.move != null) { 14868 // moving a complete application; perform an initial scan on the new install location 14869 scanFlags |= SCAN_INITIAL; 14870 } 14871 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14872 scanFlags |= SCAN_DONT_KILL_APP; 14873 } 14874 14875 // Result object to be returned 14876 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14877 14878 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14879 14880 // Sanity check 14881 if (ephemeral && (forwardLocked || onExternal)) { 14882 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14883 + " external=" + onExternal); 14884 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14885 return; 14886 } 14887 14888 // Retrieve PackageSettings and parse package 14889 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14890 | PackageParser.PARSE_ENFORCE_CODE 14891 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14892 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14893 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14894 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14895 PackageParser pp = new PackageParser(); 14896 pp.setSeparateProcesses(mSeparateProcesses); 14897 pp.setDisplayMetrics(mMetrics); 14898 14899 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14900 final PackageParser.Package pkg; 14901 try { 14902 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14903 } catch (PackageParserException e) { 14904 res.setError("Failed parse during installPackageLI", e); 14905 return; 14906 } finally { 14907 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14908 } 14909 14910 // If we are installing a clustered package add results for the children 14911 if (pkg.childPackages != null) { 14912 synchronized (mPackages) { 14913 final int childCount = pkg.childPackages.size(); 14914 for (int i = 0; i < childCount; i++) { 14915 PackageParser.Package childPkg = pkg.childPackages.get(i); 14916 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14917 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14918 childRes.pkg = childPkg; 14919 childRes.name = childPkg.packageName; 14920 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14921 if (childPs != null) { 14922 childRes.origUsers = childPs.queryInstalledUsers( 14923 sUserManager.getUserIds(), true); 14924 } 14925 if ((mPackages.containsKey(childPkg.packageName))) { 14926 childRes.removedInfo = new PackageRemovedInfo(); 14927 childRes.removedInfo.removedPackage = childPkg.packageName; 14928 } 14929 if (res.addedChildPackages == null) { 14930 res.addedChildPackages = new ArrayMap<>(); 14931 } 14932 res.addedChildPackages.put(childPkg.packageName, childRes); 14933 } 14934 } 14935 } 14936 14937 // If package doesn't declare API override, mark that we have an install 14938 // time CPU ABI override. 14939 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14940 pkg.cpuAbiOverride = args.abiOverride; 14941 } 14942 14943 String pkgName = res.name = pkg.packageName; 14944 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14945 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14946 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14947 return; 14948 } 14949 } 14950 14951 try { 14952 // either use what we've been given or parse directly from the APK 14953 if (args.certificates != null) { 14954 try { 14955 PackageParser.populateCertificates(pkg, args.certificates); 14956 } catch (PackageParserException e) { 14957 // there was something wrong with the certificates we were given; 14958 // try to pull them from the APK 14959 PackageParser.collectCertificates(pkg, parseFlags); 14960 } 14961 } else { 14962 PackageParser.collectCertificates(pkg, parseFlags); 14963 } 14964 } catch (PackageParserException e) { 14965 res.setError("Failed collect during installPackageLI", e); 14966 return; 14967 } 14968 14969 // Get rid of all references to package scan path via parser. 14970 pp = null; 14971 String oldCodePath = null; 14972 boolean systemApp = false; 14973 synchronized (mPackages) { 14974 // Check if installing already existing package 14975 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14976 String oldName = mSettings.mRenamedPackages.get(pkgName); 14977 if (pkg.mOriginalPackages != null 14978 && pkg.mOriginalPackages.contains(oldName) 14979 && mPackages.containsKey(oldName)) { 14980 // This package is derived from an original package, 14981 // and this device has been updating from that original 14982 // name. We must continue using the original name, so 14983 // rename the new package here. 14984 pkg.setPackageName(oldName); 14985 pkgName = pkg.packageName; 14986 replace = true; 14987 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14988 + oldName + " pkgName=" + pkgName); 14989 } else if (mPackages.containsKey(pkgName)) { 14990 // This package, under its official name, already exists 14991 // on the device; we should replace it. 14992 replace = true; 14993 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14994 } 14995 14996 // Child packages are installed through the parent package 14997 if (pkg.parentPackage != null) { 14998 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14999 "Package " + pkg.packageName + " is child of package " 15000 + pkg.parentPackage.parentPackage + ". Child packages " 15001 + "can be updated only through the parent package."); 15002 return; 15003 } 15004 15005 if (replace) { 15006 // Prevent apps opting out from runtime permissions 15007 PackageParser.Package oldPackage = mPackages.get(pkgName); 15008 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15009 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15010 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15011 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15012 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15013 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15014 + " doesn't support runtime permissions but the old" 15015 + " target SDK " + oldTargetSdk + " does."); 15016 return; 15017 } 15018 15019 // Prevent installing of child packages 15020 if (oldPackage.parentPackage != null) { 15021 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15022 "Package " + pkg.packageName + " is child of package " 15023 + oldPackage.parentPackage + ". Child packages " 15024 + "can be updated only through the parent package."); 15025 return; 15026 } 15027 } 15028 } 15029 15030 PackageSetting ps = mSettings.mPackages.get(pkgName); 15031 if (ps != null) { 15032 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15033 15034 // Quick sanity check that we're signed correctly if updating; 15035 // we'll check this again later when scanning, but we want to 15036 // bail early here before tripping over redefined permissions. 15037 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15038 if (!checkUpgradeKeySetLP(ps, pkg)) { 15039 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15040 + pkg.packageName + " upgrade keys do not match the " 15041 + "previously installed version"); 15042 return; 15043 } 15044 } else { 15045 try { 15046 verifySignaturesLP(ps, pkg); 15047 } catch (PackageManagerException e) { 15048 res.setError(e.error, e.getMessage()); 15049 return; 15050 } 15051 } 15052 15053 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15054 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15055 systemApp = (ps.pkg.applicationInfo.flags & 15056 ApplicationInfo.FLAG_SYSTEM) != 0; 15057 } 15058 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15059 } 15060 15061 // Check whether the newly-scanned package wants to define an already-defined perm 15062 int N = pkg.permissions.size(); 15063 for (int i = N-1; i >= 0; i--) { 15064 PackageParser.Permission perm = pkg.permissions.get(i); 15065 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15066 if (bp != null) { 15067 // If the defining package is signed with our cert, it's okay. This 15068 // also includes the "updating the same package" case, of course. 15069 // "updating same package" could also involve key-rotation. 15070 final boolean sigsOk; 15071 if (bp.sourcePackage.equals(pkg.packageName) 15072 && (bp.packageSetting instanceof PackageSetting) 15073 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15074 scanFlags))) { 15075 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15076 } else { 15077 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15078 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15079 } 15080 if (!sigsOk) { 15081 // If the owning package is the system itself, we log but allow 15082 // install to proceed; we fail the install on all other permission 15083 // redefinitions. 15084 if (!bp.sourcePackage.equals("android")) { 15085 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15086 + pkg.packageName + " attempting to redeclare permission " 15087 + perm.info.name + " already owned by " + bp.sourcePackage); 15088 res.origPermission = perm.info.name; 15089 res.origPackage = bp.sourcePackage; 15090 return; 15091 } else { 15092 Slog.w(TAG, "Package " + pkg.packageName 15093 + " attempting to redeclare system permission " 15094 + perm.info.name + "; ignoring new declaration"); 15095 pkg.permissions.remove(i); 15096 } 15097 } 15098 } 15099 } 15100 } 15101 15102 if (systemApp) { 15103 if (onExternal) { 15104 // Abort update; system app can't be replaced with app on sdcard 15105 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15106 "Cannot install updates to system apps on sdcard"); 15107 return; 15108 } else if (ephemeral) { 15109 // Abort update; system app can't be replaced with an ephemeral app 15110 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15111 "Cannot update a system app with an ephemeral app"); 15112 return; 15113 } 15114 } 15115 15116 if (args.move != null) { 15117 // We did an in-place move, so dex is ready to roll 15118 scanFlags |= SCAN_NO_DEX; 15119 scanFlags |= SCAN_MOVE; 15120 15121 synchronized (mPackages) { 15122 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15123 if (ps == null) { 15124 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15125 "Missing settings for moved package " + pkgName); 15126 } 15127 15128 // We moved the entire application as-is, so bring over the 15129 // previously derived ABI information. 15130 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15131 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15132 } 15133 15134 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15135 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15136 scanFlags |= SCAN_NO_DEX; 15137 15138 try { 15139 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15140 args.abiOverride : pkg.cpuAbiOverride); 15141 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15142 true /* extract libs */); 15143 } catch (PackageManagerException pme) { 15144 Slog.e(TAG, "Error deriving application ABI", pme); 15145 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15146 return; 15147 } 15148 15149 // Shared libraries for the package need to be updated. 15150 synchronized (mPackages) { 15151 try { 15152 updateSharedLibrariesLPw(pkg, null); 15153 } catch (PackageManagerException e) { 15154 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15155 } 15156 } 15157 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15158 // Do not run PackageDexOptimizer through the local performDexOpt 15159 // method because `pkg` may not be in `mPackages` yet. 15160 // 15161 // Also, don't fail application installs if the dexopt step fails. 15162 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15163 null /* instructionSets */, false /* checkProfiles */, 15164 getCompilerFilterForReason(REASON_INSTALL)); 15165 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15166 15167 // Notify BackgroundDexOptService that the package has been changed. 15168 // If this is an update of a package which used to fail to compile, 15169 // BDOS will remove it from its blacklist. 15170 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15171 } 15172 15173 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15174 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15175 return; 15176 } 15177 15178 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15179 15180 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15181 "installPackageLI")) { 15182 if (replace) { 15183 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15184 installerPackageName, res); 15185 } else { 15186 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15187 args.user, installerPackageName, volumeUuid, res); 15188 } 15189 } 15190 synchronized (mPackages) { 15191 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15192 if (ps != null) { 15193 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15194 } 15195 15196 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15197 for (int i = 0; i < childCount; i++) { 15198 PackageParser.Package childPkg = pkg.childPackages.get(i); 15199 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15200 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15201 if (childPs != null) { 15202 childRes.newUsers = childPs.queryInstalledUsers( 15203 sUserManager.getUserIds(), true); 15204 } 15205 } 15206 } 15207 } 15208 15209 private void startIntentFilterVerifications(int userId, boolean replacing, 15210 PackageParser.Package pkg) { 15211 if (mIntentFilterVerifierComponent == null) { 15212 Slog.w(TAG, "No IntentFilter verification will not be done as " 15213 + "there is no IntentFilterVerifier available!"); 15214 return; 15215 } 15216 15217 final int verifierUid = getPackageUid( 15218 mIntentFilterVerifierComponent.getPackageName(), 15219 MATCH_DEBUG_TRIAGED_MISSING, 15220 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15221 15222 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15223 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15224 mHandler.sendMessage(msg); 15225 15226 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15227 for (int i = 0; i < childCount; i++) { 15228 PackageParser.Package childPkg = pkg.childPackages.get(i); 15229 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15230 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15231 mHandler.sendMessage(msg); 15232 } 15233 } 15234 15235 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15236 PackageParser.Package pkg) { 15237 int size = pkg.activities.size(); 15238 if (size == 0) { 15239 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15240 "No activity, so no need to verify any IntentFilter!"); 15241 return; 15242 } 15243 15244 final boolean hasDomainURLs = hasDomainURLs(pkg); 15245 if (!hasDomainURLs) { 15246 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15247 "No domain URLs, so no need to verify any IntentFilter!"); 15248 return; 15249 } 15250 15251 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15252 + " if any IntentFilter from the " + size 15253 + " Activities needs verification ..."); 15254 15255 int count = 0; 15256 final String packageName = pkg.packageName; 15257 15258 synchronized (mPackages) { 15259 // If this is a new install and we see that we've already run verification for this 15260 // package, we have nothing to do: it means the state was restored from backup. 15261 if (!replacing) { 15262 IntentFilterVerificationInfo ivi = 15263 mSettings.getIntentFilterVerificationLPr(packageName); 15264 if (ivi != null) { 15265 if (DEBUG_DOMAIN_VERIFICATION) { 15266 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15267 + ivi.getStatusString()); 15268 } 15269 return; 15270 } 15271 } 15272 15273 // If any filters need to be verified, then all need to be. 15274 boolean needToVerify = false; 15275 for (PackageParser.Activity a : pkg.activities) { 15276 for (ActivityIntentInfo filter : a.intents) { 15277 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15278 if (DEBUG_DOMAIN_VERIFICATION) { 15279 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15280 } 15281 needToVerify = true; 15282 break; 15283 } 15284 } 15285 } 15286 15287 if (needToVerify) { 15288 final int verificationId = mIntentFilterVerificationToken++; 15289 for (PackageParser.Activity a : pkg.activities) { 15290 for (ActivityIntentInfo filter : a.intents) { 15291 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15293 "Verification needed for IntentFilter:" + filter.toString()); 15294 mIntentFilterVerifier.addOneIntentFilterVerification( 15295 verifierUid, userId, verificationId, filter, packageName); 15296 count++; 15297 } 15298 } 15299 } 15300 } 15301 } 15302 15303 if (count > 0) { 15304 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15305 + " IntentFilter verification" + (count > 1 ? "s" : "") 15306 + " for userId:" + userId); 15307 mIntentFilterVerifier.startVerifications(userId); 15308 } else { 15309 if (DEBUG_DOMAIN_VERIFICATION) { 15310 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15311 } 15312 } 15313 } 15314 15315 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15316 final ComponentName cn = filter.activity.getComponentName(); 15317 final String packageName = cn.getPackageName(); 15318 15319 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15320 packageName); 15321 if (ivi == null) { 15322 return true; 15323 } 15324 int status = ivi.getStatus(); 15325 switch (status) { 15326 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15327 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15328 return true; 15329 15330 default: 15331 // Nothing to do 15332 return false; 15333 } 15334 } 15335 15336 private static boolean isMultiArch(ApplicationInfo info) { 15337 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15338 } 15339 15340 private static boolean isExternal(PackageParser.Package pkg) { 15341 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15342 } 15343 15344 private static boolean isExternal(PackageSetting ps) { 15345 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15346 } 15347 15348 private static boolean isEphemeral(PackageParser.Package pkg) { 15349 return pkg.applicationInfo.isEphemeralApp(); 15350 } 15351 15352 private static boolean isEphemeral(PackageSetting ps) { 15353 return ps.pkg != null && isEphemeral(ps.pkg); 15354 } 15355 15356 private static boolean isSystemApp(PackageParser.Package pkg) { 15357 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15358 } 15359 15360 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15361 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15362 } 15363 15364 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15365 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15366 } 15367 15368 private static boolean isSystemApp(PackageSetting ps) { 15369 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15370 } 15371 15372 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15373 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15374 } 15375 15376 private int packageFlagsToInstallFlags(PackageSetting ps) { 15377 int installFlags = 0; 15378 if (isEphemeral(ps)) { 15379 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15380 } 15381 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15382 // This existing package was an external ASEC install when we have 15383 // the external flag without a UUID 15384 installFlags |= PackageManager.INSTALL_EXTERNAL; 15385 } 15386 if (ps.isForwardLocked()) { 15387 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15388 } 15389 return installFlags; 15390 } 15391 15392 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15393 if (isExternal(pkg)) { 15394 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15395 return StorageManager.UUID_PRIMARY_PHYSICAL; 15396 } else { 15397 return pkg.volumeUuid; 15398 } 15399 } else { 15400 return StorageManager.UUID_PRIVATE_INTERNAL; 15401 } 15402 } 15403 15404 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15405 if (isExternal(pkg)) { 15406 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15407 return mSettings.getExternalVersion(); 15408 } else { 15409 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15410 } 15411 } else { 15412 return mSettings.getInternalVersion(); 15413 } 15414 } 15415 15416 private void deleteTempPackageFiles() { 15417 final FilenameFilter filter = new FilenameFilter() { 15418 public boolean accept(File dir, String name) { 15419 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15420 } 15421 }; 15422 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15423 file.delete(); 15424 } 15425 } 15426 15427 @Override 15428 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15429 int flags) { 15430 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15431 flags); 15432 } 15433 15434 @Override 15435 public void deletePackage(final String packageName, 15436 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15437 mContext.enforceCallingOrSelfPermission( 15438 android.Manifest.permission.DELETE_PACKAGES, null); 15439 Preconditions.checkNotNull(packageName); 15440 Preconditions.checkNotNull(observer); 15441 final int uid = Binder.getCallingUid(); 15442 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15443 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15444 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15445 mContext.enforceCallingOrSelfPermission( 15446 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15447 "deletePackage for user " + userId); 15448 } 15449 15450 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15451 try { 15452 observer.onPackageDeleted(packageName, 15453 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15454 } catch (RemoteException re) { 15455 } 15456 return; 15457 } 15458 15459 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15460 try { 15461 observer.onPackageDeleted(packageName, 15462 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15463 } catch (RemoteException re) { 15464 } 15465 return; 15466 } 15467 15468 if (DEBUG_REMOVE) { 15469 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15470 + " deleteAllUsers: " + deleteAllUsers ); 15471 } 15472 // Queue up an async operation since the package deletion may take a little while. 15473 mHandler.post(new Runnable() { 15474 public void run() { 15475 mHandler.removeCallbacks(this); 15476 int returnCode; 15477 if (!deleteAllUsers) { 15478 returnCode = deletePackageX(packageName, userId, deleteFlags); 15479 } else { 15480 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15481 // If nobody is blocking uninstall, proceed with delete for all users 15482 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15483 returnCode = deletePackageX(packageName, userId, deleteFlags); 15484 } else { 15485 // Otherwise uninstall individually for users with blockUninstalls=false 15486 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15487 for (int userId : users) { 15488 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15489 returnCode = deletePackageX(packageName, userId, userFlags); 15490 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15491 Slog.w(TAG, "Package delete failed for user " + userId 15492 + ", returnCode " + returnCode); 15493 } 15494 } 15495 } 15496 // The app has only been marked uninstalled for certain users. 15497 // We still need to report that delete was blocked 15498 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15499 } 15500 } 15501 try { 15502 observer.onPackageDeleted(packageName, returnCode, null); 15503 } catch (RemoteException e) { 15504 Log.i(TAG, "Observer no longer exists."); 15505 } //end catch 15506 } //end run 15507 }); 15508 } 15509 15510 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15511 int[] result = EMPTY_INT_ARRAY; 15512 for (int userId : userIds) { 15513 if (getBlockUninstallForUser(packageName, userId)) { 15514 result = ArrayUtils.appendInt(result, userId); 15515 } 15516 } 15517 return result; 15518 } 15519 15520 @Override 15521 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15522 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15523 } 15524 15525 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15526 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15527 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15528 try { 15529 if (dpm != null) { 15530 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15531 /* callingUserOnly =*/ false); 15532 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15533 : deviceOwnerComponentName.getPackageName(); 15534 // Does the package contains the device owner? 15535 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15536 // this check is probably not needed, since DO should be registered as a device 15537 // admin on some user too. (Original bug for this: b/17657954) 15538 if (packageName.equals(deviceOwnerPackageName)) { 15539 return true; 15540 } 15541 // Does it contain a device admin for any user? 15542 int[] users; 15543 if (userId == UserHandle.USER_ALL) { 15544 users = sUserManager.getUserIds(); 15545 } else { 15546 users = new int[]{userId}; 15547 } 15548 for (int i = 0; i < users.length; ++i) { 15549 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15550 return true; 15551 } 15552 } 15553 } 15554 } catch (RemoteException e) { 15555 } 15556 return false; 15557 } 15558 15559 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15560 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15561 } 15562 15563 /** 15564 * This method is an internal method that could be get invoked either 15565 * to delete an installed package or to clean up a failed installation. 15566 * After deleting an installed package, a broadcast is sent to notify any 15567 * listeners that the package has been removed. For cleaning up a failed 15568 * installation, the broadcast is not necessary since the package's 15569 * installation wouldn't have sent the initial broadcast either 15570 * The key steps in deleting a package are 15571 * deleting the package information in internal structures like mPackages, 15572 * deleting the packages base directories through installd 15573 * updating mSettings to reflect current status 15574 * persisting settings for later use 15575 * sending a broadcast if necessary 15576 */ 15577 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15578 final PackageRemovedInfo info = new PackageRemovedInfo(); 15579 final boolean res; 15580 15581 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15582 ? UserHandle.ALL : new UserHandle(userId); 15583 15584 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15585 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15586 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15587 } 15588 15589 PackageSetting uninstalledPs = null; 15590 15591 // for the uninstall-updates case and restricted profiles, remember the per- 15592 // user handle installed state 15593 int[] allUsers; 15594 synchronized (mPackages) { 15595 uninstalledPs = mSettings.mPackages.get(packageName); 15596 if (uninstalledPs == null) { 15597 Slog.w(TAG, "Not removing non-existent package " + packageName); 15598 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15599 } 15600 allUsers = sUserManager.getUserIds(); 15601 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15602 } 15603 15604 synchronized (mInstallLock) { 15605 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15606 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15607 "deletePackageX")) { 15608 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15609 deleteFlags | REMOVE_CHATTY, info, true, null); 15610 } 15611 synchronized (mPackages) { 15612 if (res) { 15613 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15614 } 15615 } 15616 } 15617 15618 if (res) { 15619 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15620 info.sendPackageRemovedBroadcasts(killApp); 15621 info.sendSystemPackageUpdatedBroadcasts(); 15622 info.sendSystemPackageAppearedBroadcasts(); 15623 } 15624 // Force a gc here. 15625 Runtime.getRuntime().gc(); 15626 // Delete the resources here after sending the broadcast to let 15627 // other processes clean up before deleting resources. 15628 if (info.args != null) { 15629 synchronized (mInstallLock) { 15630 info.args.doPostDeleteLI(true); 15631 } 15632 } 15633 15634 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15635 } 15636 15637 class PackageRemovedInfo { 15638 String removedPackage; 15639 int uid = -1; 15640 int removedAppId = -1; 15641 int[] origUsers; 15642 int[] removedUsers = null; 15643 boolean isRemovedPackageSystemUpdate = false; 15644 boolean isUpdate; 15645 boolean dataRemoved; 15646 boolean removedForAllUsers; 15647 // Clean up resources deleted packages. 15648 InstallArgs args = null; 15649 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15650 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15651 15652 void sendPackageRemovedBroadcasts(boolean killApp) { 15653 sendPackageRemovedBroadcastInternal(killApp); 15654 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15655 for (int i = 0; i < childCount; i++) { 15656 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15657 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15658 } 15659 } 15660 15661 void sendSystemPackageUpdatedBroadcasts() { 15662 if (isRemovedPackageSystemUpdate) { 15663 sendSystemPackageUpdatedBroadcastsInternal(); 15664 final int childCount = (removedChildPackages != null) 15665 ? removedChildPackages.size() : 0; 15666 for (int i = 0; i < childCount; i++) { 15667 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15668 if (childInfo.isRemovedPackageSystemUpdate) { 15669 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15670 } 15671 } 15672 } 15673 } 15674 15675 void sendSystemPackageAppearedBroadcasts() { 15676 final int packageCount = (appearedChildPackages != null) 15677 ? appearedChildPackages.size() : 0; 15678 for (int i = 0; i < packageCount; i++) { 15679 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15680 for (int userId : installedInfo.newUsers) { 15681 sendPackageAddedForUser(installedInfo.name, true, 15682 UserHandle.getAppId(installedInfo.uid), userId); 15683 } 15684 } 15685 } 15686 15687 private void sendSystemPackageUpdatedBroadcastsInternal() { 15688 Bundle extras = new Bundle(2); 15689 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15690 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15691 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15692 extras, 0, null, null, null); 15693 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15694 extras, 0, null, null, null); 15695 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15696 null, 0, removedPackage, null, null); 15697 } 15698 15699 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15700 Bundle extras = new Bundle(2); 15701 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15702 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15703 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15704 if (isUpdate || isRemovedPackageSystemUpdate) { 15705 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15706 } 15707 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15708 if (removedPackage != null) { 15709 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15710 extras, 0, null, null, removedUsers); 15711 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15712 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15713 removedPackage, extras, 0, null, null, removedUsers); 15714 } 15715 } 15716 if (removedAppId >= 0) { 15717 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15718 removedUsers); 15719 } 15720 } 15721 } 15722 15723 /* 15724 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15725 * flag is not set, the data directory is removed as well. 15726 * make sure this flag is set for partially installed apps. If not its meaningless to 15727 * delete a partially installed application. 15728 */ 15729 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15730 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15731 String packageName = ps.name; 15732 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15733 // Retrieve object to delete permissions for shared user later on 15734 final PackageParser.Package deletedPkg; 15735 final PackageSetting deletedPs; 15736 // reader 15737 synchronized (mPackages) { 15738 deletedPkg = mPackages.get(packageName); 15739 deletedPs = mSettings.mPackages.get(packageName); 15740 if (outInfo != null) { 15741 outInfo.removedPackage = packageName; 15742 outInfo.removedUsers = deletedPs != null 15743 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15744 : null; 15745 } 15746 } 15747 15748 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15749 15750 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15751 final PackageParser.Package resolvedPkg; 15752 if (deletedPkg != null) { 15753 resolvedPkg = deletedPkg; 15754 } else { 15755 // We don't have a parsed package when it lives on an ejected 15756 // adopted storage device, so fake something together 15757 resolvedPkg = new PackageParser.Package(ps.name); 15758 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15759 } 15760 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15761 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15762 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15763 if (outInfo != null) { 15764 outInfo.dataRemoved = true; 15765 } 15766 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15767 } 15768 15769 // writer 15770 synchronized (mPackages) { 15771 if (deletedPs != null) { 15772 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15773 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15774 clearDefaultBrowserIfNeeded(packageName); 15775 if (outInfo != null) { 15776 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15777 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15778 } 15779 updatePermissionsLPw(deletedPs.name, null, 0); 15780 if (deletedPs.sharedUser != null) { 15781 // Remove permissions associated with package. Since runtime 15782 // permissions are per user we have to kill the removed package 15783 // or packages running under the shared user of the removed 15784 // package if revoking the permissions requested only by the removed 15785 // package is successful and this causes a change in gids. 15786 for (int userId : UserManagerService.getInstance().getUserIds()) { 15787 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15788 userId); 15789 if (userIdToKill == UserHandle.USER_ALL 15790 || userIdToKill >= UserHandle.USER_SYSTEM) { 15791 // If gids changed for this user, kill all affected packages. 15792 mHandler.post(new Runnable() { 15793 @Override 15794 public void run() { 15795 // This has to happen with no lock held. 15796 killApplication(deletedPs.name, deletedPs.appId, 15797 KILL_APP_REASON_GIDS_CHANGED); 15798 } 15799 }); 15800 break; 15801 } 15802 } 15803 } 15804 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15805 } 15806 // make sure to preserve per-user disabled state if this removal was just 15807 // a downgrade of a system app to the factory package 15808 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15809 if (DEBUG_REMOVE) { 15810 Slog.d(TAG, "Propagating install state across downgrade"); 15811 } 15812 for (int userId : allUserHandles) { 15813 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15814 if (DEBUG_REMOVE) { 15815 Slog.d(TAG, " user " + userId + " => " + installed); 15816 } 15817 ps.setInstalled(installed, userId); 15818 } 15819 } 15820 } 15821 // can downgrade to reader 15822 if (writeSettings) { 15823 // Save settings now 15824 mSettings.writeLPr(); 15825 } 15826 } 15827 if (outInfo != null) { 15828 // A user ID was deleted here. Go through all users and remove it 15829 // from KeyStore. 15830 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15831 } 15832 } 15833 15834 static boolean locationIsPrivileged(File path) { 15835 try { 15836 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15837 .getCanonicalPath(); 15838 return path.getCanonicalPath().startsWith(privilegedAppDir); 15839 } catch (IOException e) { 15840 Slog.e(TAG, "Unable to access code path " + path); 15841 } 15842 return false; 15843 } 15844 15845 /* 15846 * Tries to delete system package. 15847 */ 15848 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15849 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15850 boolean writeSettings) { 15851 if (deletedPs.parentPackageName != null) { 15852 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15853 return false; 15854 } 15855 15856 final boolean applyUserRestrictions 15857 = (allUserHandles != null) && (outInfo.origUsers != null); 15858 final PackageSetting disabledPs; 15859 // Confirm if the system package has been updated 15860 // An updated system app can be deleted. This will also have to restore 15861 // the system pkg from system partition 15862 // reader 15863 synchronized (mPackages) { 15864 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15865 } 15866 15867 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15868 + " disabledPs=" + disabledPs); 15869 15870 if (disabledPs == null) { 15871 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15872 return false; 15873 } else if (DEBUG_REMOVE) { 15874 Slog.d(TAG, "Deleting system pkg from data partition"); 15875 } 15876 15877 if (DEBUG_REMOVE) { 15878 if (applyUserRestrictions) { 15879 Slog.d(TAG, "Remembering install states:"); 15880 for (int userId : allUserHandles) { 15881 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15882 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15883 } 15884 } 15885 } 15886 15887 // Delete the updated package 15888 outInfo.isRemovedPackageSystemUpdate = true; 15889 if (outInfo.removedChildPackages != null) { 15890 final int childCount = (deletedPs.childPackageNames != null) 15891 ? deletedPs.childPackageNames.size() : 0; 15892 for (int i = 0; i < childCount; i++) { 15893 String childPackageName = deletedPs.childPackageNames.get(i); 15894 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15895 .contains(childPackageName)) { 15896 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15897 childPackageName); 15898 if (childInfo != null) { 15899 childInfo.isRemovedPackageSystemUpdate = true; 15900 } 15901 } 15902 } 15903 } 15904 15905 if (disabledPs.versionCode < deletedPs.versionCode) { 15906 // Delete data for downgrades 15907 flags &= ~PackageManager.DELETE_KEEP_DATA; 15908 } else { 15909 // Preserve data by setting flag 15910 flags |= PackageManager.DELETE_KEEP_DATA; 15911 } 15912 15913 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15914 outInfo, writeSettings, disabledPs.pkg); 15915 if (!ret) { 15916 return false; 15917 } 15918 15919 // writer 15920 synchronized (mPackages) { 15921 // Reinstate the old system package 15922 enableSystemPackageLPw(disabledPs.pkg); 15923 // Remove any native libraries from the upgraded package. 15924 removeNativeBinariesLI(deletedPs); 15925 } 15926 15927 // Install the system package 15928 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15929 int parseFlags = mDefParseFlags 15930 | PackageParser.PARSE_MUST_BE_APK 15931 | PackageParser.PARSE_IS_SYSTEM 15932 | PackageParser.PARSE_IS_SYSTEM_DIR; 15933 if (locationIsPrivileged(disabledPs.codePath)) { 15934 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15935 } 15936 15937 final PackageParser.Package newPkg; 15938 try { 15939 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15940 } catch (PackageManagerException e) { 15941 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15942 + e.getMessage()); 15943 return false; 15944 } 15945 15946 prepareAppDataAfterInstallLIF(newPkg); 15947 15948 // writer 15949 synchronized (mPackages) { 15950 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15951 15952 // Propagate the permissions state as we do not want to drop on the floor 15953 // runtime permissions. The update permissions method below will take 15954 // care of removing obsolete permissions and grant install permissions. 15955 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15956 updatePermissionsLPw(newPkg.packageName, newPkg, 15957 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15958 15959 if (applyUserRestrictions) { 15960 if (DEBUG_REMOVE) { 15961 Slog.d(TAG, "Propagating install state across reinstall"); 15962 } 15963 for (int userId : allUserHandles) { 15964 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15965 if (DEBUG_REMOVE) { 15966 Slog.d(TAG, " user " + userId + " => " + installed); 15967 } 15968 ps.setInstalled(installed, userId); 15969 15970 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15971 } 15972 // Regardless of writeSettings we need to ensure that this restriction 15973 // state propagation is persisted 15974 mSettings.writeAllUsersPackageRestrictionsLPr(); 15975 } 15976 // can downgrade to reader here 15977 if (writeSettings) { 15978 mSettings.writeLPr(); 15979 } 15980 } 15981 return true; 15982 } 15983 15984 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15985 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15986 PackageRemovedInfo outInfo, boolean writeSettings, 15987 PackageParser.Package replacingPackage) { 15988 synchronized (mPackages) { 15989 if (outInfo != null) { 15990 outInfo.uid = ps.appId; 15991 } 15992 15993 if (outInfo != null && outInfo.removedChildPackages != null) { 15994 final int childCount = (ps.childPackageNames != null) 15995 ? ps.childPackageNames.size() : 0; 15996 for (int i = 0; i < childCount; i++) { 15997 String childPackageName = ps.childPackageNames.get(i); 15998 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15999 if (childPs == null) { 16000 return false; 16001 } 16002 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16003 childPackageName); 16004 if (childInfo != null) { 16005 childInfo.uid = childPs.appId; 16006 } 16007 } 16008 } 16009 } 16010 16011 // Delete package data from internal structures and also remove data if flag is set 16012 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16013 16014 // Delete the child packages data 16015 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16016 for (int i = 0; i < childCount; i++) { 16017 PackageSetting childPs; 16018 synchronized (mPackages) { 16019 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16020 } 16021 if (childPs != null) { 16022 PackageRemovedInfo childOutInfo = (outInfo != null 16023 && outInfo.removedChildPackages != null) 16024 ? outInfo.removedChildPackages.get(childPs.name) : null; 16025 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16026 && (replacingPackage != null 16027 && !replacingPackage.hasChildPackage(childPs.name)) 16028 ? flags & ~DELETE_KEEP_DATA : flags; 16029 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16030 deleteFlags, writeSettings); 16031 } 16032 } 16033 16034 // Delete application code and resources only for parent packages 16035 if (ps.parentPackageName == null) { 16036 if (deleteCodeAndResources && (outInfo != null)) { 16037 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16038 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16039 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16040 } 16041 } 16042 16043 return true; 16044 } 16045 16046 @Override 16047 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16048 int userId) { 16049 mContext.enforceCallingOrSelfPermission( 16050 android.Manifest.permission.DELETE_PACKAGES, null); 16051 synchronized (mPackages) { 16052 PackageSetting ps = mSettings.mPackages.get(packageName); 16053 if (ps == null) { 16054 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16055 return false; 16056 } 16057 if (!ps.getInstalled(userId)) { 16058 // Can't block uninstall for an app that is not installed or enabled. 16059 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16060 return false; 16061 } 16062 ps.setBlockUninstall(blockUninstall, userId); 16063 mSettings.writePackageRestrictionsLPr(userId); 16064 } 16065 return true; 16066 } 16067 16068 @Override 16069 public boolean getBlockUninstallForUser(String packageName, int userId) { 16070 synchronized (mPackages) { 16071 PackageSetting ps = mSettings.mPackages.get(packageName); 16072 if (ps == null) { 16073 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16074 return false; 16075 } 16076 return ps.getBlockUninstall(userId); 16077 } 16078 } 16079 16080 @Override 16081 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16082 int callingUid = Binder.getCallingUid(); 16083 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16084 throw new SecurityException( 16085 "setRequiredForSystemUser can only be run by the system or root"); 16086 } 16087 synchronized (mPackages) { 16088 PackageSetting ps = mSettings.mPackages.get(packageName); 16089 if (ps == null) { 16090 Log.w(TAG, "Package doesn't exist: " + packageName); 16091 return false; 16092 } 16093 if (systemUserApp) { 16094 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16095 } else { 16096 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16097 } 16098 mSettings.writeLPr(); 16099 } 16100 return true; 16101 } 16102 16103 /* 16104 * This method handles package deletion in general 16105 */ 16106 private boolean deletePackageLIF(String packageName, UserHandle user, 16107 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16108 PackageRemovedInfo outInfo, boolean writeSettings, 16109 PackageParser.Package replacingPackage) { 16110 if (packageName == null) { 16111 Slog.w(TAG, "Attempt to delete null packageName."); 16112 return false; 16113 } 16114 16115 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16116 16117 PackageSetting ps; 16118 16119 synchronized (mPackages) { 16120 ps = mSettings.mPackages.get(packageName); 16121 if (ps == null) { 16122 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16123 return false; 16124 } 16125 16126 if (ps.parentPackageName != null && (!isSystemApp(ps) 16127 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16128 if (DEBUG_REMOVE) { 16129 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16130 + ((user == null) ? UserHandle.USER_ALL : user)); 16131 } 16132 final int removedUserId = (user != null) ? user.getIdentifier() 16133 : UserHandle.USER_ALL; 16134 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16135 return false; 16136 } 16137 markPackageUninstalledForUserLPw(ps, user); 16138 scheduleWritePackageRestrictionsLocked(user); 16139 return true; 16140 } 16141 } 16142 16143 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16144 && user.getIdentifier() != UserHandle.USER_ALL)) { 16145 // The caller is asking that the package only be deleted for a single 16146 // user. To do this, we just mark its uninstalled state and delete 16147 // its data. If this is a system app, we only allow this to happen if 16148 // they have set the special DELETE_SYSTEM_APP which requests different 16149 // semantics than normal for uninstalling system apps. 16150 markPackageUninstalledForUserLPw(ps, user); 16151 16152 if (!isSystemApp(ps)) { 16153 // Do not uninstall the APK if an app should be cached 16154 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16155 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16156 // Other user still have this package installed, so all 16157 // we need to do is clear this user's data and save that 16158 // it is uninstalled. 16159 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16160 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16161 return false; 16162 } 16163 scheduleWritePackageRestrictionsLocked(user); 16164 return true; 16165 } else { 16166 // We need to set it back to 'installed' so the uninstall 16167 // broadcasts will be sent correctly. 16168 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16169 ps.setInstalled(true, user.getIdentifier()); 16170 } 16171 } else { 16172 // This is a system app, so we assume that the 16173 // other users still have this package installed, so all 16174 // we need to do is clear this user's data and save that 16175 // it is uninstalled. 16176 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16177 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16178 return false; 16179 } 16180 scheduleWritePackageRestrictionsLocked(user); 16181 return true; 16182 } 16183 } 16184 16185 // If we are deleting a composite package for all users, keep track 16186 // of result for each child. 16187 if (ps.childPackageNames != null && outInfo != null) { 16188 synchronized (mPackages) { 16189 final int childCount = ps.childPackageNames.size(); 16190 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16191 for (int i = 0; i < childCount; i++) { 16192 String childPackageName = ps.childPackageNames.get(i); 16193 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16194 childInfo.removedPackage = childPackageName; 16195 outInfo.removedChildPackages.put(childPackageName, childInfo); 16196 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16197 if (childPs != null) { 16198 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16199 } 16200 } 16201 } 16202 } 16203 16204 boolean ret = false; 16205 if (isSystemApp(ps)) { 16206 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16207 // When an updated system application is deleted we delete the existing resources 16208 // as well and fall back to existing code in system partition 16209 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16210 } else { 16211 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16212 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16213 outInfo, writeSettings, replacingPackage); 16214 } 16215 16216 // Take a note whether we deleted the package for all users 16217 if (outInfo != null) { 16218 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16219 if (outInfo.removedChildPackages != null) { 16220 synchronized (mPackages) { 16221 final int childCount = outInfo.removedChildPackages.size(); 16222 for (int i = 0; i < childCount; i++) { 16223 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16224 if (childInfo != null) { 16225 childInfo.removedForAllUsers = mPackages.get( 16226 childInfo.removedPackage) == null; 16227 } 16228 } 16229 } 16230 } 16231 // If we uninstalled an update to a system app there may be some 16232 // child packages that appeared as they are declared in the system 16233 // app but were not declared in the update. 16234 if (isSystemApp(ps)) { 16235 synchronized (mPackages) { 16236 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16237 final int childCount = (updatedPs.childPackageNames != null) 16238 ? updatedPs.childPackageNames.size() : 0; 16239 for (int i = 0; i < childCount; i++) { 16240 String childPackageName = updatedPs.childPackageNames.get(i); 16241 if (outInfo.removedChildPackages == null 16242 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16243 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16244 if (childPs == null) { 16245 continue; 16246 } 16247 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16248 installRes.name = childPackageName; 16249 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16250 installRes.pkg = mPackages.get(childPackageName); 16251 installRes.uid = childPs.pkg.applicationInfo.uid; 16252 if (outInfo.appearedChildPackages == null) { 16253 outInfo.appearedChildPackages = new ArrayMap<>(); 16254 } 16255 outInfo.appearedChildPackages.put(childPackageName, installRes); 16256 } 16257 } 16258 } 16259 } 16260 } 16261 16262 return ret; 16263 } 16264 16265 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16266 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16267 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16268 for (int nextUserId : userIds) { 16269 if (DEBUG_REMOVE) { 16270 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16271 } 16272 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16273 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16274 false /*hidden*/, false /*suspended*/, null, null, null, 16275 false /*blockUninstall*/, 16276 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16277 } 16278 } 16279 16280 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16281 PackageRemovedInfo outInfo) { 16282 final PackageParser.Package pkg; 16283 synchronized (mPackages) { 16284 pkg = mPackages.get(ps.name); 16285 } 16286 16287 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16288 : new int[] {userId}; 16289 for (int nextUserId : userIds) { 16290 if (DEBUG_REMOVE) { 16291 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16292 + nextUserId); 16293 } 16294 16295 destroyAppDataLIF(pkg, userId, 16296 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16297 destroyAppProfilesLIF(pkg, userId); 16298 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16299 schedulePackageCleaning(ps.name, nextUserId, false); 16300 synchronized (mPackages) { 16301 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16302 scheduleWritePackageRestrictionsLocked(nextUserId); 16303 } 16304 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16305 } 16306 } 16307 16308 if (outInfo != null) { 16309 outInfo.removedPackage = ps.name; 16310 outInfo.removedAppId = ps.appId; 16311 outInfo.removedUsers = userIds; 16312 } 16313 16314 return true; 16315 } 16316 16317 private final class ClearStorageConnection implements ServiceConnection { 16318 IMediaContainerService mContainerService; 16319 16320 @Override 16321 public void onServiceConnected(ComponentName name, IBinder service) { 16322 synchronized (this) { 16323 mContainerService = IMediaContainerService.Stub.asInterface(service); 16324 notifyAll(); 16325 } 16326 } 16327 16328 @Override 16329 public void onServiceDisconnected(ComponentName name) { 16330 } 16331 } 16332 16333 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16334 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16335 16336 final boolean mounted; 16337 if (Environment.isExternalStorageEmulated()) { 16338 mounted = true; 16339 } else { 16340 final String status = Environment.getExternalStorageState(); 16341 16342 mounted = status.equals(Environment.MEDIA_MOUNTED) 16343 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16344 } 16345 16346 if (!mounted) { 16347 return; 16348 } 16349 16350 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16351 int[] users; 16352 if (userId == UserHandle.USER_ALL) { 16353 users = sUserManager.getUserIds(); 16354 } else { 16355 users = new int[] { userId }; 16356 } 16357 final ClearStorageConnection conn = new ClearStorageConnection(); 16358 if (mContext.bindServiceAsUser( 16359 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16360 try { 16361 for (int curUser : users) { 16362 long timeout = SystemClock.uptimeMillis() + 5000; 16363 synchronized (conn) { 16364 long now; 16365 while (conn.mContainerService == null && 16366 (now = SystemClock.uptimeMillis()) < timeout) { 16367 try { 16368 conn.wait(timeout - now); 16369 } catch (InterruptedException e) { 16370 } 16371 } 16372 } 16373 if (conn.mContainerService == null) { 16374 return; 16375 } 16376 16377 final UserEnvironment userEnv = new UserEnvironment(curUser); 16378 clearDirectory(conn.mContainerService, 16379 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16380 if (allData) { 16381 clearDirectory(conn.mContainerService, 16382 userEnv.buildExternalStorageAppDataDirs(packageName)); 16383 clearDirectory(conn.mContainerService, 16384 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16385 } 16386 } 16387 } finally { 16388 mContext.unbindService(conn); 16389 } 16390 } 16391 } 16392 16393 @Override 16394 public void clearApplicationProfileData(String packageName) { 16395 enforceSystemOrRoot("Only the system can clear all profile data"); 16396 16397 final PackageParser.Package pkg; 16398 synchronized (mPackages) { 16399 pkg = mPackages.get(packageName); 16400 } 16401 16402 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16403 synchronized (mInstallLock) { 16404 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16405 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16406 true /* removeBaseMarker */); 16407 } 16408 } 16409 } 16410 16411 @Override 16412 public void clearApplicationUserData(final String packageName, 16413 final IPackageDataObserver observer, final int userId) { 16414 mContext.enforceCallingOrSelfPermission( 16415 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16416 16417 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16418 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16419 16420 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16421 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16422 } 16423 // Queue up an async operation since the package deletion may take a little while. 16424 mHandler.post(new Runnable() { 16425 public void run() { 16426 mHandler.removeCallbacks(this); 16427 final boolean succeeded; 16428 try (PackageFreezer freezer = freezePackage(packageName, 16429 "clearApplicationUserData")) { 16430 synchronized (mInstallLock) { 16431 succeeded = clearApplicationUserDataLIF(packageName, userId); 16432 } 16433 clearExternalStorageDataSync(packageName, userId, true); 16434 } 16435 if (succeeded) { 16436 // invoke DeviceStorageMonitor's update method to clear any notifications 16437 DeviceStorageMonitorInternal dsm = LocalServices 16438 .getService(DeviceStorageMonitorInternal.class); 16439 if (dsm != null) { 16440 dsm.checkMemory(); 16441 } 16442 } 16443 if(observer != null) { 16444 try { 16445 observer.onRemoveCompleted(packageName, succeeded); 16446 } catch (RemoteException e) { 16447 Log.i(TAG, "Observer no longer exists."); 16448 } 16449 } //end if observer 16450 } //end run 16451 }); 16452 } 16453 16454 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16455 if (packageName == null) { 16456 Slog.w(TAG, "Attempt to delete null packageName."); 16457 return false; 16458 } 16459 16460 // Try finding details about the requested package 16461 PackageParser.Package pkg; 16462 synchronized (mPackages) { 16463 pkg = mPackages.get(packageName); 16464 if (pkg == null) { 16465 final PackageSetting ps = mSettings.mPackages.get(packageName); 16466 if (ps != null) { 16467 pkg = ps.pkg; 16468 } 16469 } 16470 16471 if (pkg == null) { 16472 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16473 return false; 16474 } 16475 16476 PackageSetting ps = (PackageSetting) pkg.mExtras; 16477 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16478 } 16479 16480 clearAppDataLIF(pkg, userId, 16481 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16482 16483 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16484 removeKeystoreDataIfNeeded(userId, appId); 16485 16486 UserManagerInternal umInternal = getUserManagerInternal(); 16487 final int flags; 16488 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16489 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16490 } else if (umInternal.isUserRunning(userId)) { 16491 flags = StorageManager.FLAG_STORAGE_DE; 16492 } else { 16493 flags = 0; 16494 } 16495 prepareAppDataContentsLIF(pkg, userId, flags); 16496 16497 return true; 16498 } 16499 16500 /** 16501 * Reverts user permission state changes (permissions and flags) in 16502 * all packages for a given user. 16503 * 16504 * @param userId The device user for which to do a reset. 16505 */ 16506 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16507 final int packageCount = mPackages.size(); 16508 for (int i = 0; i < packageCount; i++) { 16509 PackageParser.Package pkg = mPackages.valueAt(i); 16510 PackageSetting ps = (PackageSetting) pkg.mExtras; 16511 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16512 } 16513 } 16514 16515 private void resetNetworkPolicies(int userId) { 16516 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16517 } 16518 16519 /** 16520 * Reverts user permission state changes (permissions and flags). 16521 * 16522 * @param ps The package for which to reset. 16523 * @param userId The device user for which to do a reset. 16524 */ 16525 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16526 final PackageSetting ps, final int userId) { 16527 if (ps.pkg == null) { 16528 return; 16529 } 16530 16531 // These are flags that can change base on user actions. 16532 final int userSettableMask = FLAG_PERMISSION_USER_SET 16533 | FLAG_PERMISSION_USER_FIXED 16534 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16535 | FLAG_PERMISSION_REVIEW_REQUIRED; 16536 16537 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16538 | FLAG_PERMISSION_POLICY_FIXED; 16539 16540 boolean writeInstallPermissions = false; 16541 boolean writeRuntimePermissions = false; 16542 16543 final int permissionCount = ps.pkg.requestedPermissions.size(); 16544 for (int i = 0; i < permissionCount; i++) { 16545 String permission = ps.pkg.requestedPermissions.get(i); 16546 16547 BasePermission bp = mSettings.mPermissions.get(permission); 16548 if (bp == null) { 16549 continue; 16550 } 16551 16552 // If shared user we just reset the state to which only this app contributed. 16553 if (ps.sharedUser != null) { 16554 boolean used = false; 16555 final int packageCount = ps.sharedUser.packages.size(); 16556 for (int j = 0; j < packageCount; j++) { 16557 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16558 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16559 && pkg.pkg.requestedPermissions.contains(permission)) { 16560 used = true; 16561 break; 16562 } 16563 } 16564 if (used) { 16565 continue; 16566 } 16567 } 16568 16569 PermissionsState permissionsState = ps.getPermissionsState(); 16570 16571 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16572 16573 // Always clear the user settable flags. 16574 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16575 bp.name) != null; 16576 // If permission review is enabled and this is a legacy app, mark the 16577 // permission as requiring a review as this is the initial state. 16578 int flags = 0; 16579 if (Build.PERMISSIONS_REVIEW_REQUIRED 16580 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16581 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16582 } 16583 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16584 if (hasInstallState) { 16585 writeInstallPermissions = true; 16586 } else { 16587 writeRuntimePermissions = true; 16588 } 16589 } 16590 16591 // Below is only runtime permission handling. 16592 if (!bp.isRuntime()) { 16593 continue; 16594 } 16595 16596 // Never clobber system or policy. 16597 if ((oldFlags & policyOrSystemFlags) != 0) { 16598 continue; 16599 } 16600 16601 // If this permission was granted by default, make sure it is. 16602 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16603 if (permissionsState.grantRuntimePermission(bp, userId) 16604 != PERMISSION_OPERATION_FAILURE) { 16605 writeRuntimePermissions = true; 16606 } 16607 // If permission review is enabled the permissions for a legacy apps 16608 // are represented as constantly granted runtime ones, so don't revoke. 16609 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16610 // Otherwise, reset the permission. 16611 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16612 switch (revokeResult) { 16613 case PERMISSION_OPERATION_SUCCESS: 16614 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16615 writeRuntimePermissions = true; 16616 final int appId = ps.appId; 16617 mHandler.post(new Runnable() { 16618 @Override 16619 public void run() { 16620 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16621 } 16622 }); 16623 } break; 16624 } 16625 } 16626 } 16627 16628 // Synchronously write as we are taking permissions away. 16629 if (writeRuntimePermissions) { 16630 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16631 } 16632 16633 // Synchronously write as we are taking permissions away. 16634 if (writeInstallPermissions) { 16635 mSettings.writeLPr(); 16636 } 16637 } 16638 16639 /** 16640 * Remove entries from the keystore daemon. Will only remove it if the 16641 * {@code appId} is valid. 16642 */ 16643 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16644 if (appId < 0) { 16645 return; 16646 } 16647 16648 final KeyStore keyStore = KeyStore.getInstance(); 16649 if (keyStore != null) { 16650 if (userId == UserHandle.USER_ALL) { 16651 for (final int individual : sUserManager.getUserIds()) { 16652 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16653 } 16654 } else { 16655 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16656 } 16657 } else { 16658 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16659 } 16660 } 16661 16662 @Override 16663 public void deleteApplicationCacheFiles(final String packageName, 16664 final IPackageDataObserver observer) { 16665 final int userId = UserHandle.getCallingUserId(); 16666 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16667 } 16668 16669 @Override 16670 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16671 final IPackageDataObserver observer) { 16672 mContext.enforceCallingOrSelfPermission( 16673 android.Manifest.permission.DELETE_CACHE_FILES, null); 16674 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16675 /* requireFullPermission= */ true, /* checkShell= */ false, 16676 "delete application cache files"); 16677 16678 final PackageParser.Package pkg; 16679 synchronized (mPackages) { 16680 pkg = mPackages.get(packageName); 16681 } 16682 16683 // Queue up an async operation since the package deletion may take a little while. 16684 mHandler.post(new Runnable() { 16685 public void run() { 16686 synchronized (mInstallLock) { 16687 final int flags = StorageManager.FLAG_STORAGE_DE 16688 | StorageManager.FLAG_STORAGE_CE; 16689 // We're only clearing cache files, so we don't care if the 16690 // app is unfrozen and still able to run 16691 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16692 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16693 } 16694 clearExternalStorageDataSync(packageName, userId, false); 16695 if (observer != null) { 16696 try { 16697 observer.onRemoveCompleted(packageName, true); 16698 } catch (RemoteException e) { 16699 Log.i(TAG, "Observer no longer exists."); 16700 } 16701 } 16702 } 16703 }); 16704 } 16705 16706 @Override 16707 public void getPackageSizeInfo(final String packageName, int userHandle, 16708 final IPackageStatsObserver observer) { 16709 mContext.enforceCallingOrSelfPermission( 16710 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16711 if (packageName == null) { 16712 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16713 } 16714 16715 PackageStats stats = new PackageStats(packageName, userHandle); 16716 16717 /* 16718 * Queue up an async operation since the package measurement may take a 16719 * little while. 16720 */ 16721 Message msg = mHandler.obtainMessage(INIT_COPY); 16722 msg.obj = new MeasureParams(stats, observer); 16723 mHandler.sendMessage(msg); 16724 } 16725 16726 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16727 final PackageSetting ps; 16728 synchronized (mPackages) { 16729 ps = mSettings.mPackages.get(packageName); 16730 if (ps == null) { 16731 Slog.w(TAG, "Failed to find settings for " + packageName); 16732 return false; 16733 } 16734 } 16735 try { 16736 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16737 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16738 ps.getCeDataInode(userId), ps.codePathString, stats); 16739 } catch (InstallerException e) { 16740 Slog.w(TAG, String.valueOf(e)); 16741 return false; 16742 } 16743 16744 // For now, ignore code size of packages on system partition 16745 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16746 stats.codeSize = 0; 16747 } 16748 16749 return true; 16750 } 16751 16752 private int getUidTargetSdkVersionLockedLPr(int uid) { 16753 Object obj = mSettings.getUserIdLPr(uid); 16754 if (obj instanceof SharedUserSetting) { 16755 final SharedUserSetting sus = (SharedUserSetting) obj; 16756 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16757 final Iterator<PackageSetting> it = sus.packages.iterator(); 16758 while (it.hasNext()) { 16759 final PackageSetting ps = it.next(); 16760 if (ps.pkg != null) { 16761 int v = ps.pkg.applicationInfo.targetSdkVersion; 16762 if (v < vers) vers = v; 16763 } 16764 } 16765 return vers; 16766 } else if (obj instanceof PackageSetting) { 16767 final PackageSetting ps = (PackageSetting) obj; 16768 if (ps.pkg != null) { 16769 return ps.pkg.applicationInfo.targetSdkVersion; 16770 } 16771 } 16772 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16773 } 16774 16775 @Override 16776 public void addPreferredActivity(IntentFilter filter, int match, 16777 ComponentName[] set, ComponentName activity, int userId) { 16778 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16779 "Adding preferred"); 16780 } 16781 16782 private void addPreferredActivityInternal(IntentFilter filter, int match, 16783 ComponentName[] set, ComponentName activity, boolean always, int userId, 16784 String opname) { 16785 // writer 16786 int callingUid = Binder.getCallingUid(); 16787 enforceCrossUserPermission(callingUid, userId, 16788 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16789 if (filter.countActions() == 0) { 16790 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16791 return; 16792 } 16793 synchronized (mPackages) { 16794 if (mContext.checkCallingOrSelfPermission( 16795 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16796 != PackageManager.PERMISSION_GRANTED) { 16797 if (getUidTargetSdkVersionLockedLPr(callingUid) 16798 < Build.VERSION_CODES.FROYO) { 16799 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16800 + callingUid); 16801 return; 16802 } 16803 mContext.enforceCallingOrSelfPermission( 16804 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16805 } 16806 16807 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16808 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16809 + userId + ":"); 16810 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16811 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16812 scheduleWritePackageRestrictionsLocked(userId); 16813 } 16814 } 16815 16816 @Override 16817 public void replacePreferredActivity(IntentFilter filter, int match, 16818 ComponentName[] set, ComponentName activity, int userId) { 16819 if (filter.countActions() != 1) { 16820 throw new IllegalArgumentException( 16821 "replacePreferredActivity expects filter to have only 1 action."); 16822 } 16823 if (filter.countDataAuthorities() != 0 16824 || filter.countDataPaths() != 0 16825 || filter.countDataSchemes() > 1 16826 || filter.countDataTypes() != 0) { 16827 throw new IllegalArgumentException( 16828 "replacePreferredActivity expects filter to have no data authorities, " + 16829 "paths, or types; and at most one scheme."); 16830 } 16831 16832 final int callingUid = Binder.getCallingUid(); 16833 enforceCrossUserPermission(callingUid, userId, 16834 true /* requireFullPermission */, false /* checkShell */, 16835 "replace preferred activity"); 16836 synchronized (mPackages) { 16837 if (mContext.checkCallingOrSelfPermission( 16838 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16839 != PackageManager.PERMISSION_GRANTED) { 16840 if (getUidTargetSdkVersionLockedLPr(callingUid) 16841 < Build.VERSION_CODES.FROYO) { 16842 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16843 + Binder.getCallingUid()); 16844 return; 16845 } 16846 mContext.enforceCallingOrSelfPermission( 16847 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16848 } 16849 16850 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16851 if (pir != null) { 16852 // Get all of the existing entries that exactly match this filter. 16853 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16854 if (existing != null && existing.size() == 1) { 16855 PreferredActivity cur = existing.get(0); 16856 if (DEBUG_PREFERRED) { 16857 Slog.i(TAG, "Checking replace of preferred:"); 16858 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16859 if (!cur.mPref.mAlways) { 16860 Slog.i(TAG, " -- CUR; not mAlways!"); 16861 } else { 16862 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16863 Slog.i(TAG, " -- CUR: mSet=" 16864 + Arrays.toString(cur.mPref.mSetComponents)); 16865 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16866 Slog.i(TAG, " -- NEW: mMatch=" 16867 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16868 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16869 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16870 } 16871 } 16872 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16873 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16874 && cur.mPref.sameSet(set)) { 16875 // Setting the preferred activity to what it happens to be already 16876 if (DEBUG_PREFERRED) { 16877 Slog.i(TAG, "Replacing with same preferred activity " 16878 + cur.mPref.mShortComponent + " for user " 16879 + userId + ":"); 16880 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16881 } 16882 return; 16883 } 16884 } 16885 16886 if (existing != null) { 16887 if (DEBUG_PREFERRED) { 16888 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16889 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16890 } 16891 for (int i = 0; i < existing.size(); i++) { 16892 PreferredActivity pa = existing.get(i); 16893 if (DEBUG_PREFERRED) { 16894 Slog.i(TAG, "Removing existing preferred activity " 16895 + pa.mPref.mComponent + ":"); 16896 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16897 } 16898 pir.removeFilter(pa); 16899 } 16900 } 16901 } 16902 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16903 "Replacing preferred"); 16904 } 16905 } 16906 16907 @Override 16908 public void clearPackagePreferredActivities(String packageName) { 16909 final int uid = Binder.getCallingUid(); 16910 // writer 16911 synchronized (mPackages) { 16912 PackageParser.Package pkg = mPackages.get(packageName); 16913 if (pkg == null || pkg.applicationInfo.uid != uid) { 16914 if (mContext.checkCallingOrSelfPermission( 16915 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16916 != PackageManager.PERMISSION_GRANTED) { 16917 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16918 < Build.VERSION_CODES.FROYO) { 16919 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16920 + Binder.getCallingUid()); 16921 return; 16922 } 16923 mContext.enforceCallingOrSelfPermission( 16924 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16925 } 16926 } 16927 16928 int user = UserHandle.getCallingUserId(); 16929 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16930 scheduleWritePackageRestrictionsLocked(user); 16931 } 16932 } 16933 } 16934 16935 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16936 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16937 ArrayList<PreferredActivity> removed = null; 16938 boolean changed = false; 16939 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16940 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16941 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16942 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16943 continue; 16944 } 16945 Iterator<PreferredActivity> it = pir.filterIterator(); 16946 while (it.hasNext()) { 16947 PreferredActivity pa = it.next(); 16948 // Mark entry for removal only if it matches the package name 16949 // and the entry is of type "always". 16950 if (packageName == null || 16951 (pa.mPref.mComponent.getPackageName().equals(packageName) 16952 && pa.mPref.mAlways)) { 16953 if (removed == null) { 16954 removed = new ArrayList<PreferredActivity>(); 16955 } 16956 removed.add(pa); 16957 } 16958 } 16959 if (removed != null) { 16960 for (int j=0; j<removed.size(); j++) { 16961 PreferredActivity pa = removed.get(j); 16962 pir.removeFilter(pa); 16963 } 16964 changed = true; 16965 } 16966 } 16967 return changed; 16968 } 16969 16970 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16971 private void clearIntentFilterVerificationsLPw(int userId) { 16972 final int packageCount = mPackages.size(); 16973 for (int i = 0; i < packageCount; i++) { 16974 PackageParser.Package pkg = mPackages.valueAt(i); 16975 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16976 } 16977 } 16978 16979 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16980 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16981 if (userId == UserHandle.USER_ALL) { 16982 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16983 sUserManager.getUserIds())) { 16984 for (int oneUserId : sUserManager.getUserIds()) { 16985 scheduleWritePackageRestrictionsLocked(oneUserId); 16986 } 16987 } 16988 } else { 16989 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16990 scheduleWritePackageRestrictionsLocked(userId); 16991 } 16992 } 16993 } 16994 16995 void clearDefaultBrowserIfNeeded(String packageName) { 16996 for (int oneUserId : sUserManager.getUserIds()) { 16997 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16998 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16999 if (packageName.equals(defaultBrowserPackageName)) { 17000 setDefaultBrowserPackageName(null, oneUserId); 17001 } 17002 } 17003 } 17004 17005 @Override 17006 public void resetApplicationPreferences(int userId) { 17007 mContext.enforceCallingOrSelfPermission( 17008 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17009 final long identity = Binder.clearCallingIdentity(); 17010 // writer 17011 try { 17012 synchronized (mPackages) { 17013 clearPackagePreferredActivitiesLPw(null, userId); 17014 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17015 // TODO: We have to reset the default SMS and Phone. This requires 17016 // significant refactoring to keep all default apps in the package 17017 // manager (cleaner but more work) or have the services provide 17018 // callbacks to the package manager to request a default app reset. 17019 applyFactoryDefaultBrowserLPw(userId); 17020 clearIntentFilterVerificationsLPw(userId); 17021 primeDomainVerificationsLPw(userId); 17022 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17023 scheduleWritePackageRestrictionsLocked(userId); 17024 } 17025 resetNetworkPolicies(userId); 17026 } finally { 17027 Binder.restoreCallingIdentity(identity); 17028 } 17029 } 17030 17031 @Override 17032 public int getPreferredActivities(List<IntentFilter> outFilters, 17033 List<ComponentName> outActivities, String packageName) { 17034 17035 int num = 0; 17036 final int userId = UserHandle.getCallingUserId(); 17037 // reader 17038 synchronized (mPackages) { 17039 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17040 if (pir != null) { 17041 final Iterator<PreferredActivity> it = pir.filterIterator(); 17042 while (it.hasNext()) { 17043 final PreferredActivity pa = it.next(); 17044 if (packageName == null 17045 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17046 && pa.mPref.mAlways)) { 17047 if (outFilters != null) { 17048 outFilters.add(new IntentFilter(pa)); 17049 } 17050 if (outActivities != null) { 17051 outActivities.add(pa.mPref.mComponent); 17052 } 17053 } 17054 } 17055 } 17056 } 17057 17058 return num; 17059 } 17060 17061 @Override 17062 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17063 int userId) { 17064 int callingUid = Binder.getCallingUid(); 17065 if (callingUid != Process.SYSTEM_UID) { 17066 throw new SecurityException( 17067 "addPersistentPreferredActivity can only be run by the system"); 17068 } 17069 if (filter.countActions() == 0) { 17070 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17071 return; 17072 } 17073 synchronized (mPackages) { 17074 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17075 ":"); 17076 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17077 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17078 new PersistentPreferredActivity(filter, activity)); 17079 scheduleWritePackageRestrictionsLocked(userId); 17080 } 17081 } 17082 17083 @Override 17084 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17085 int callingUid = Binder.getCallingUid(); 17086 if (callingUid != Process.SYSTEM_UID) { 17087 throw new SecurityException( 17088 "clearPackagePersistentPreferredActivities can only be run by the system"); 17089 } 17090 ArrayList<PersistentPreferredActivity> removed = null; 17091 boolean changed = false; 17092 synchronized (mPackages) { 17093 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17094 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17095 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17096 .valueAt(i); 17097 if (userId != thisUserId) { 17098 continue; 17099 } 17100 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17101 while (it.hasNext()) { 17102 PersistentPreferredActivity ppa = it.next(); 17103 // Mark entry for removal only if it matches the package name. 17104 if (ppa.mComponent.getPackageName().equals(packageName)) { 17105 if (removed == null) { 17106 removed = new ArrayList<PersistentPreferredActivity>(); 17107 } 17108 removed.add(ppa); 17109 } 17110 } 17111 if (removed != null) { 17112 for (int j=0; j<removed.size(); j++) { 17113 PersistentPreferredActivity ppa = removed.get(j); 17114 ppir.removeFilter(ppa); 17115 } 17116 changed = true; 17117 } 17118 } 17119 17120 if (changed) { 17121 scheduleWritePackageRestrictionsLocked(userId); 17122 } 17123 } 17124 } 17125 17126 /** 17127 * Common machinery for picking apart a restored XML blob and passing 17128 * it to a caller-supplied functor to be applied to the running system. 17129 */ 17130 private void restoreFromXml(XmlPullParser parser, int userId, 17131 String expectedStartTag, BlobXmlRestorer functor) 17132 throws IOException, XmlPullParserException { 17133 int type; 17134 while ((type = parser.next()) != XmlPullParser.START_TAG 17135 && type != XmlPullParser.END_DOCUMENT) { 17136 } 17137 if (type != XmlPullParser.START_TAG) { 17138 // oops didn't find a start tag?! 17139 if (DEBUG_BACKUP) { 17140 Slog.e(TAG, "Didn't find start tag during restore"); 17141 } 17142 return; 17143 } 17144Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17145 // this is supposed to be TAG_PREFERRED_BACKUP 17146 if (!expectedStartTag.equals(parser.getName())) { 17147 if (DEBUG_BACKUP) { 17148 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17149 } 17150 return; 17151 } 17152 17153 // skip interfering stuff, then we're aligned with the backing implementation 17154 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17155Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17156 functor.apply(parser, userId); 17157 } 17158 17159 private interface BlobXmlRestorer { 17160 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17161 } 17162 17163 /** 17164 * Non-Binder method, support for the backup/restore mechanism: write the 17165 * full set of preferred activities in its canonical XML format. Returns the 17166 * XML output as a byte array, or null if there is none. 17167 */ 17168 @Override 17169 public byte[] getPreferredActivityBackup(int userId) { 17170 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17171 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17172 } 17173 17174 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17175 try { 17176 final XmlSerializer serializer = new FastXmlSerializer(); 17177 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17178 serializer.startDocument(null, true); 17179 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17180 17181 synchronized (mPackages) { 17182 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17183 } 17184 17185 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17186 serializer.endDocument(); 17187 serializer.flush(); 17188 } catch (Exception e) { 17189 if (DEBUG_BACKUP) { 17190 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17191 } 17192 return null; 17193 } 17194 17195 return dataStream.toByteArray(); 17196 } 17197 17198 @Override 17199 public void restorePreferredActivities(byte[] backup, int userId) { 17200 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17201 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17202 } 17203 17204 try { 17205 final XmlPullParser parser = Xml.newPullParser(); 17206 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17207 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17208 new BlobXmlRestorer() { 17209 @Override 17210 public void apply(XmlPullParser parser, int userId) 17211 throws XmlPullParserException, IOException { 17212 synchronized (mPackages) { 17213 mSettings.readPreferredActivitiesLPw(parser, userId); 17214 } 17215 } 17216 } ); 17217 } catch (Exception e) { 17218 if (DEBUG_BACKUP) { 17219 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17220 } 17221 } 17222 } 17223 17224 /** 17225 * Non-Binder method, support for the backup/restore mechanism: write the 17226 * default browser (etc) settings in its canonical XML format. Returns the default 17227 * browser XML representation as a byte array, or null if there is none. 17228 */ 17229 @Override 17230 public byte[] getDefaultAppsBackup(int userId) { 17231 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17232 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17233 } 17234 17235 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17236 try { 17237 final XmlSerializer serializer = new FastXmlSerializer(); 17238 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17239 serializer.startDocument(null, true); 17240 serializer.startTag(null, TAG_DEFAULT_APPS); 17241 17242 synchronized (mPackages) { 17243 mSettings.writeDefaultAppsLPr(serializer, userId); 17244 } 17245 17246 serializer.endTag(null, TAG_DEFAULT_APPS); 17247 serializer.endDocument(); 17248 serializer.flush(); 17249 } catch (Exception e) { 17250 if (DEBUG_BACKUP) { 17251 Slog.e(TAG, "Unable to write default apps for backup", e); 17252 } 17253 return null; 17254 } 17255 17256 return dataStream.toByteArray(); 17257 } 17258 17259 @Override 17260 public void restoreDefaultApps(byte[] backup, int userId) { 17261 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17262 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17263 } 17264 17265 try { 17266 final XmlPullParser parser = Xml.newPullParser(); 17267 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17268 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17269 new BlobXmlRestorer() { 17270 @Override 17271 public void apply(XmlPullParser parser, int userId) 17272 throws XmlPullParserException, IOException { 17273 synchronized (mPackages) { 17274 mSettings.readDefaultAppsLPw(parser, userId); 17275 } 17276 } 17277 } ); 17278 } catch (Exception e) { 17279 if (DEBUG_BACKUP) { 17280 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17281 } 17282 } 17283 } 17284 17285 @Override 17286 public byte[] getIntentFilterVerificationBackup(int userId) { 17287 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17288 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17289 } 17290 17291 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17292 try { 17293 final XmlSerializer serializer = new FastXmlSerializer(); 17294 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17295 serializer.startDocument(null, true); 17296 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17297 17298 synchronized (mPackages) { 17299 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17300 } 17301 17302 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17303 serializer.endDocument(); 17304 serializer.flush(); 17305 } catch (Exception e) { 17306 if (DEBUG_BACKUP) { 17307 Slog.e(TAG, "Unable to write default apps for backup", e); 17308 } 17309 return null; 17310 } 17311 17312 return dataStream.toByteArray(); 17313 } 17314 17315 @Override 17316 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17317 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17318 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17319 } 17320 17321 try { 17322 final XmlPullParser parser = Xml.newPullParser(); 17323 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17324 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17325 new BlobXmlRestorer() { 17326 @Override 17327 public void apply(XmlPullParser parser, int userId) 17328 throws XmlPullParserException, IOException { 17329 synchronized (mPackages) { 17330 mSettings.readAllDomainVerificationsLPr(parser, userId); 17331 mSettings.writeLPr(); 17332 } 17333 } 17334 } ); 17335 } catch (Exception e) { 17336 if (DEBUG_BACKUP) { 17337 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17338 } 17339 } 17340 } 17341 17342 @Override 17343 public byte[] getPermissionGrantBackup(int userId) { 17344 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17345 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17346 } 17347 17348 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17349 try { 17350 final XmlSerializer serializer = new FastXmlSerializer(); 17351 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17352 serializer.startDocument(null, true); 17353 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17354 17355 synchronized (mPackages) { 17356 serializeRuntimePermissionGrantsLPr(serializer, userId); 17357 } 17358 17359 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17360 serializer.endDocument(); 17361 serializer.flush(); 17362 } catch (Exception e) { 17363 if (DEBUG_BACKUP) { 17364 Slog.e(TAG, "Unable to write default apps for backup", e); 17365 } 17366 return null; 17367 } 17368 17369 return dataStream.toByteArray(); 17370 } 17371 17372 @Override 17373 public void restorePermissionGrants(byte[] backup, int userId) { 17374 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17375 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17376 } 17377 17378 try { 17379 final XmlPullParser parser = Xml.newPullParser(); 17380 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17381 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17382 new BlobXmlRestorer() { 17383 @Override 17384 public void apply(XmlPullParser parser, int userId) 17385 throws XmlPullParserException, IOException { 17386 synchronized (mPackages) { 17387 processRestoredPermissionGrantsLPr(parser, userId); 17388 } 17389 } 17390 } ); 17391 } catch (Exception e) { 17392 if (DEBUG_BACKUP) { 17393 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17394 } 17395 } 17396 } 17397 17398 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17399 throws IOException { 17400 serializer.startTag(null, TAG_ALL_GRANTS); 17401 17402 final int N = mSettings.mPackages.size(); 17403 for (int i = 0; i < N; i++) { 17404 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17405 boolean pkgGrantsKnown = false; 17406 17407 PermissionsState packagePerms = ps.getPermissionsState(); 17408 17409 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17410 final int grantFlags = state.getFlags(); 17411 // only look at grants that are not system/policy fixed 17412 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17413 final boolean isGranted = state.isGranted(); 17414 // And only back up the user-twiddled state bits 17415 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17416 final String packageName = mSettings.mPackages.keyAt(i); 17417 if (!pkgGrantsKnown) { 17418 serializer.startTag(null, TAG_GRANT); 17419 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17420 pkgGrantsKnown = true; 17421 } 17422 17423 final boolean userSet = 17424 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17425 final boolean userFixed = 17426 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17427 final boolean revoke = 17428 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17429 17430 serializer.startTag(null, TAG_PERMISSION); 17431 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17432 if (isGranted) { 17433 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17434 } 17435 if (userSet) { 17436 serializer.attribute(null, ATTR_USER_SET, "true"); 17437 } 17438 if (userFixed) { 17439 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17440 } 17441 if (revoke) { 17442 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17443 } 17444 serializer.endTag(null, TAG_PERMISSION); 17445 } 17446 } 17447 } 17448 17449 if (pkgGrantsKnown) { 17450 serializer.endTag(null, TAG_GRANT); 17451 } 17452 } 17453 17454 serializer.endTag(null, TAG_ALL_GRANTS); 17455 } 17456 17457 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17458 throws XmlPullParserException, IOException { 17459 String pkgName = null; 17460 int outerDepth = parser.getDepth(); 17461 int type; 17462 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17463 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17464 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17465 continue; 17466 } 17467 17468 final String tagName = parser.getName(); 17469 if (tagName.equals(TAG_GRANT)) { 17470 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17471 if (DEBUG_BACKUP) { 17472 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17473 } 17474 } else if (tagName.equals(TAG_PERMISSION)) { 17475 17476 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17477 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17478 17479 int newFlagSet = 0; 17480 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17481 newFlagSet |= FLAG_PERMISSION_USER_SET; 17482 } 17483 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17484 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17485 } 17486 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17487 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17488 } 17489 if (DEBUG_BACKUP) { 17490 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17491 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17492 } 17493 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17494 if (ps != null) { 17495 // Already installed so we apply the grant immediately 17496 if (DEBUG_BACKUP) { 17497 Slog.v(TAG, " + already installed; applying"); 17498 } 17499 PermissionsState perms = ps.getPermissionsState(); 17500 BasePermission bp = mSettings.mPermissions.get(permName); 17501 if (bp != null) { 17502 if (isGranted) { 17503 perms.grantRuntimePermission(bp, userId); 17504 } 17505 if (newFlagSet != 0) { 17506 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17507 } 17508 } 17509 } else { 17510 // Need to wait for post-restore install to apply the grant 17511 if (DEBUG_BACKUP) { 17512 Slog.v(TAG, " - not yet installed; saving for later"); 17513 } 17514 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17515 isGranted, newFlagSet, userId); 17516 } 17517 } else { 17518 PackageManagerService.reportSettingsProblem(Log.WARN, 17519 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17520 XmlUtils.skipCurrentTag(parser); 17521 } 17522 } 17523 17524 scheduleWriteSettingsLocked(); 17525 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17526 } 17527 17528 @Override 17529 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17530 int sourceUserId, int targetUserId, int flags) { 17531 mContext.enforceCallingOrSelfPermission( 17532 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17533 int callingUid = Binder.getCallingUid(); 17534 enforceOwnerRights(ownerPackage, callingUid); 17535 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17536 if (intentFilter.countActions() == 0) { 17537 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17538 return; 17539 } 17540 synchronized (mPackages) { 17541 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17542 ownerPackage, targetUserId, flags); 17543 CrossProfileIntentResolver resolver = 17544 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17545 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17546 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17547 if (existing != null) { 17548 int size = existing.size(); 17549 for (int i = 0; i < size; i++) { 17550 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17551 return; 17552 } 17553 } 17554 } 17555 resolver.addFilter(newFilter); 17556 scheduleWritePackageRestrictionsLocked(sourceUserId); 17557 } 17558 } 17559 17560 @Override 17561 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17562 mContext.enforceCallingOrSelfPermission( 17563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17564 int callingUid = Binder.getCallingUid(); 17565 enforceOwnerRights(ownerPackage, callingUid); 17566 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17567 synchronized (mPackages) { 17568 CrossProfileIntentResolver resolver = 17569 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17570 ArraySet<CrossProfileIntentFilter> set = 17571 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17572 for (CrossProfileIntentFilter filter : set) { 17573 if (filter.getOwnerPackage().equals(ownerPackage)) { 17574 resolver.removeFilter(filter); 17575 } 17576 } 17577 scheduleWritePackageRestrictionsLocked(sourceUserId); 17578 } 17579 } 17580 17581 // Enforcing that callingUid is owning pkg on userId 17582 private void enforceOwnerRights(String pkg, int callingUid) { 17583 // The system owns everything. 17584 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17585 return; 17586 } 17587 int callingUserId = UserHandle.getUserId(callingUid); 17588 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17589 if (pi == null) { 17590 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17591 + callingUserId); 17592 } 17593 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17594 throw new SecurityException("Calling uid " + callingUid 17595 + " does not own package " + pkg); 17596 } 17597 } 17598 17599 @Override 17600 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17601 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17602 } 17603 17604 private Intent getHomeIntent() { 17605 Intent intent = new Intent(Intent.ACTION_MAIN); 17606 intent.addCategory(Intent.CATEGORY_HOME); 17607 return intent; 17608 } 17609 17610 private IntentFilter getHomeFilter() { 17611 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17612 filter.addCategory(Intent.CATEGORY_HOME); 17613 filter.addCategory(Intent.CATEGORY_DEFAULT); 17614 return filter; 17615 } 17616 17617 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17618 int userId) { 17619 Intent intent = getHomeIntent(); 17620 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17621 PackageManager.GET_META_DATA, userId); 17622 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17623 true, false, false, userId); 17624 17625 allHomeCandidates.clear(); 17626 if (list != null) { 17627 for (ResolveInfo ri : list) { 17628 allHomeCandidates.add(ri); 17629 } 17630 } 17631 return (preferred == null || preferred.activityInfo == null) 17632 ? null 17633 : new ComponentName(preferred.activityInfo.packageName, 17634 preferred.activityInfo.name); 17635 } 17636 17637 @Override 17638 public void setHomeActivity(ComponentName comp, int userId) { 17639 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17640 getHomeActivitiesAsUser(homeActivities, userId); 17641 17642 boolean found = false; 17643 17644 final int size = homeActivities.size(); 17645 final ComponentName[] set = new ComponentName[size]; 17646 for (int i = 0; i < size; i++) { 17647 final ResolveInfo candidate = homeActivities.get(i); 17648 final ActivityInfo info = candidate.activityInfo; 17649 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17650 set[i] = activityName; 17651 if (!found && activityName.equals(comp)) { 17652 found = true; 17653 } 17654 } 17655 if (!found) { 17656 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17657 + userId); 17658 } 17659 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17660 set, comp, userId); 17661 } 17662 17663 private @Nullable String getSetupWizardPackageName() { 17664 final Intent intent = new Intent(Intent.ACTION_MAIN); 17665 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17666 17667 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17668 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17669 | MATCH_DISABLED_COMPONENTS, 17670 UserHandle.myUserId()); 17671 if (matches.size() == 1) { 17672 return matches.get(0).getComponentInfo().packageName; 17673 } else { 17674 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17675 + ": matches=" + matches); 17676 return null; 17677 } 17678 } 17679 17680 @Override 17681 public void setApplicationEnabledSetting(String appPackageName, 17682 int newState, int flags, int userId, String callingPackage) { 17683 if (!sUserManager.exists(userId)) return; 17684 if (callingPackage == null) { 17685 callingPackage = Integer.toString(Binder.getCallingUid()); 17686 } 17687 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17688 } 17689 17690 @Override 17691 public void setComponentEnabledSetting(ComponentName componentName, 17692 int newState, int flags, int userId) { 17693 if (!sUserManager.exists(userId)) return; 17694 setEnabledSetting(componentName.getPackageName(), 17695 componentName.getClassName(), newState, flags, userId, null); 17696 } 17697 17698 private void setEnabledSetting(final String packageName, String className, int newState, 17699 final int flags, int userId, String callingPackage) { 17700 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17701 || newState == COMPONENT_ENABLED_STATE_ENABLED 17702 || newState == COMPONENT_ENABLED_STATE_DISABLED 17703 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17704 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17705 throw new IllegalArgumentException("Invalid new component state: " 17706 + newState); 17707 } 17708 PackageSetting pkgSetting; 17709 final int uid = Binder.getCallingUid(); 17710 final int permission; 17711 if (uid == Process.SYSTEM_UID) { 17712 permission = PackageManager.PERMISSION_GRANTED; 17713 } else { 17714 permission = mContext.checkCallingOrSelfPermission( 17715 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17716 } 17717 enforceCrossUserPermission(uid, userId, 17718 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17719 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17720 boolean sendNow = false; 17721 boolean isApp = (className == null); 17722 String componentName = isApp ? packageName : className; 17723 int packageUid = -1; 17724 ArrayList<String> components; 17725 17726 // writer 17727 synchronized (mPackages) { 17728 pkgSetting = mSettings.mPackages.get(packageName); 17729 if (pkgSetting == null) { 17730 if (className == null) { 17731 throw new IllegalArgumentException("Unknown package: " + packageName); 17732 } 17733 throw new IllegalArgumentException( 17734 "Unknown component: " + packageName + "/" + className); 17735 } 17736 } 17737 17738 // Limit who can change which apps 17739 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17740 // Don't allow apps that don't have permission to modify other apps 17741 if (!allowedByPermission) { 17742 throw new SecurityException( 17743 "Permission Denial: attempt to change component state from pid=" 17744 + Binder.getCallingPid() 17745 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17746 } 17747 // Don't allow changing profile and device owners. 17748 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17749 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17750 } 17751 } 17752 17753 synchronized (mPackages) { 17754 if (uid == Process.SHELL_UID) { 17755 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17756 int oldState = pkgSetting.getEnabled(userId); 17757 if (className == null 17758 && 17759 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17760 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17761 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17762 && 17763 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17764 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17765 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17766 // ok 17767 } else { 17768 throw new SecurityException( 17769 "Shell cannot change component state for " + packageName + "/" 17770 + className + " to " + newState); 17771 } 17772 } 17773 if (className == null) { 17774 // We're dealing with an application/package level state change 17775 if (pkgSetting.getEnabled(userId) == newState) { 17776 // Nothing to do 17777 return; 17778 } 17779 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17780 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17781 // Don't care about who enables an app. 17782 callingPackage = null; 17783 } 17784 pkgSetting.setEnabled(newState, userId, callingPackage); 17785 // pkgSetting.pkg.mSetEnabled = newState; 17786 } else { 17787 // We're dealing with a component level state change 17788 // First, verify that this is a valid class name. 17789 PackageParser.Package pkg = pkgSetting.pkg; 17790 if (pkg == null || !pkg.hasComponentClassName(className)) { 17791 if (pkg != null && 17792 pkg.applicationInfo.targetSdkVersion >= 17793 Build.VERSION_CODES.JELLY_BEAN) { 17794 throw new IllegalArgumentException("Component class " + className 17795 + " does not exist in " + packageName); 17796 } else { 17797 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17798 + className + " does not exist in " + packageName); 17799 } 17800 } 17801 switch (newState) { 17802 case COMPONENT_ENABLED_STATE_ENABLED: 17803 if (!pkgSetting.enableComponentLPw(className, userId)) { 17804 return; 17805 } 17806 break; 17807 case COMPONENT_ENABLED_STATE_DISABLED: 17808 if (!pkgSetting.disableComponentLPw(className, userId)) { 17809 return; 17810 } 17811 break; 17812 case COMPONENT_ENABLED_STATE_DEFAULT: 17813 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17814 return; 17815 } 17816 break; 17817 default: 17818 Slog.e(TAG, "Invalid new component state: " + newState); 17819 return; 17820 } 17821 } 17822 scheduleWritePackageRestrictionsLocked(userId); 17823 components = mPendingBroadcasts.get(userId, packageName); 17824 final boolean newPackage = components == null; 17825 if (newPackage) { 17826 components = new ArrayList<String>(); 17827 } 17828 if (!components.contains(componentName)) { 17829 components.add(componentName); 17830 } 17831 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17832 sendNow = true; 17833 // Purge entry from pending broadcast list if another one exists already 17834 // since we are sending one right away. 17835 mPendingBroadcasts.remove(userId, packageName); 17836 } else { 17837 if (newPackage) { 17838 mPendingBroadcasts.put(userId, packageName, components); 17839 } 17840 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17841 // Schedule a message 17842 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17843 } 17844 } 17845 } 17846 17847 long callingId = Binder.clearCallingIdentity(); 17848 try { 17849 if (sendNow) { 17850 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17851 sendPackageChangedBroadcast(packageName, 17852 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17853 } 17854 } finally { 17855 Binder.restoreCallingIdentity(callingId); 17856 } 17857 } 17858 17859 @Override 17860 public void flushPackageRestrictionsAsUser(int userId) { 17861 if (!sUserManager.exists(userId)) { 17862 return; 17863 } 17864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17865 false /* checkShell */, "flushPackageRestrictions"); 17866 synchronized (mPackages) { 17867 mSettings.writePackageRestrictionsLPr(userId); 17868 mDirtyUsers.remove(userId); 17869 if (mDirtyUsers.isEmpty()) { 17870 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17871 } 17872 } 17873 } 17874 17875 private void sendPackageChangedBroadcast(String packageName, 17876 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17877 if (DEBUG_INSTALL) 17878 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17879 + componentNames); 17880 Bundle extras = new Bundle(4); 17881 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17882 String nameList[] = new String[componentNames.size()]; 17883 componentNames.toArray(nameList); 17884 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17885 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17886 extras.putInt(Intent.EXTRA_UID, packageUid); 17887 // If this is not reporting a change of the overall package, then only send it 17888 // to registered receivers. We don't want to launch a swath of apps for every 17889 // little component state change. 17890 final int flags = !componentNames.contains(packageName) 17891 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17892 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17893 new int[] {UserHandle.getUserId(packageUid)}); 17894 } 17895 17896 @Override 17897 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17898 if (!sUserManager.exists(userId)) return; 17899 final int uid = Binder.getCallingUid(); 17900 final int permission = mContext.checkCallingOrSelfPermission( 17901 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17902 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17903 enforceCrossUserPermission(uid, userId, 17904 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17905 // writer 17906 synchronized (mPackages) { 17907 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17908 allowedByPermission, uid, userId)) { 17909 scheduleWritePackageRestrictionsLocked(userId); 17910 } 17911 } 17912 } 17913 17914 @Override 17915 public String getInstallerPackageName(String packageName) { 17916 // reader 17917 synchronized (mPackages) { 17918 return mSettings.getInstallerPackageNameLPr(packageName); 17919 } 17920 } 17921 17922 public boolean isOrphaned(String packageName) { 17923 // reader 17924 synchronized (mPackages) { 17925 return mSettings.isOrphaned(packageName); 17926 } 17927 } 17928 17929 @Override 17930 public int getApplicationEnabledSetting(String packageName, int userId) { 17931 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17932 int uid = Binder.getCallingUid(); 17933 enforceCrossUserPermission(uid, userId, 17934 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17935 // reader 17936 synchronized (mPackages) { 17937 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17938 } 17939 } 17940 17941 @Override 17942 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17943 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17944 int uid = Binder.getCallingUid(); 17945 enforceCrossUserPermission(uid, userId, 17946 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17947 // reader 17948 synchronized (mPackages) { 17949 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17950 } 17951 } 17952 17953 @Override 17954 public void enterSafeMode() { 17955 enforceSystemOrRoot("Only the system can request entering safe mode"); 17956 17957 if (!mSystemReady) { 17958 mSafeMode = true; 17959 } 17960 } 17961 17962 @Override 17963 public void systemReady() { 17964 mSystemReady = true; 17965 17966 // Read the compatibilty setting when the system is ready. 17967 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17968 mContext.getContentResolver(), 17969 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17970 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17971 if (DEBUG_SETTINGS) { 17972 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17973 } 17974 17975 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17976 17977 synchronized (mPackages) { 17978 // Verify that all of the preferred activity components actually 17979 // exist. It is possible for applications to be updated and at 17980 // that point remove a previously declared activity component that 17981 // had been set as a preferred activity. We try to clean this up 17982 // the next time we encounter that preferred activity, but it is 17983 // possible for the user flow to never be able to return to that 17984 // situation so here we do a sanity check to make sure we haven't 17985 // left any junk around. 17986 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17987 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17988 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17989 removed.clear(); 17990 for (PreferredActivity pa : pir.filterSet()) { 17991 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17992 removed.add(pa); 17993 } 17994 } 17995 if (removed.size() > 0) { 17996 for (int r=0; r<removed.size(); r++) { 17997 PreferredActivity pa = removed.get(r); 17998 Slog.w(TAG, "Removing dangling preferred activity: " 17999 + pa.mPref.mComponent); 18000 pir.removeFilter(pa); 18001 } 18002 mSettings.writePackageRestrictionsLPr( 18003 mSettings.mPreferredActivities.keyAt(i)); 18004 } 18005 } 18006 18007 for (int userId : UserManagerService.getInstance().getUserIds()) { 18008 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18009 grantPermissionsUserIds = ArrayUtils.appendInt( 18010 grantPermissionsUserIds, userId); 18011 } 18012 } 18013 } 18014 sUserManager.systemReady(); 18015 18016 // If we upgraded grant all default permissions before kicking off. 18017 for (int userId : grantPermissionsUserIds) { 18018 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18019 } 18020 18021 // Kick off any messages waiting for system ready 18022 if (mPostSystemReadyMessages != null) { 18023 for (Message msg : mPostSystemReadyMessages) { 18024 msg.sendToTarget(); 18025 } 18026 mPostSystemReadyMessages = null; 18027 } 18028 18029 // Watch for external volumes that come and go over time 18030 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18031 storage.registerListener(mStorageListener); 18032 18033 mInstallerService.systemReady(); 18034 mPackageDexOptimizer.systemReady(); 18035 18036 MountServiceInternal mountServiceInternal = LocalServices.getService( 18037 MountServiceInternal.class); 18038 mountServiceInternal.addExternalStoragePolicy( 18039 new MountServiceInternal.ExternalStorageMountPolicy() { 18040 @Override 18041 public int getMountMode(int uid, String packageName) { 18042 if (Process.isIsolated(uid)) { 18043 return Zygote.MOUNT_EXTERNAL_NONE; 18044 } 18045 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18046 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18047 } 18048 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18049 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18050 } 18051 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18052 return Zygote.MOUNT_EXTERNAL_READ; 18053 } 18054 return Zygote.MOUNT_EXTERNAL_WRITE; 18055 } 18056 18057 @Override 18058 public boolean hasExternalStorage(int uid, String packageName) { 18059 return true; 18060 } 18061 }); 18062 18063 // Now that we're mostly running, clean up stale users and apps 18064 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18065 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18066 } 18067 18068 @Override 18069 public boolean isSafeMode() { 18070 return mSafeMode; 18071 } 18072 18073 @Override 18074 public boolean hasSystemUidErrors() { 18075 return mHasSystemUidErrors; 18076 } 18077 18078 static String arrayToString(int[] array) { 18079 StringBuffer buf = new StringBuffer(128); 18080 buf.append('['); 18081 if (array != null) { 18082 for (int i=0; i<array.length; i++) { 18083 if (i > 0) buf.append(", "); 18084 buf.append(array[i]); 18085 } 18086 } 18087 buf.append(']'); 18088 return buf.toString(); 18089 } 18090 18091 static class DumpState { 18092 public static final int DUMP_LIBS = 1 << 0; 18093 public static final int DUMP_FEATURES = 1 << 1; 18094 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18095 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18096 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18097 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18098 public static final int DUMP_PERMISSIONS = 1 << 6; 18099 public static final int DUMP_PACKAGES = 1 << 7; 18100 public static final int DUMP_SHARED_USERS = 1 << 8; 18101 public static final int DUMP_MESSAGES = 1 << 9; 18102 public static final int DUMP_PROVIDERS = 1 << 10; 18103 public static final int DUMP_VERIFIERS = 1 << 11; 18104 public static final int DUMP_PREFERRED = 1 << 12; 18105 public static final int DUMP_PREFERRED_XML = 1 << 13; 18106 public static final int DUMP_KEYSETS = 1 << 14; 18107 public static final int DUMP_VERSION = 1 << 15; 18108 public static final int DUMP_INSTALLS = 1 << 16; 18109 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18110 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18111 public static final int DUMP_FROZEN = 1 << 19; 18112 public static final int DUMP_DEXOPT = 1 << 20; 18113 18114 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18115 18116 private int mTypes; 18117 18118 private int mOptions; 18119 18120 private boolean mTitlePrinted; 18121 18122 private SharedUserSetting mSharedUser; 18123 18124 public boolean isDumping(int type) { 18125 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18126 return true; 18127 } 18128 18129 return (mTypes & type) != 0; 18130 } 18131 18132 public void setDump(int type) { 18133 mTypes |= type; 18134 } 18135 18136 public boolean isOptionEnabled(int option) { 18137 return (mOptions & option) != 0; 18138 } 18139 18140 public void setOptionEnabled(int option) { 18141 mOptions |= option; 18142 } 18143 18144 public boolean onTitlePrinted() { 18145 final boolean printed = mTitlePrinted; 18146 mTitlePrinted = true; 18147 return printed; 18148 } 18149 18150 public boolean getTitlePrinted() { 18151 return mTitlePrinted; 18152 } 18153 18154 public void setTitlePrinted(boolean enabled) { 18155 mTitlePrinted = enabled; 18156 } 18157 18158 public SharedUserSetting getSharedUser() { 18159 return mSharedUser; 18160 } 18161 18162 public void setSharedUser(SharedUserSetting user) { 18163 mSharedUser = user; 18164 } 18165 } 18166 18167 @Override 18168 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18169 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18170 (new PackageManagerShellCommand(this)).exec( 18171 this, in, out, err, args, resultReceiver); 18172 } 18173 18174 @Override 18175 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18176 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18177 != PackageManager.PERMISSION_GRANTED) { 18178 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18179 + Binder.getCallingPid() 18180 + ", uid=" + Binder.getCallingUid() 18181 + " without permission " 18182 + android.Manifest.permission.DUMP); 18183 return; 18184 } 18185 18186 DumpState dumpState = new DumpState(); 18187 boolean fullPreferred = false; 18188 boolean checkin = false; 18189 18190 String packageName = null; 18191 ArraySet<String> permissionNames = null; 18192 18193 int opti = 0; 18194 while (opti < args.length) { 18195 String opt = args[opti]; 18196 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18197 break; 18198 } 18199 opti++; 18200 18201 if ("-a".equals(opt)) { 18202 // Right now we only know how to print all. 18203 } else if ("-h".equals(opt)) { 18204 pw.println("Package manager dump options:"); 18205 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18206 pw.println(" --checkin: dump for a checkin"); 18207 pw.println(" -f: print details of intent filters"); 18208 pw.println(" -h: print this help"); 18209 pw.println(" cmd may be one of:"); 18210 pw.println(" l[ibraries]: list known shared libraries"); 18211 pw.println(" f[eatures]: list device features"); 18212 pw.println(" k[eysets]: print known keysets"); 18213 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18214 pw.println(" perm[issions]: dump permissions"); 18215 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18216 pw.println(" pref[erred]: print preferred package settings"); 18217 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18218 pw.println(" prov[iders]: dump content providers"); 18219 pw.println(" p[ackages]: dump installed packages"); 18220 pw.println(" s[hared-users]: dump shared user IDs"); 18221 pw.println(" m[essages]: print collected runtime messages"); 18222 pw.println(" v[erifiers]: print package verifier info"); 18223 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18224 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18225 pw.println(" version: print database version info"); 18226 pw.println(" write: write current settings now"); 18227 pw.println(" installs: details about install sessions"); 18228 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18229 pw.println(" dexopt: dump dexopt state"); 18230 pw.println(" <package.name>: info about given package"); 18231 return; 18232 } else if ("--checkin".equals(opt)) { 18233 checkin = true; 18234 } else if ("-f".equals(opt)) { 18235 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18236 } else { 18237 pw.println("Unknown argument: " + opt + "; use -h for help"); 18238 } 18239 } 18240 18241 // Is the caller requesting to dump a particular piece of data? 18242 if (opti < args.length) { 18243 String cmd = args[opti]; 18244 opti++; 18245 // Is this a package name? 18246 if ("android".equals(cmd) || cmd.contains(".")) { 18247 packageName = cmd; 18248 // When dumping a single package, we always dump all of its 18249 // filter information since the amount of data will be reasonable. 18250 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18251 } else if ("check-permission".equals(cmd)) { 18252 if (opti >= args.length) { 18253 pw.println("Error: check-permission missing permission argument"); 18254 return; 18255 } 18256 String perm = args[opti]; 18257 opti++; 18258 if (opti >= args.length) { 18259 pw.println("Error: check-permission missing package argument"); 18260 return; 18261 } 18262 String pkg = args[opti]; 18263 opti++; 18264 int user = UserHandle.getUserId(Binder.getCallingUid()); 18265 if (opti < args.length) { 18266 try { 18267 user = Integer.parseInt(args[opti]); 18268 } catch (NumberFormatException e) { 18269 pw.println("Error: check-permission user argument is not a number: " 18270 + args[opti]); 18271 return; 18272 } 18273 } 18274 pw.println(checkPermission(perm, pkg, user)); 18275 return; 18276 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18277 dumpState.setDump(DumpState.DUMP_LIBS); 18278 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18279 dumpState.setDump(DumpState.DUMP_FEATURES); 18280 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18281 if (opti >= args.length) { 18282 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18283 | DumpState.DUMP_SERVICE_RESOLVERS 18284 | DumpState.DUMP_RECEIVER_RESOLVERS 18285 | DumpState.DUMP_CONTENT_RESOLVERS); 18286 } else { 18287 while (opti < args.length) { 18288 String name = args[opti]; 18289 if ("a".equals(name) || "activity".equals(name)) { 18290 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18291 } else if ("s".equals(name) || "service".equals(name)) { 18292 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18293 } else if ("r".equals(name) || "receiver".equals(name)) { 18294 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18295 } else if ("c".equals(name) || "content".equals(name)) { 18296 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18297 } else { 18298 pw.println("Error: unknown resolver table type: " + name); 18299 return; 18300 } 18301 opti++; 18302 } 18303 } 18304 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18305 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18306 } else if ("permission".equals(cmd)) { 18307 if (opti >= args.length) { 18308 pw.println("Error: permission requires permission name"); 18309 return; 18310 } 18311 permissionNames = new ArraySet<>(); 18312 while (opti < args.length) { 18313 permissionNames.add(args[opti]); 18314 opti++; 18315 } 18316 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18317 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18318 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18319 dumpState.setDump(DumpState.DUMP_PREFERRED); 18320 } else if ("preferred-xml".equals(cmd)) { 18321 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18322 if (opti < args.length && "--full".equals(args[opti])) { 18323 fullPreferred = true; 18324 opti++; 18325 } 18326 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18327 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18328 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18329 dumpState.setDump(DumpState.DUMP_PACKAGES); 18330 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18331 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18332 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18333 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18334 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18335 dumpState.setDump(DumpState.DUMP_MESSAGES); 18336 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18337 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18338 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18339 || "intent-filter-verifiers".equals(cmd)) { 18340 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18341 } else if ("version".equals(cmd)) { 18342 dumpState.setDump(DumpState.DUMP_VERSION); 18343 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18344 dumpState.setDump(DumpState.DUMP_KEYSETS); 18345 } else if ("installs".equals(cmd)) { 18346 dumpState.setDump(DumpState.DUMP_INSTALLS); 18347 } else if ("frozen".equals(cmd)) { 18348 dumpState.setDump(DumpState.DUMP_FROZEN); 18349 } else if ("dexopt".equals(cmd)) { 18350 dumpState.setDump(DumpState.DUMP_DEXOPT); 18351 } else if ("write".equals(cmd)) { 18352 synchronized (mPackages) { 18353 mSettings.writeLPr(); 18354 pw.println("Settings written."); 18355 return; 18356 } 18357 } 18358 } 18359 18360 if (checkin) { 18361 pw.println("vers,1"); 18362 } 18363 18364 // reader 18365 synchronized (mPackages) { 18366 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18367 if (!checkin) { 18368 if (dumpState.onTitlePrinted()) 18369 pw.println(); 18370 pw.println("Database versions:"); 18371 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18372 } 18373 } 18374 18375 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18376 if (!checkin) { 18377 if (dumpState.onTitlePrinted()) 18378 pw.println(); 18379 pw.println("Verifiers:"); 18380 pw.print(" Required: "); 18381 pw.print(mRequiredVerifierPackage); 18382 pw.print(" (uid="); 18383 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18384 UserHandle.USER_SYSTEM)); 18385 pw.println(")"); 18386 } else if (mRequiredVerifierPackage != null) { 18387 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18388 pw.print(","); 18389 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18390 UserHandle.USER_SYSTEM)); 18391 } 18392 } 18393 18394 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18395 packageName == null) { 18396 if (mIntentFilterVerifierComponent != null) { 18397 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18398 if (!checkin) { 18399 if (dumpState.onTitlePrinted()) 18400 pw.println(); 18401 pw.println("Intent Filter Verifier:"); 18402 pw.print(" Using: "); 18403 pw.print(verifierPackageName); 18404 pw.print(" (uid="); 18405 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18406 UserHandle.USER_SYSTEM)); 18407 pw.println(")"); 18408 } else if (verifierPackageName != null) { 18409 pw.print("ifv,"); pw.print(verifierPackageName); 18410 pw.print(","); 18411 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18412 UserHandle.USER_SYSTEM)); 18413 } 18414 } else { 18415 pw.println(); 18416 pw.println("No Intent Filter Verifier available!"); 18417 } 18418 } 18419 18420 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18421 boolean printedHeader = false; 18422 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18423 while (it.hasNext()) { 18424 String name = it.next(); 18425 SharedLibraryEntry ent = mSharedLibraries.get(name); 18426 if (!checkin) { 18427 if (!printedHeader) { 18428 if (dumpState.onTitlePrinted()) 18429 pw.println(); 18430 pw.println("Libraries:"); 18431 printedHeader = true; 18432 } 18433 pw.print(" "); 18434 } else { 18435 pw.print("lib,"); 18436 } 18437 pw.print(name); 18438 if (!checkin) { 18439 pw.print(" -> "); 18440 } 18441 if (ent.path != null) { 18442 if (!checkin) { 18443 pw.print("(jar) "); 18444 pw.print(ent.path); 18445 } else { 18446 pw.print(",jar,"); 18447 pw.print(ent.path); 18448 } 18449 } else { 18450 if (!checkin) { 18451 pw.print("(apk) "); 18452 pw.print(ent.apk); 18453 } else { 18454 pw.print(",apk,"); 18455 pw.print(ent.apk); 18456 } 18457 } 18458 pw.println(); 18459 } 18460 } 18461 18462 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18463 if (dumpState.onTitlePrinted()) 18464 pw.println(); 18465 if (!checkin) { 18466 pw.println("Features:"); 18467 } 18468 18469 for (FeatureInfo feat : mAvailableFeatures.values()) { 18470 if (checkin) { 18471 pw.print("feat,"); 18472 pw.print(feat.name); 18473 pw.print(","); 18474 pw.println(feat.version); 18475 } else { 18476 pw.print(" "); 18477 pw.print(feat.name); 18478 if (feat.version > 0) { 18479 pw.print(" version="); 18480 pw.print(feat.version); 18481 } 18482 pw.println(); 18483 } 18484 } 18485 } 18486 18487 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18488 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18489 : "Activity Resolver Table:", " ", packageName, 18490 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18491 dumpState.setTitlePrinted(true); 18492 } 18493 } 18494 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18495 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18496 : "Receiver Resolver Table:", " ", packageName, 18497 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18498 dumpState.setTitlePrinted(true); 18499 } 18500 } 18501 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18502 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18503 : "Service Resolver Table:", " ", packageName, 18504 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18505 dumpState.setTitlePrinted(true); 18506 } 18507 } 18508 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18509 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18510 : "Provider Resolver Table:", " ", packageName, 18511 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18512 dumpState.setTitlePrinted(true); 18513 } 18514 } 18515 18516 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18517 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18518 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18519 int user = mSettings.mPreferredActivities.keyAt(i); 18520 if (pir.dump(pw, 18521 dumpState.getTitlePrinted() 18522 ? "\nPreferred Activities User " + user + ":" 18523 : "Preferred Activities User " + user + ":", " ", 18524 packageName, true, false)) { 18525 dumpState.setTitlePrinted(true); 18526 } 18527 } 18528 } 18529 18530 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18531 pw.flush(); 18532 FileOutputStream fout = new FileOutputStream(fd); 18533 BufferedOutputStream str = new BufferedOutputStream(fout); 18534 XmlSerializer serializer = new FastXmlSerializer(); 18535 try { 18536 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18537 serializer.startDocument(null, true); 18538 serializer.setFeature( 18539 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18540 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18541 serializer.endDocument(); 18542 serializer.flush(); 18543 } catch (IllegalArgumentException e) { 18544 pw.println("Failed writing: " + e); 18545 } catch (IllegalStateException e) { 18546 pw.println("Failed writing: " + e); 18547 } catch (IOException e) { 18548 pw.println("Failed writing: " + e); 18549 } 18550 } 18551 18552 if (!checkin 18553 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18554 && packageName == null) { 18555 pw.println(); 18556 int count = mSettings.mPackages.size(); 18557 if (count == 0) { 18558 pw.println("No applications!"); 18559 pw.println(); 18560 } else { 18561 final String prefix = " "; 18562 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18563 if (allPackageSettings.size() == 0) { 18564 pw.println("No domain preferred apps!"); 18565 pw.println(); 18566 } else { 18567 pw.println("App verification status:"); 18568 pw.println(); 18569 count = 0; 18570 for (PackageSetting ps : allPackageSettings) { 18571 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18572 if (ivi == null || ivi.getPackageName() == null) continue; 18573 pw.println(prefix + "Package: " + ivi.getPackageName()); 18574 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18575 pw.println(prefix + "Status: " + ivi.getStatusString()); 18576 pw.println(); 18577 count++; 18578 } 18579 if (count == 0) { 18580 pw.println(prefix + "No app verification established."); 18581 pw.println(); 18582 } 18583 for (int userId : sUserManager.getUserIds()) { 18584 pw.println("App linkages for user " + userId + ":"); 18585 pw.println(); 18586 count = 0; 18587 for (PackageSetting ps : allPackageSettings) { 18588 final long status = ps.getDomainVerificationStatusForUser(userId); 18589 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18590 continue; 18591 } 18592 pw.println(prefix + "Package: " + ps.name); 18593 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18594 String statusStr = IntentFilterVerificationInfo. 18595 getStatusStringFromValue(status); 18596 pw.println(prefix + "Status: " + statusStr); 18597 pw.println(); 18598 count++; 18599 } 18600 if (count == 0) { 18601 pw.println(prefix + "No configured app linkages."); 18602 pw.println(); 18603 } 18604 } 18605 } 18606 } 18607 } 18608 18609 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18610 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18611 if (packageName == null && permissionNames == null) { 18612 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18613 if (iperm == 0) { 18614 if (dumpState.onTitlePrinted()) 18615 pw.println(); 18616 pw.println("AppOp Permissions:"); 18617 } 18618 pw.print(" AppOp Permission "); 18619 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18620 pw.println(":"); 18621 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18622 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18623 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18624 } 18625 } 18626 } 18627 } 18628 18629 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18630 boolean printedSomething = false; 18631 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18632 if (packageName != null && !packageName.equals(p.info.packageName)) { 18633 continue; 18634 } 18635 if (!printedSomething) { 18636 if (dumpState.onTitlePrinted()) 18637 pw.println(); 18638 pw.println("Registered ContentProviders:"); 18639 printedSomething = true; 18640 } 18641 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18642 pw.print(" "); pw.println(p.toString()); 18643 } 18644 printedSomething = false; 18645 for (Map.Entry<String, PackageParser.Provider> entry : 18646 mProvidersByAuthority.entrySet()) { 18647 PackageParser.Provider p = entry.getValue(); 18648 if (packageName != null && !packageName.equals(p.info.packageName)) { 18649 continue; 18650 } 18651 if (!printedSomething) { 18652 if (dumpState.onTitlePrinted()) 18653 pw.println(); 18654 pw.println("ContentProvider Authorities:"); 18655 printedSomething = true; 18656 } 18657 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18658 pw.print(" "); pw.println(p.toString()); 18659 if (p.info != null && p.info.applicationInfo != null) { 18660 final String appInfo = p.info.applicationInfo.toString(); 18661 pw.print(" applicationInfo="); pw.println(appInfo); 18662 } 18663 } 18664 } 18665 18666 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18667 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18668 } 18669 18670 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18671 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18672 } 18673 18674 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18675 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18676 } 18677 18678 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18679 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18680 } 18681 18682 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18683 // XXX should handle packageName != null by dumping only install data that 18684 // the given package is involved with. 18685 if (dumpState.onTitlePrinted()) pw.println(); 18686 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18687 } 18688 18689 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18690 // XXX should handle packageName != null by dumping only install data that 18691 // the given package is involved with. 18692 if (dumpState.onTitlePrinted()) pw.println(); 18693 18694 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18695 ipw.println(); 18696 ipw.println("Frozen packages:"); 18697 ipw.increaseIndent(); 18698 if (mFrozenPackages.size() == 0) { 18699 ipw.println("(none)"); 18700 } else { 18701 for (int i = 0; i < mFrozenPackages.size(); i++) { 18702 ipw.println(mFrozenPackages.valueAt(i)); 18703 } 18704 } 18705 ipw.decreaseIndent(); 18706 } 18707 18708 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18709 if (dumpState.onTitlePrinted()) pw.println(); 18710 dumpDexoptStateLPr(pw, packageName); 18711 } 18712 18713 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18714 if (dumpState.onTitlePrinted()) pw.println(); 18715 mSettings.dumpReadMessagesLPr(pw, dumpState); 18716 18717 pw.println(); 18718 pw.println("Package warning messages:"); 18719 BufferedReader in = null; 18720 String line = null; 18721 try { 18722 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18723 while ((line = in.readLine()) != null) { 18724 if (line.contains("ignored: updated version")) continue; 18725 pw.println(line); 18726 } 18727 } catch (IOException ignored) { 18728 } finally { 18729 IoUtils.closeQuietly(in); 18730 } 18731 } 18732 18733 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18734 BufferedReader in = null; 18735 String line = null; 18736 try { 18737 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18738 while ((line = in.readLine()) != null) { 18739 if (line.contains("ignored: updated version")) continue; 18740 pw.print("msg,"); 18741 pw.println(line); 18742 } 18743 } catch (IOException ignored) { 18744 } finally { 18745 IoUtils.closeQuietly(in); 18746 } 18747 } 18748 } 18749 } 18750 18751 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18752 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18753 ipw.println(); 18754 ipw.println("Dexopt state:"); 18755 ipw.increaseIndent(); 18756 Collection<PackageParser.Package> packages = null; 18757 if (packageName != null) { 18758 PackageParser.Package targetPackage = mPackages.get(packageName); 18759 if (targetPackage != null) { 18760 packages = Collections.singletonList(targetPackage); 18761 } else { 18762 ipw.println("Unable to find package: " + packageName); 18763 return; 18764 } 18765 } else { 18766 packages = mPackages.values(); 18767 } 18768 18769 for (PackageParser.Package pkg : packages) { 18770 ipw.println("[" + pkg.packageName + "]"); 18771 ipw.increaseIndent(); 18772 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18773 ipw.decreaseIndent(); 18774 } 18775 } 18776 18777 private String dumpDomainString(String packageName) { 18778 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18779 .getList(); 18780 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18781 18782 ArraySet<String> result = new ArraySet<>(); 18783 if (iviList.size() > 0) { 18784 for (IntentFilterVerificationInfo ivi : iviList) { 18785 for (String host : ivi.getDomains()) { 18786 result.add(host); 18787 } 18788 } 18789 } 18790 if (filters != null && filters.size() > 0) { 18791 for (IntentFilter filter : filters) { 18792 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18793 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18794 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18795 result.addAll(filter.getHostsList()); 18796 } 18797 } 18798 } 18799 18800 StringBuilder sb = new StringBuilder(result.size() * 16); 18801 for (String domain : result) { 18802 if (sb.length() > 0) sb.append(" "); 18803 sb.append(domain); 18804 } 18805 return sb.toString(); 18806 } 18807 18808 // ------- apps on sdcard specific code ------- 18809 static final boolean DEBUG_SD_INSTALL = false; 18810 18811 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18812 18813 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18814 18815 private boolean mMediaMounted = false; 18816 18817 static String getEncryptKey() { 18818 try { 18819 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18820 SD_ENCRYPTION_KEYSTORE_NAME); 18821 if (sdEncKey == null) { 18822 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18823 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18824 if (sdEncKey == null) { 18825 Slog.e(TAG, "Failed to create encryption keys"); 18826 return null; 18827 } 18828 } 18829 return sdEncKey; 18830 } catch (NoSuchAlgorithmException nsae) { 18831 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18832 return null; 18833 } catch (IOException ioe) { 18834 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18835 return null; 18836 } 18837 } 18838 18839 /* 18840 * Update media status on PackageManager. 18841 */ 18842 @Override 18843 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18844 int callingUid = Binder.getCallingUid(); 18845 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18846 throw new SecurityException("Media status can only be updated by the system"); 18847 } 18848 // reader; this apparently protects mMediaMounted, but should probably 18849 // be a different lock in that case. 18850 synchronized (mPackages) { 18851 Log.i(TAG, "Updating external media status from " 18852 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18853 + (mediaStatus ? "mounted" : "unmounted")); 18854 if (DEBUG_SD_INSTALL) 18855 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18856 + ", mMediaMounted=" + mMediaMounted); 18857 if (mediaStatus == mMediaMounted) { 18858 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18859 : 0, -1); 18860 mHandler.sendMessage(msg); 18861 return; 18862 } 18863 mMediaMounted = mediaStatus; 18864 } 18865 // Queue up an async operation since the package installation may take a 18866 // little while. 18867 mHandler.post(new Runnable() { 18868 public void run() { 18869 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18870 } 18871 }); 18872 } 18873 18874 /** 18875 * Called by MountService when the initial ASECs to scan are available. 18876 * Should block until all the ASEC containers are finished being scanned. 18877 */ 18878 public void scanAvailableAsecs() { 18879 updateExternalMediaStatusInner(true, false, false); 18880 } 18881 18882 /* 18883 * Collect information of applications on external media, map them against 18884 * existing containers and update information based on current mount status. 18885 * Please note that we always have to report status if reportStatus has been 18886 * set to true especially when unloading packages. 18887 */ 18888 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18889 boolean externalStorage) { 18890 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18891 int[] uidArr = EmptyArray.INT; 18892 18893 final String[] list = PackageHelper.getSecureContainerList(); 18894 if (ArrayUtils.isEmpty(list)) { 18895 Log.i(TAG, "No secure containers found"); 18896 } else { 18897 // Process list of secure containers and categorize them 18898 // as active or stale based on their package internal state. 18899 18900 // reader 18901 synchronized (mPackages) { 18902 for (String cid : list) { 18903 // Leave stages untouched for now; installer service owns them 18904 if (PackageInstallerService.isStageName(cid)) continue; 18905 18906 if (DEBUG_SD_INSTALL) 18907 Log.i(TAG, "Processing container " + cid); 18908 String pkgName = getAsecPackageName(cid); 18909 if (pkgName == null) { 18910 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18911 continue; 18912 } 18913 if (DEBUG_SD_INSTALL) 18914 Log.i(TAG, "Looking for pkg : " + pkgName); 18915 18916 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18917 if (ps == null) { 18918 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18919 continue; 18920 } 18921 18922 /* 18923 * Skip packages that are not external if we're unmounting 18924 * external storage. 18925 */ 18926 if (externalStorage && !isMounted && !isExternal(ps)) { 18927 continue; 18928 } 18929 18930 final AsecInstallArgs args = new AsecInstallArgs(cid, 18931 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18932 // The package status is changed only if the code path 18933 // matches between settings and the container id. 18934 if (ps.codePathString != null 18935 && ps.codePathString.startsWith(args.getCodePath())) { 18936 if (DEBUG_SD_INSTALL) { 18937 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18938 + " at code path: " + ps.codePathString); 18939 } 18940 18941 // We do have a valid package installed on sdcard 18942 processCids.put(args, ps.codePathString); 18943 final int uid = ps.appId; 18944 if (uid != -1) { 18945 uidArr = ArrayUtils.appendInt(uidArr, uid); 18946 } 18947 } else { 18948 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18949 + ps.codePathString); 18950 } 18951 } 18952 } 18953 18954 Arrays.sort(uidArr); 18955 } 18956 18957 // Process packages with valid entries. 18958 if (isMounted) { 18959 if (DEBUG_SD_INSTALL) 18960 Log.i(TAG, "Loading packages"); 18961 loadMediaPackages(processCids, uidArr, externalStorage); 18962 startCleaningPackages(); 18963 mInstallerService.onSecureContainersAvailable(); 18964 } else { 18965 if (DEBUG_SD_INSTALL) 18966 Log.i(TAG, "Unloading packages"); 18967 unloadMediaPackages(processCids, uidArr, reportStatus); 18968 } 18969 } 18970 18971 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18972 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18973 final int size = infos.size(); 18974 final String[] packageNames = new String[size]; 18975 final int[] packageUids = new int[size]; 18976 for (int i = 0; i < size; i++) { 18977 final ApplicationInfo info = infos.get(i); 18978 packageNames[i] = info.packageName; 18979 packageUids[i] = info.uid; 18980 } 18981 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18982 finishedReceiver); 18983 } 18984 18985 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18986 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18987 sendResourcesChangedBroadcast(mediaStatus, replacing, 18988 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18989 } 18990 18991 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18992 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18993 int size = pkgList.length; 18994 if (size > 0) { 18995 // Send broadcasts here 18996 Bundle extras = new Bundle(); 18997 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18998 if (uidArr != null) { 18999 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19000 } 19001 if (replacing) { 19002 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19003 } 19004 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19005 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19006 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19007 } 19008 } 19009 19010 /* 19011 * Look at potentially valid container ids from processCids If package 19012 * information doesn't match the one on record or package scanning fails, 19013 * the cid is added to list of removeCids. We currently don't delete stale 19014 * containers. 19015 */ 19016 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19017 boolean externalStorage) { 19018 ArrayList<String> pkgList = new ArrayList<String>(); 19019 Set<AsecInstallArgs> keys = processCids.keySet(); 19020 19021 for (AsecInstallArgs args : keys) { 19022 String codePath = processCids.get(args); 19023 if (DEBUG_SD_INSTALL) 19024 Log.i(TAG, "Loading container : " + args.cid); 19025 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19026 try { 19027 // Make sure there are no container errors first. 19028 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19029 Slog.e(TAG, "Failed to mount cid : " + args.cid 19030 + " when installing from sdcard"); 19031 continue; 19032 } 19033 // Check code path here. 19034 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19035 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19036 + " does not match one in settings " + codePath); 19037 continue; 19038 } 19039 // Parse package 19040 int parseFlags = mDefParseFlags; 19041 if (args.isExternalAsec()) { 19042 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19043 } 19044 if (args.isFwdLocked()) { 19045 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19046 } 19047 19048 synchronized (mInstallLock) { 19049 PackageParser.Package pkg = null; 19050 try { 19051 // Sadly we don't know the package name yet to freeze it 19052 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19053 SCAN_IGNORE_FROZEN, 0, null); 19054 } catch (PackageManagerException e) { 19055 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19056 } 19057 // Scan the package 19058 if (pkg != null) { 19059 /* 19060 * TODO why is the lock being held? doPostInstall is 19061 * called in other places without the lock. This needs 19062 * to be straightened out. 19063 */ 19064 // writer 19065 synchronized (mPackages) { 19066 retCode = PackageManager.INSTALL_SUCCEEDED; 19067 pkgList.add(pkg.packageName); 19068 // Post process args 19069 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19070 pkg.applicationInfo.uid); 19071 } 19072 } else { 19073 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19074 } 19075 } 19076 19077 } finally { 19078 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19079 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19080 } 19081 } 19082 } 19083 // writer 19084 synchronized (mPackages) { 19085 // If the platform SDK has changed since the last time we booted, 19086 // we need to re-grant app permission to catch any new ones that 19087 // appear. This is really a hack, and means that apps can in some 19088 // cases get permissions that the user didn't initially explicitly 19089 // allow... it would be nice to have some better way to handle 19090 // this situation. 19091 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19092 : mSettings.getInternalVersion(); 19093 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19094 : StorageManager.UUID_PRIVATE_INTERNAL; 19095 19096 int updateFlags = UPDATE_PERMISSIONS_ALL; 19097 if (ver.sdkVersion != mSdkVersion) { 19098 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19099 + mSdkVersion + "; regranting permissions for external"); 19100 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19101 } 19102 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19103 19104 // Yay, everything is now upgraded 19105 ver.forceCurrent(); 19106 19107 // can downgrade to reader 19108 // Persist settings 19109 mSettings.writeLPr(); 19110 } 19111 // Send a broadcast to let everyone know we are done processing 19112 if (pkgList.size() > 0) { 19113 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19114 } 19115 } 19116 19117 /* 19118 * Utility method to unload a list of specified containers 19119 */ 19120 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19121 // Just unmount all valid containers. 19122 for (AsecInstallArgs arg : cidArgs) { 19123 synchronized (mInstallLock) { 19124 arg.doPostDeleteLI(false); 19125 } 19126 } 19127 } 19128 19129 /* 19130 * Unload packages mounted on external media. This involves deleting package 19131 * data from internal structures, sending broadcasts about disabled packages, 19132 * gc'ing to free up references, unmounting all secure containers 19133 * corresponding to packages on external media, and posting a 19134 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19135 * that we always have to post this message if status has been requested no 19136 * matter what. 19137 */ 19138 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19139 final boolean reportStatus) { 19140 if (DEBUG_SD_INSTALL) 19141 Log.i(TAG, "unloading media packages"); 19142 ArrayList<String> pkgList = new ArrayList<String>(); 19143 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19144 final Set<AsecInstallArgs> keys = processCids.keySet(); 19145 for (AsecInstallArgs args : keys) { 19146 String pkgName = args.getPackageName(); 19147 if (DEBUG_SD_INSTALL) 19148 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19149 // Delete package internally 19150 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19151 synchronized (mInstallLock) { 19152 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19153 final boolean res; 19154 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19155 "unloadMediaPackages")) { 19156 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19157 null); 19158 } 19159 if (res) { 19160 pkgList.add(pkgName); 19161 } else { 19162 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19163 failedList.add(args); 19164 } 19165 } 19166 } 19167 19168 // reader 19169 synchronized (mPackages) { 19170 // We didn't update the settings after removing each package; 19171 // write them now for all packages. 19172 mSettings.writeLPr(); 19173 } 19174 19175 // We have to absolutely send UPDATED_MEDIA_STATUS only 19176 // after confirming that all the receivers processed the ordered 19177 // broadcast when packages get disabled, force a gc to clean things up. 19178 // and unload all the containers. 19179 if (pkgList.size() > 0) { 19180 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19181 new IIntentReceiver.Stub() { 19182 public void performReceive(Intent intent, int resultCode, String data, 19183 Bundle extras, boolean ordered, boolean sticky, 19184 int sendingUser) throws RemoteException { 19185 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19186 reportStatus ? 1 : 0, 1, keys); 19187 mHandler.sendMessage(msg); 19188 } 19189 }); 19190 } else { 19191 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19192 keys); 19193 mHandler.sendMessage(msg); 19194 } 19195 } 19196 19197 private void loadPrivatePackages(final VolumeInfo vol) { 19198 mHandler.post(new Runnable() { 19199 @Override 19200 public void run() { 19201 loadPrivatePackagesInner(vol); 19202 } 19203 }); 19204 } 19205 19206 private void loadPrivatePackagesInner(VolumeInfo vol) { 19207 final String volumeUuid = vol.fsUuid; 19208 if (TextUtils.isEmpty(volumeUuid)) { 19209 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19210 return; 19211 } 19212 19213 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19214 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19215 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19216 19217 final VersionInfo ver; 19218 final List<PackageSetting> packages; 19219 synchronized (mPackages) { 19220 ver = mSettings.findOrCreateVersion(volumeUuid); 19221 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19222 } 19223 19224 for (PackageSetting ps : packages) { 19225 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19226 synchronized (mInstallLock) { 19227 final PackageParser.Package pkg; 19228 try { 19229 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19230 loaded.add(pkg.applicationInfo); 19231 19232 } catch (PackageManagerException e) { 19233 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19234 } 19235 19236 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19237 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19238 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19239 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19240 } 19241 } 19242 } 19243 19244 // Reconcile app data for all started/unlocked users 19245 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19246 final UserManager um = mContext.getSystemService(UserManager.class); 19247 UserManagerInternal umInternal = getUserManagerInternal(); 19248 for (UserInfo user : um.getUsers()) { 19249 final int flags; 19250 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19251 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19252 } else if (umInternal.isUserRunning(user.id)) { 19253 flags = StorageManager.FLAG_STORAGE_DE; 19254 } else { 19255 continue; 19256 } 19257 19258 try { 19259 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19260 synchronized (mInstallLock) { 19261 reconcileAppsDataLI(volumeUuid, user.id, flags); 19262 } 19263 } catch (IllegalStateException e) { 19264 // Device was probably ejected, and we'll process that event momentarily 19265 Slog.w(TAG, "Failed to prepare storage: " + e); 19266 } 19267 } 19268 19269 synchronized (mPackages) { 19270 int updateFlags = UPDATE_PERMISSIONS_ALL; 19271 if (ver.sdkVersion != mSdkVersion) { 19272 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19273 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19274 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19275 } 19276 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19277 19278 // Yay, everything is now upgraded 19279 ver.forceCurrent(); 19280 19281 mSettings.writeLPr(); 19282 } 19283 19284 for (PackageFreezer freezer : freezers) { 19285 freezer.close(); 19286 } 19287 19288 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19289 sendResourcesChangedBroadcast(true, false, loaded, null); 19290 } 19291 19292 private void unloadPrivatePackages(final VolumeInfo vol) { 19293 mHandler.post(new Runnable() { 19294 @Override 19295 public void run() { 19296 unloadPrivatePackagesInner(vol); 19297 } 19298 }); 19299 } 19300 19301 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19302 final String volumeUuid = vol.fsUuid; 19303 if (TextUtils.isEmpty(volumeUuid)) { 19304 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19305 return; 19306 } 19307 19308 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19309 synchronized (mInstallLock) { 19310 synchronized (mPackages) { 19311 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19312 for (PackageSetting ps : packages) { 19313 if (ps.pkg == null) continue; 19314 19315 final ApplicationInfo info = ps.pkg.applicationInfo; 19316 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19317 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19318 19319 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19320 "unloadPrivatePackagesInner")) { 19321 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19322 false, null)) { 19323 unloaded.add(info); 19324 } else { 19325 Slog.w(TAG, "Failed to unload " + ps.codePath); 19326 } 19327 } 19328 19329 // Try very hard to release any references to this package 19330 // so we don't risk the system server being killed due to 19331 // open FDs 19332 AttributeCache.instance().removePackage(ps.name); 19333 } 19334 19335 mSettings.writeLPr(); 19336 } 19337 } 19338 19339 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19340 sendResourcesChangedBroadcast(false, false, unloaded, null); 19341 19342 // Try very hard to release any references to this path so we don't risk 19343 // the system server being killed due to open FDs 19344 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19345 19346 for (int i = 0; i < 3; i++) { 19347 System.gc(); 19348 System.runFinalization(); 19349 } 19350 } 19351 19352 /** 19353 * Prepare storage areas for given user on all mounted devices. 19354 */ 19355 void prepareUserData(int userId, int userSerial, int flags) { 19356 synchronized (mInstallLock) { 19357 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19358 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19359 final String volumeUuid = vol.getFsUuid(); 19360 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19361 } 19362 } 19363 } 19364 19365 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19366 boolean allowRecover) { 19367 // Prepare storage and verify that serial numbers are consistent; if 19368 // there's a mismatch we need to destroy to avoid leaking data 19369 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19370 try { 19371 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19372 19373 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19374 UserManagerService.enforceSerialNumber( 19375 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19376 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19377 UserManagerService.enforceSerialNumber( 19378 Environment.getDataSystemDeDirectory(userId), userSerial); 19379 } 19380 } 19381 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19382 UserManagerService.enforceSerialNumber( 19383 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19384 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19385 UserManagerService.enforceSerialNumber( 19386 Environment.getDataSystemCeDirectory(userId), userSerial); 19387 } 19388 } 19389 19390 synchronized (mInstallLock) { 19391 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19392 } 19393 } catch (Exception e) { 19394 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19395 + " because we failed to prepare: " + e); 19396 destroyUserDataLI(volumeUuid, userId, 19397 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19398 19399 if (allowRecover) { 19400 // Try one last time; if we fail again we're really in trouble 19401 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19402 } 19403 } 19404 } 19405 19406 /** 19407 * Destroy storage areas for given user on all mounted devices. 19408 */ 19409 void destroyUserData(int userId, int flags) { 19410 synchronized (mInstallLock) { 19411 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19412 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19413 final String volumeUuid = vol.getFsUuid(); 19414 destroyUserDataLI(volumeUuid, userId, flags); 19415 } 19416 } 19417 } 19418 19419 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19420 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19421 try { 19422 // Clean up app data, profile data, and media data 19423 mInstaller.destroyUserData(volumeUuid, userId, flags); 19424 19425 // Clean up system data 19426 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19427 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19428 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19429 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19430 } 19431 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19432 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19433 } 19434 } 19435 19436 // Data with special labels is now gone, so finish the job 19437 storage.destroyUserStorage(volumeUuid, userId, flags); 19438 19439 } catch (Exception e) { 19440 logCriticalInfo(Log.WARN, 19441 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19442 } 19443 } 19444 19445 /** 19446 * Examine all users present on given mounted volume, and destroy data 19447 * belonging to users that are no longer valid, or whose user ID has been 19448 * recycled. 19449 */ 19450 private void reconcileUsers(String volumeUuid) { 19451 final List<File> files = new ArrayList<>(); 19452 Collections.addAll(files, FileUtils 19453 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19454 Collections.addAll(files, FileUtils 19455 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19456 Collections.addAll(files, FileUtils 19457 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19458 Collections.addAll(files, FileUtils 19459 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19460 for (File file : files) { 19461 if (!file.isDirectory()) continue; 19462 19463 final int userId; 19464 final UserInfo info; 19465 try { 19466 userId = Integer.parseInt(file.getName()); 19467 info = sUserManager.getUserInfo(userId); 19468 } catch (NumberFormatException e) { 19469 Slog.w(TAG, "Invalid user directory " + file); 19470 continue; 19471 } 19472 19473 boolean destroyUser = false; 19474 if (info == null) { 19475 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19476 + " because no matching user was found"); 19477 destroyUser = true; 19478 } else if (!mOnlyCore) { 19479 try { 19480 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19481 } catch (IOException e) { 19482 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19483 + " because we failed to enforce serial number: " + e); 19484 destroyUser = true; 19485 } 19486 } 19487 19488 if (destroyUser) { 19489 synchronized (mInstallLock) { 19490 destroyUserDataLI(volumeUuid, userId, 19491 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19492 } 19493 } 19494 } 19495 } 19496 19497 private void assertPackageKnown(String volumeUuid, String packageName) 19498 throws PackageManagerException { 19499 synchronized (mPackages) { 19500 final PackageSetting ps = mSettings.mPackages.get(packageName); 19501 if (ps == null) { 19502 throw new PackageManagerException("Package " + packageName + " is unknown"); 19503 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19504 throw new PackageManagerException( 19505 "Package " + packageName + " found on unknown volume " + volumeUuid 19506 + "; expected volume " + ps.volumeUuid); 19507 } 19508 } 19509 } 19510 19511 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19512 throws PackageManagerException { 19513 synchronized (mPackages) { 19514 final PackageSetting ps = mSettings.mPackages.get(packageName); 19515 if (ps == null) { 19516 throw new PackageManagerException("Package " + packageName + " is unknown"); 19517 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19518 throw new PackageManagerException( 19519 "Package " + packageName + " found on unknown volume " + volumeUuid 19520 + "; expected volume " + ps.volumeUuid); 19521 } else if (!ps.getInstalled(userId)) { 19522 throw new PackageManagerException( 19523 "Package " + packageName + " not installed for user " + userId); 19524 } 19525 } 19526 } 19527 19528 /** 19529 * Examine all apps present on given mounted volume, and destroy apps that 19530 * aren't expected, either due to uninstallation or reinstallation on 19531 * another volume. 19532 */ 19533 private void reconcileApps(String volumeUuid) { 19534 final File[] files = FileUtils 19535 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19536 for (File file : files) { 19537 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19538 && !PackageInstallerService.isStageName(file.getName()); 19539 if (!isPackage) { 19540 // Ignore entries which are not packages 19541 continue; 19542 } 19543 19544 try { 19545 final PackageLite pkg = PackageParser.parsePackageLite(file, 19546 PackageParser.PARSE_MUST_BE_APK); 19547 assertPackageKnown(volumeUuid, pkg.packageName); 19548 19549 } catch (PackageParserException | PackageManagerException e) { 19550 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19551 synchronized (mInstallLock) { 19552 removeCodePathLI(file); 19553 } 19554 } 19555 } 19556 } 19557 19558 /** 19559 * Reconcile all app data for the given user. 19560 * <p> 19561 * Verifies that directories exist and that ownership and labeling is 19562 * correct for all installed apps on all mounted volumes. 19563 */ 19564 void reconcileAppsData(int userId, int flags) { 19565 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19566 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19567 final String volumeUuid = vol.getFsUuid(); 19568 synchronized (mInstallLock) { 19569 reconcileAppsDataLI(volumeUuid, userId, flags); 19570 } 19571 } 19572 } 19573 19574 /** 19575 * Reconcile all app data on given mounted volume. 19576 * <p> 19577 * Destroys app data that isn't expected, either due to uninstallation or 19578 * reinstallation on another volume. 19579 * <p> 19580 * Verifies that directories exist and that ownership and labeling is 19581 * correct for all installed apps. 19582 */ 19583 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19584 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19585 + Integer.toHexString(flags)); 19586 19587 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19588 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19589 19590 boolean restoreconNeeded = false; 19591 19592 // First look for stale data that doesn't belong, and check if things 19593 // have changed since we did our last restorecon 19594 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19595 if (StorageManager.isFileEncryptedNativeOrEmulated() 19596 && !StorageManager.isUserKeyUnlocked(userId)) { 19597 throw new RuntimeException( 19598 "Yikes, someone asked us to reconcile CE storage while " + userId 19599 + " was still locked; this would have caused massive data loss!"); 19600 } 19601 19602 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19603 19604 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19605 for (File file : files) { 19606 final String packageName = file.getName(); 19607 try { 19608 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19609 } catch (PackageManagerException e) { 19610 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19611 try { 19612 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19613 StorageManager.FLAG_STORAGE_CE, 0); 19614 } catch (InstallerException e2) { 19615 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19616 } 19617 } 19618 } 19619 } 19620 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19621 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19622 19623 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19624 for (File file : files) { 19625 final String packageName = file.getName(); 19626 try { 19627 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19628 } catch (PackageManagerException e) { 19629 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19630 try { 19631 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19632 StorageManager.FLAG_STORAGE_DE, 0); 19633 } catch (InstallerException e2) { 19634 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19635 } 19636 } 19637 } 19638 } 19639 19640 // Ensure that data directories are ready to roll for all packages 19641 // installed for this volume and user 19642 final List<PackageSetting> packages; 19643 synchronized (mPackages) { 19644 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19645 } 19646 int preparedCount = 0; 19647 for (PackageSetting ps : packages) { 19648 final String packageName = ps.name; 19649 if (ps.pkg == null) { 19650 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19651 // TODO: might be due to legacy ASEC apps; we should circle back 19652 // and reconcile again once they're scanned 19653 continue; 19654 } 19655 19656 if (ps.getInstalled(userId)) { 19657 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19658 19659 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19660 // We may have just shuffled around app data directories, so 19661 // prepare them one more time 19662 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19663 } 19664 19665 preparedCount++; 19666 } 19667 } 19668 19669 if (restoreconNeeded) { 19670 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19671 SELinuxMMAC.setRestoreconDone(ceDir); 19672 } 19673 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19674 SELinuxMMAC.setRestoreconDone(deDir); 19675 } 19676 } 19677 19678 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19679 + " packages; restoreconNeeded was " + restoreconNeeded); 19680 } 19681 19682 /** 19683 * Prepare app data for the given app just after it was installed or 19684 * upgraded. This method carefully only touches users that it's installed 19685 * for, and it forces a restorecon to handle any seinfo changes. 19686 * <p> 19687 * Verifies that directories exist and that ownership and labeling is 19688 * correct for all installed apps. If there is an ownership mismatch, it 19689 * will try recovering system apps by wiping data; third-party app data is 19690 * left intact. 19691 * <p> 19692 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19693 */ 19694 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19695 final PackageSetting ps; 19696 synchronized (mPackages) { 19697 ps = mSettings.mPackages.get(pkg.packageName); 19698 mSettings.writeKernelMappingLPr(ps); 19699 } 19700 19701 final UserManager um = mContext.getSystemService(UserManager.class); 19702 UserManagerInternal umInternal = getUserManagerInternal(); 19703 for (UserInfo user : um.getUsers()) { 19704 final int flags; 19705 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19706 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19707 } else if (umInternal.isUserRunning(user.id)) { 19708 flags = StorageManager.FLAG_STORAGE_DE; 19709 } else { 19710 continue; 19711 } 19712 19713 if (ps.getInstalled(user.id)) { 19714 // Whenever an app changes, force a restorecon of its data 19715 // TODO: when user data is locked, mark that we're still dirty 19716 prepareAppDataLIF(pkg, user.id, flags, true); 19717 } 19718 } 19719 } 19720 19721 /** 19722 * Prepare app data for the given app. 19723 * <p> 19724 * Verifies that directories exist and that ownership and labeling is 19725 * correct for all installed apps. If there is an ownership mismatch, this 19726 * will try recovering system apps by wiping data; third-party app data is 19727 * left intact. 19728 */ 19729 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19730 boolean restoreconNeeded) { 19731 if (pkg == null) { 19732 Slog.wtf(TAG, "Package was null!", new Throwable()); 19733 return; 19734 } 19735 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19736 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19737 for (int i = 0; i < childCount; i++) { 19738 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19739 } 19740 } 19741 19742 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19743 boolean restoreconNeeded) { 19744 if (DEBUG_APP_DATA) { 19745 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19746 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19747 } 19748 19749 final String volumeUuid = pkg.volumeUuid; 19750 final String packageName = pkg.packageName; 19751 final ApplicationInfo app = pkg.applicationInfo; 19752 final int appId = UserHandle.getAppId(app.uid); 19753 19754 Preconditions.checkNotNull(app.seinfo); 19755 19756 try { 19757 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19758 appId, app.seinfo, app.targetSdkVersion); 19759 } catch (InstallerException e) { 19760 if (app.isSystemApp()) { 19761 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19762 + ", but trying to recover: " + e); 19763 destroyAppDataLeafLIF(pkg, userId, flags); 19764 try { 19765 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19766 appId, app.seinfo, app.targetSdkVersion); 19767 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19768 } catch (InstallerException e2) { 19769 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19770 } 19771 } else { 19772 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19773 } 19774 } 19775 19776 if (restoreconNeeded) { 19777 try { 19778 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19779 app.seinfo); 19780 } catch (InstallerException e) { 19781 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19782 } 19783 } 19784 19785 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19786 try { 19787 // CE storage is unlocked right now, so read out the inode and 19788 // remember for use later when it's locked 19789 // TODO: mark this structure as dirty so we persist it! 19790 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19791 StorageManager.FLAG_STORAGE_CE); 19792 synchronized (mPackages) { 19793 final PackageSetting ps = mSettings.mPackages.get(packageName); 19794 if (ps != null) { 19795 ps.setCeDataInode(ceDataInode, userId); 19796 } 19797 } 19798 } catch (InstallerException e) { 19799 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19800 } 19801 } 19802 19803 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19804 } 19805 19806 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19807 if (pkg == null) { 19808 Slog.wtf(TAG, "Package was null!", new Throwable()); 19809 return; 19810 } 19811 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19812 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19813 for (int i = 0; i < childCount; i++) { 19814 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19815 } 19816 } 19817 19818 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19819 final String volumeUuid = pkg.volumeUuid; 19820 final String packageName = pkg.packageName; 19821 final ApplicationInfo app = pkg.applicationInfo; 19822 19823 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19824 // Create a native library symlink only if we have native libraries 19825 // and if the native libraries are 32 bit libraries. We do not provide 19826 // this symlink for 64 bit libraries. 19827 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19828 final String nativeLibPath = app.nativeLibraryDir; 19829 try { 19830 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19831 nativeLibPath, userId); 19832 } catch (InstallerException e) { 19833 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19834 } 19835 } 19836 } 19837 } 19838 19839 /** 19840 * For system apps on non-FBE devices, this method migrates any existing 19841 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19842 * requested by the app. 19843 */ 19844 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19845 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19846 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19847 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19848 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19849 try { 19850 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19851 storageTarget); 19852 } catch (InstallerException e) { 19853 logCriticalInfo(Log.WARN, 19854 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19855 } 19856 return true; 19857 } else { 19858 return false; 19859 } 19860 } 19861 19862 public PackageFreezer freezePackage(String packageName, String killReason) { 19863 return new PackageFreezer(packageName, killReason); 19864 } 19865 19866 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19867 String killReason) { 19868 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19869 return new PackageFreezer(); 19870 } else { 19871 return freezePackage(packageName, killReason); 19872 } 19873 } 19874 19875 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19876 String killReason) { 19877 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19878 return new PackageFreezer(); 19879 } else { 19880 return freezePackage(packageName, killReason); 19881 } 19882 } 19883 19884 /** 19885 * Class that freezes and kills the given package upon creation, and 19886 * unfreezes it upon closing. This is typically used when doing surgery on 19887 * app code/data to prevent the app from running while you're working. 19888 */ 19889 private class PackageFreezer implements AutoCloseable { 19890 private final String mPackageName; 19891 private final PackageFreezer[] mChildren; 19892 19893 private final boolean mWeFroze; 19894 19895 private final AtomicBoolean mClosed = new AtomicBoolean(); 19896 private final CloseGuard mCloseGuard = CloseGuard.get(); 19897 19898 /** 19899 * Create and return a stub freezer that doesn't actually do anything, 19900 * typically used when someone requested 19901 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19902 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19903 */ 19904 public PackageFreezer() { 19905 mPackageName = null; 19906 mChildren = null; 19907 mWeFroze = false; 19908 mCloseGuard.open("close"); 19909 } 19910 19911 public PackageFreezer(String packageName, String killReason) { 19912 synchronized (mPackages) { 19913 mPackageName = packageName; 19914 mWeFroze = mFrozenPackages.add(mPackageName); 19915 19916 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19917 if (ps != null) { 19918 killApplication(ps.name, ps.appId, killReason); 19919 } 19920 19921 final PackageParser.Package p = mPackages.get(packageName); 19922 if (p != null && p.childPackages != null) { 19923 final int N = p.childPackages.size(); 19924 mChildren = new PackageFreezer[N]; 19925 for (int i = 0; i < N; i++) { 19926 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19927 killReason); 19928 } 19929 } else { 19930 mChildren = null; 19931 } 19932 } 19933 mCloseGuard.open("close"); 19934 } 19935 19936 @Override 19937 protected void finalize() throws Throwable { 19938 try { 19939 mCloseGuard.warnIfOpen(); 19940 close(); 19941 } finally { 19942 super.finalize(); 19943 } 19944 } 19945 19946 @Override 19947 public void close() { 19948 mCloseGuard.close(); 19949 if (mClosed.compareAndSet(false, true)) { 19950 synchronized (mPackages) { 19951 if (mWeFroze) { 19952 mFrozenPackages.remove(mPackageName); 19953 } 19954 19955 if (mChildren != null) { 19956 for (PackageFreezer freezer : mChildren) { 19957 freezer.close(); 19958 } 19959 } 19960 } 19961 } 19962 } 19963 } 19964 19965 /** 19966 * Verify that given package is currently frozen. 19967 */ 19968 private void checkPackageFrozen(String packageName) { 19969 synchronized (mPackages) { 19970 if (!mFrozenPackages.contains(packageName)) { 19971 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19972 } 19973 } 19974 } 19975 19976 @Override 19977 public int movePackage(final String packageName, final String volumeUuid) { 19978 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19979 19980 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19981 final int moveId = mNextMoveId.getAndIncrement(); 19982 mHandler.post(new Runnable() { 19983 @Override 19984 public void run() { 19985 try { 19986 movePackageInternal(packageName, volumeUuid, moveId, user); 19987 } catch (PackageManagerException e) { 19988 Slog.w(TAG, "Failed to move " + packageName, e); 19989 mMoveCallbacks.notifyStatusChanged(moveId, 19990 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19991 } 19992 } 19993 }); 19994 return moveId; 19995 } 19996 19997 private void movePackageInternal(final String packageName, final String volumeUuid, 19998 final int moveId, UserHandle user) throws PackageManagerException { 19999 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20000 final PackageManager pm = mContext.getPackageManager(); 20001 20002 final boolean currentAsec; 20003 final String currentVolumeUuid; 20004 final File codeFile; 20005 final String installerPackageName; 20006 final String packageAbiOverride; 20007 final int appId; 20008 final String seinfo; 20009 final String label; 20010 final int targetSdkVersion; 20011 final PackageFreezer freezer; 20012 final int[] installedUserIds; 20013 20014 // reader 20015 synchronized (mPackages) { 20016 final PackageParser.Package pkg = mPackages.get(packageName); 20017 final PackageSetting ps = mSettings.mPackages.get(packageName); 20018 if (pkg == null || ps == null) { 20019 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20020 } 20021 20022 if (pkg.applicationInfo.isSystemApp()) { 20023 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20024 "Cannot move system application"); 20025 } 20026 20027 if (pkg.applicationInfo.isExternalAsec()) { 20028 currentAsec = true; 20029 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20030 } else if (pkg.applicationInfo.isForwardLocked()) { 20031 currentAsec = true; 20032 currentVolumeUuid = "forward_locked"; 20033 } else { 20034 currentAsec = false; 20035 currentVolumeUuid = ps.volumeUuid; 20036 20037 final File probe = new File(pkg.codePath); 20038 final File probeOat = new File(probe, "oat"); 20039 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20040 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20041 "Move only supported for modern cluster style installs"); 20042 } 20043 } 20044 20045 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20046 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20047 "Package already moved to " + volumeUuid); 20048 } 20049 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20050 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20051 "Device admin cannot be moved"); 20052 } 20053 20054 if (mFrozenPackages.contains(packageName)) { 20055 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20056 "Failed to move already frozen package"); 20057 } 20058 20059 codeFile = new File(pkg.codePath); 20060 installerPackageName = ps.installerPackageName; 20061 packageAbiOverride = ps.cpuAbiOverrideString; 20062 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20063 seinfo = pkg.applicationInfo.seinfo; 20064 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20065 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20066 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20067 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20068 } 20069 20070 final Bundle extras = new Bundle(); 20071 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20072 extras.putString(Intent.EXTRA_TITLE, label); 20073 mMoveCallbacks.notifyCreated(moveId, extras); 20074 20075 int installFlags; 20076 final boolean moveCompleteApp; 20077 final File measurePath; 20078 20079 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20080 installFlags = INSTALL_INTERNAL; 20081 moveCompleteApp = !currentAsec; 20082 measurePath = Environment.getDataAppDirectory(volumeUuid); 20083 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20084 installFlags = INSTALL_EXTERNAL; 20085 moveCompleteApp = false; 20086 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20087 } else { 20088 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20089 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20090 || !volume.isMountedWritable()) { 20091 freezer.close(); 20092 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20093 "Move location not mounted private volume"); 20094 } 20095 20096 Preconditions.checkState(!currentAsec); 20097 20098 installFlags = INSTALL_INTERNAL; 20099 moveCompleteApp = true; 20100 measurePath = Environment.getDataAppDirectory(volumeUuid); 20101 } 20102 20103 final PackageStats stats = new PackageStats(null, -1); 20104 synchronized (mInstaller) { 20105 for (int userId : installedUserIds) { 20106 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20107 freezer.close(); 20108 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20109 "Failed to measure package size"); 20110 } 20111 } 20112 } 20113 20114 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20115 + stats.dataSize); 20116 20117 final long startFreeBytes = measurePath.getFreeSpace(); 20118 final long sizeBytes; 20119 if (moveCompleteApp) { 20120 sizeBytes = stats.codeSize + stats.dataSize; 20121 } else { 20122 sizeBytes = stats.codeSize; 20123 } 20124 20125 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20126 freezer.close(); 20127 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20128 "Not enough free space to move"); 20129 } 20130 20131 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20132 20133 final CountDownLatch installedLatch = new CountDownLatch(1); 20134 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20135 @Override 20136 public void onUserActionRequired(Intent intent) throws RemoteException { 20137 throw new IllegalStateException(); 20138 } 20139 20140 @Override 20141 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20142 Bundle extras) throws RemoteException { 20143 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20144 + PackageManager.installStatusToString(returnCode, msg)); 20145 20146 installedLatch.countDown(); 20147 freezer.close(); 20148 20149 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20150 switch (status) { 20151 case PackageInstaller.STATUS_SUCCESS: 20152 mMoveCallbacks.notifyStatusChanged(moveId, 20153 PackageManager.MOVE_SUCCEEDED); 20154 break; 20155 case PackageInstaller.STATUS_FAILURE_STORAGE: 20156 mMoveCallbacks.notifyStatusChanged(moveId, 20157 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20158 break; 20159 default: 20160 mMoveCallbacks.notifyStatusChanged(moveId, 20161 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20162 break; 20163 } 20164 } 20165 }; 20166 20167 final MoveInfo move; 20168 if (moveCompleteApp) { 20169 // Kick off a thread to report progress estimates 20170 new Thread() { 20171 @Override 20172 public void run() { 20173 while (true) { 20174 try { 20175 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20176 break; 20177 } 20178 } catch (InterruptedException ignored) { 20179 } 20180 20181 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20182 final int progress = 10 + (int) MathUtils.constrain( 20183 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20184 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20185 } 20186 } 20187 }.start(); 20188 20189 final String dataAppName = codeFile.getName(); 20190 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20191 dataAppName, appId, seinfo, targetSdkVersion); 20192 } else { 20193 move = null; 20194 } 20195 20196 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20197 20198 final Message msg = mHandler.obtainMessage(INIT_COPY); 20199 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20200 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20201 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20202 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20203 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20204 msg.obj = params; 20205 20206 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20207 System.identityHashCode(msg.obj)); 20208 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20209 System.identityHashCode(msg.obj)); 20210 20211 mHandler.sendMessage(msg); 20212 } 20213 20214 @Override 20215 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20217 20218 final int realMoveId = mNextMoveId.getAndIncrement(); 20219 final Bundle extras = new Bundle(); 20220 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20221 mMoveCallbacks.notifyCreated(realMoveId, extras); 20222 20223 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20224 @Override 20225 public void onCreated(int moveId, Bundle extras) { 20226 // Ignored 20227 } 20228 20229 @Override 20230 public void onStatusChanged(int moveId, int status, long estMillis) { 20231 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20232 } 20233 }; 20234 20235 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20236 storage.setPrimaryStorageUuid(volumeUuid, callback); 20237 return realMoveId; 20238 } 20239 20240 @Override 20241 public int getMoveStatus(int moveId) { 20242 mContext.enforceCallingOrSelfPermission( 20243 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20244 return mMoveCallbacks.mLastStatus.get(moveId); 20245 } 20246 20247 @Override 20248 public void registerMoveCallback(IPackageMoveObserver callback) { 20249 mContext.enforceCallingOrSelfPermission( 20250 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20251 mMoveCallbacks.register(callback); 20252 } 20253 20254 @Override 20255 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20256 mContext.enforceCallingOrSelfPermission( 20257 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20258 mMoveCallbacks.unregister(callback); 20259 } 20260 20261 @Override 20262 public boolean setInstallLocation(int loc) { 20263 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20264 null); 20265 if (getInstallLocation() == loc) { 20266 return true; 20267 } 20268 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20269 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20270 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20271 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20272 return true; 20273 } 20274 return false; 20275 } 20276 20277 @Override 20278 public int getInstallLocation() { 20279 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20280 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20281 PackageHelper.APP_INSTALL_AUTO); 20282 } 20283 20284 /** Called by UserManagerService */ 20285 void cleanUpUser(UserManagerService userManager, int userHandle) { 20286 synchronized (mPackages) { 20287 mDirtyUsers.remove(userHandle); 20288 mUserNeedsBadging.delete(userHandle); 20289 mSettings.removeUserLPw(userHandle); 20290 mPendingBroadcasts.remove(userHandle); 20291 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20292 removeUnusedPackagesLPw(userManager, userHandle); 20293 } 20294 } 20295 20296 /** 20297 * We're removing userHandle and would like to remove any downloaded packages 20298 * that are no longer in use by any other user. 20299 * @param userHandle the user being removed 20300 */ 20301 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20302 final boolean DEBUG_CLEAN_APKS = false; 20303 int [] users = userManager.getUserIds(); 20304 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20305 while (psit.hasNext()) { 20306 PackageSetting ps = psit.next(); 20307 if (ps.pkg == null) { 20308 continue; 20309 } 20310 final String packageName = ps.pkg.packageName; 20311 // Skip over if system app 20312 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20313 continue; 20314 } 20315 if (DEBUG_CLEAN_APKS) { 20316 Slog.i(TAG, "Checking package " + packageName); 20317 } 20318 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20319 if (keep) { 20320 if (DEBUG_CLEAN_APKS) { 20321 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20322 } 20323 } else { 20324 for (int i = 0; i < users.length; i++) { 20325 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20326 keep = true; 20327 if (DEBUG_CLEAN_APKS) { 20328 Slog.i(TAG, " Keeping package " + packageName + " for user " 20329 + users[i]); 20330 } 20331 break; 20332 } 20333 } 20334 } 20335 if (!keep) { 20336 if (DEBUG_CLEAN_APKS) { 20337 Slog.i(TAG, " Removing package " + packageName); 20338 } 20339 mHandler.post(new Runnable() { 20340 public void run() { 20341 deletePackageX(packageName, userHandle, 0); 20342 } //end run 20343 }); 20344 } 20345 } 20346 } 20347 20348 /** Called by UserManagerService */ 20349 void createNewUser(int userId) { 20350 synchronized (mInstallLock) { 20351 mSettings.createNewUserLI(this, mInstaller, userId); 20352 } 20353 synchronized (mPackages) { 20354 scheduleWritePackageRestrictionsLocked(userId); 20355 scheduleWritePackageListLocked(userId); 20356 applyFactoryDefaultBrowserLPw(userId); 20357 primeDomainVerificationsLPw(userId); 20358 } 20359 } 20360 20361 void onBeforeUserStartUninitialized(final int userId) { 20362 synchronized (mPackages) { 20363 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20364 return; 20365 } 20366 } 20367 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20368 // If permission review for legacy apps is required, we represent 20369 // dagerous permissions for such apps as always granted runtime 20370 // permissions to keep per user flag state whether review is needed. 20371 // Hence, if a new user is added we have to propagate dangerous 20372 // permission grants for these legacy apps. 20373 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20374 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20375 | UPDATE_PERMISSIONS_REPLACE_ALL); 20376 } 20377 } 20378 20379 @Override 20380 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20381 mContext.enforceCallingOrSelfPermission( 20382 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20383 "Only package verification agents can read the verifier device identity"); 20384 20385 synchronized (mPackages) { 20386 return mSettings.getVerifierDeviceIdentityLPw(); 20387 } 20388 } 20389 20390 @Override 20391 public void setPermissionEnforced(String permission, boolean enforced) { 20392 // TODO: Now that we no longer change GID for storage, this should to away. 20393 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20394 "setPermissionEnforced"); 20395 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20396 synchronized (mPackages) { 20397 if (mSettings.mReadExternalStorageEnforced == null 20398 || mSettings.mReadExternalStorageEnforced != enforced) { 20399 mSettings.mReadExternalStorageEnforced = enforced; 20400 mSettings.writeLPr(); 20401 } 20402 } 20403 // kill any non-foreground processes so we restart them and 20404 // grant/revoke the GID. 20405 final IActivityManager am = ActivityManagerNative.getDefault(); 20406 if (am != null) { 20407 final long token = Binder.clearCallingIdentity(); 20408 try { 20409 am.killProcessesBelowForeground("setPermissionEnforcement"); 20410 } catch (RemoteException e) { 20411 } finally { 20412 Binder.restoreCallingIdentity(token); 20413 } 20414 } 20415 } else { 20416 throw new IllegalArgumentException("No selective enforcement for " + permission); 20417 } 20418 } 20419 20420 @Override 20421 @Deprecated 20422 public boolean isPermissionEnforced(String permission) { 20423 return true; 20424 } 20425 20426 @Override 20427 public boolean isStorageLow() { 20428 final long token = Binder.clearCallingIdentity(); 20429 try { 20430 final DeviceStorageMonitorInternal 20431 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20432 if (dsm != null) { 20433 return dsm.isMemoryLow(); 20434 } else { 20435 return false; 20436 } 20437 } finally { 20438 Binder.restoreCallingIdentity(token); 20439 } 20440 } 20441 20442 @Override 20443 public IPackageInstaller getPackageInstaller() { 20444 return mInstallerService; 20445 } 20446 20447 private boolean userNeedsBadging(int userId) { 20448 int index = mUserNeedsBadging.indexOfKey(userId); 20449 if (index < 0) { 20450 final UserInfo userInfo; 20451 final long token = Binder.clearCallingIdentity(); 20452 try { 20453 userInfo = sUserManager.getUserInfo(userId); 20454 } finally { 20455 Binder.restoreCallingIdentity(token); 20456 } 20457 final boolean b; 20458 if (userInfo != null && userInfo.isManagedProfile()) { 20459 b = true; 20460 } else { 20461 b = false; 20462 } 20463 mUserNeedsBadging.put(userId, b); 20464 return b; 20465 } 20466 return mUserNeedsBadging.valueAt(index); 20467 } 20468 20469 @Override 20470 public KeySet getKeySetByAlias(String packageName, String alias) { 20471 if (packageName == null || alias == null) { 20472 return null; 20473 } 20474 synchronized(mPackages) { 20475 final PackageParser.Package pkg = mPackages.get(packageName); 20476 if (pkg == null) { 20477 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20478 throw new IllegalArgumentException("Unknown package: " + packageName); 20479 } 20480 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20481 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20482 } 20483 } 20484 20485 @Override 20486 public KeySet getSigningKeySet(String packageName) { 20487 if (packageName == null) { 20488 return null; 20489 } 20490 synchronized(mPackages) { 20491 final PackageParser.Package pkg = mPackages.get(packageName); 20492 if (pkg == null) { 20493 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20494 throw new IllegalArgumentException("Unknown package: " + packageName); 20495 } 20496 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20497 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20498 throw new SecurityException("May not access signing KeySet of other apps."); 20499 } 20500 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20501 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20502 } 20503 } 20504 20505 @Override 20506 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20507 if (packageName == null || ks == null) { 20508 return false; 20509 } 20510 synchronized(mPackages) { 20511 final PackageParser.Package pkg = mPackages.get(packageName); 20512 if (pkg == null) { 20513 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20514 throw new IllegalArgumentException("Unknown package: " + packageName); 20515 } 20516 IBinder ksh = ks.getToken(); 20517 if (ksh instanceof KeySetHandle) { 20518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20519 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20520 } 20521 return false; 20522 } 20523 } 20524 20525 @Override 20526 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20527 if (packageName == null || ks == null) { 20528 return false; 20529 } 20530 synchronized(mPackages) { 20531 final PackageParser.Package pkg = mPackages.get(packageName); 20532 if (pkg == null) { 20533 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20534 throw new IllegalArgumentException("Unknown package: " + packageName); 20535 } 20536 IBinder ksh = ks.getToken(); 20537 if (ksh instanceof KeySetHandle) { 20538 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20539 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20540 } 20541 return false; 20542 } 20543 } 20544 20545 private void deletePackageIfUnusedLPr(final String packageName) { 20546 PackageSetting ps = mSettings.mPackages.get(packageName); 20547 if (ps == null) { 20548 return; 20549 } 20550 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20551 // TODO Implement atomic delete if package is unused 20552 // It is currently possible that the package will be deleted even if it is installed 20553 // after this method returns. 20554 mHandler.post(new Runnable() { 20555 public void run() { 20556 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20557 } 20558 }); 20559 } 20560 } 20561 20562 /** 20563 * Check and throw if the given before/after packages would be considered a 20564 * downgrade. 20565 */ 20566 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20567 throws PackageManagerException { 20568 if (after.versionCode < before.mVersionCode) { 20569 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20570 "Update version code " + after.versionCode + " is older than current " 20571 + before.mVersionCode); 20572 } else if (after.versionCode == before.mVersionCode) { 20573 if (after.baseRevisionCode < before.baseRevisionCode) { 20574 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20575 "Update base revision code " + after.baseRevisionCode 20576 + " is older than current " + before.baseRevisionCode); 20577 } 20578 20579 if (!ArrayUtils.isEmpty(after.splitNames)) { 20580 for (int i = 0; i < after.splitNames.length; i++) { 20581 final String splitName = after.splitNames[i]; 20582 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20583 if (j != -1) { 20584 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20585 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20586 "Update split " + splitName + " revision code " 20587 + after.splitRevisionCodes[i] + " is older than current " 20588 + before.splitRevisionCodes[j]); 20589 } 20590 } 20591 } 20592 } 20593 } 20594 } 20595 20596 private static class MoveCallbacks extends Handler { 20597 private static final int MSG_CREATED = 1; 20598 private static final int MSG_STATUS_CHANGED = 2; 20599 20600 private final RemoteCallbackList<IPackageMoveObserver> 20601 mCallbacks = new RemoteCallbackList<>(); 20602 20603 private final SparseIntArray mLastStatus = new SparseIntArray(); 20604 20605 public MoveCallbacks(Looper looper) { 20606 super(looper); 20607 } 20608 20609 public void register(IPackageMoveObserver callback) { 20610 mCallbacks.register(callback); 20611 } 20612 20613 public void unregister(IPackageMoveObserver callback) { 20614 mCallbacks.unregister(callback); 20615 } 20616 20617 @Override 20618 public void handleMessage(Message msg) { 20619 final SomeArgs args = (SomeArgs) msg.obj; 20620 final int n = mCallbacks.beginBroadcast(); 20621 for (int i = 0; i < n; i++) { 20622 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20623 try { 20624 invokeCallback(callback, msg.what, args); 20625 } catch (RemoteException ignored) { 20626 } 20627 } 20628 mCallbacks.finishBroadcast(); 20629 args.recycle(); 20630 } 20631 20632 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20633 throws RemoteException { 20634 switch (what) { 20635 case MSG_CREATED: { 20636 callback.onCreated(args.argi1, (Bundle) args.arg2); 20637 break; 20638 } 20639 case MSG_STATUS_CHANGED: { 20640 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20641 break; 20642 } 20643 } 20644 } 20645 20646 private void notifyCreated(int moveId, Bundle extras) { 20647 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20648 20649 final SomeArgs args = SomeArgs.obtain(); 20650 args.argi1 = moveId; 20651 args.arg2 = extras; 20652 obtainMessage(MSG_CREATED, args).sendToTarget(); 20653 } 20654 20655 private void notifyStatusChanged(int moveId, int status) { 20656 notifyStatusChanged(moveId, status, -1); 20657 } 20658 20659 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20660 Slog.v(TAG, "Move " + moveId + " status " + status); 20661 20662 final SomeArgs args = SomeArgs.obtain(); 20663 args.argi1 = moveId; 20664 args.argi2 = status; 20665 args.arg3 = estMillis; 20666 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20667 20668 synchronized (mLastStatus) { 20669 mLastStatus.put(moveId, status); 20670 } 20671 } 20672 } 20673 20674 private final static class OnPermissionChangeListeners extends Handler { 20675 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20676 20677 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20678 new RemoteCallbackList<>(); 20679 20680 public OnPermissionChangeListeners(Looper looper) { 20681 super(looper); 20682 } 20683 20684 @Override 20685 public void handleMessage(Message msg) { 20686 switch (msg.what) { 20687 case MSG_ON_PERMISSIONS_CHANGED: { 20688 final int uid = msg.arg1; 20689 handleOnPermissionsChanged(uid); 20690 } break; 20691 } 20692 } 20693 20694 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20695 mPermissionListeners.register(listener); 20696 20697 } 20698 20699 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20700 mPermissionListeners.unregister(listener); 20701 } 20702 20703 public void onPermissionsChanged(int uid) { 20704 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20705 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20706 } 20707 } 20708 20709 private void handleOnPermissionsChanged(int uid) { 20710 final int count = mPermissionListeners.beginBroadcast(); 20711 try { 20712 for (int i = 0; i < count; i++) { 20713 IOnPermissionsChangeListener callback = mPermissionListeners 20714 .getBroadcastItem(i); 20715 try { 20716 callback.onPermissionsChanged(uid); 20717 } catch (RemoteException e) { 20718 Log.e(TAG, "Permission listener is dead", e); 20719 } 20720 } 20721 } finally { 20722 mPermissionListeners.finishBroadcast(); 20723 } 20724 } 20725 } 20726 20727 private class PackageManagerInternalImpl extends PackageManagerInternal { 20728 @Override 20729 public void setLocationPackagesProvider(PackagesProvider provider) { 20730 synchronized (mPackages) { 20731 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20732 } 20733 } 20734 20735 @Override 20736 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20737 synchronized (mPackages) { 20738 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20739 } 20740 } 20741 20742 @Override 20743 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20744 synchronized (mPackages) { 20745 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20746 } 20747 } 20748 20749 @Override 20750 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20751 synchronized (mPackages) { 20752 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20753 } 20754 } 20755 20756 @Override 20757 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20758 synchronized (mPackages) { 20759 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20760 } 20761 } 20762 20763 @Override 20764 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20765 synchronized (mPackages) { 20766 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20767 } 20768 } 20769 20770 @Override 20771 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20772 synchronized (mPackages) { 20773 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20774 packageName, userId); 20775 } 20776 } 20777 20778 @Override 20779 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20780 synchronized (mPackages) { 20781 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20782 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20783 packageName, userId); 20784 } 20785 } 20786 20787 @Override 20788 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20789 synchronized (mPackages) { 20790 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20791 packageName, userId); 20792 } 20793 } 20794 20795 @Override 20796 public void setKeepUninstalledPackages(final List<String> packageList) { 20797 Preconditions.checkNotNull(packageList); 20798 List<String> removedFromList = null; 20799 synchronized (mPackages) { 20800 if (mKeepUninstalledPackages != null) { 20801 final int packagesCount = mKeepUninstalledPackages.size(); 20802 for (int i = 0; i < packagesCount; i++) { 20803 String oldPackage = mKeepUninstalledPackages.get(i); 20804 if (packageList != null && packageList.contains(oldPackage)) { 20805 continue; 20806 } 20807 if (removedFromList == null) { 20808 removedFromList = new ArrayList<>(); 20809 } 20810 removedFromList.add(oldPackage); 20811 } 20812 } 20813 mKeepUninstalledPackages = new ArrayList<>(packageList); 20814 if (removedFromList != null) { 20815 final int removedCount = removedFromList.size(); 20816 for (int i = 0; i < removedCount; i++) { 20817 deletePackageIfUnusedLPr(removedFromList.get(i)); 20818 } 20819 } 20820 } 20821 } 20822 20823 @Override 20824 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20825 synchronized (mPackages) { 20826 // If we do not support permission review, done. 20827 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20828 return false; 20829 } 20830 20831 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20832 if (packageSetting == null) { 20833 return false; 20834 } 20835 20836 // Permission review applies only to apps not supporting the new permission model. 20837 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20838 return false; 20839 } 20840 20841 // Legacy apps have the permission and get user consent on launch. 20842 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20843 return permissionsState.isPermissionReviewRequired(userId); 20844 } 20845 } 20846 20847 @Override 20848 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20849 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20850 } 20851 20852 @Override 20853 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20854 int userId) { 20855 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20856 } 20857 20858 @Override 20859 public void setDeviceAndProfileOwnerPackages( 20860 int deviceOwnerUserId, String deviceOwnerPackage, 20861 SparseArray<String> profileOwnerPackages) { 20862 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20863 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20864 } 20865 20866 @Override 20867 public boolean canPackageBeWiped(int userId, String packageName) { 20868 return mProtectedPackages.canPackageBeWiped(userId, 20869 packageName); 20870 } 20871 } 20872 20873 @Override 20874 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20875 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20876 synchronized (mPackages) { 20877 final long identity = Binder.clearCallingIdentity(); 20878 try { 20879 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20880 packageNames, userId); 20881 } finally { 20882 Binder.restoreCallingIdentity(identity); 20883 } 20884 } 20885 } 20886 20887 private static void enforceSystemOrPhoneCaller(String tag) { 20888 int callingUid = Binder.getCallingUid(); 20889 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20890 throw new SecurityException( 20891 "Cannot call " + tag + " from UID " + callingUid); 20892 } 20893 } 20894 20895 boolean isHistoricalPackageUsageAvailable() { 20896 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20897 } 20898 20899 /** 20900 * Return a <b>copy</b> of the collection of packages known to the package manager. 20901 * @return A copy of the values of mPackages. 20902 */ 20903 Collection<PackageParser.Package> getPackages() { 20904 synchronized (mPackages) { 20905 return new ArrayList<>(mPackages.values()); 20906 } 20907 } 20908 20909 /** 20910 * Logs process start information (including base APK hash) to the security log. 20911 * @hide 20912 */ 20913 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20914 String apkFile, int pid) { 20915 if (!SecurityLog.isLoggingEnabled()) { 20916 return; 20917 } 20918 Bundle data = new Bundle(); 20919 data.putLong("startTimestamp", System.currentTimeMillis()); 20920 data.putString("processName", processName); 20921 data.putInt("uid", uid); 20922 data.putString("seinfo", seinfo); 20923 data.putString("apkFile", apkFile); 20924 data.putInt("pid", pid); 20925 Message msg = mProcessLoggingHandler.obtainMessage( 20926 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20927 msg.setData(data); 20928 mProcessLoggingHandler.sendMessage(msg); 20929 } 20930} 20931