PackageManagerService.java revision 092d9613676e841093ed1992b559aea455d56548
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 = 0xFFFFFFFF; 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.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1223 readVersion1LP(in, sb); 1224 } else { 1225 readVersion0LP(in, sb, firstLine); 1226 } 1227 } catch (FileNotFoundException expected) { 1228 mIsHistoricalPackageUsageAvailable = false; 1229 } catch (IOException e) { 1230 Log.w(TAG, "Failed to read package usage times", e); 1231 } finally { 1232 IoUtils.closeQuietly(in); 1233 } 1234 } 1235 mLastWritten.set(SystemClock.elapsedRealtime()); 1236 } 1237 1238 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1239 throws IOException { 1240 // Initial version of the file had no version number and stored one 1241 // package-timestamp pair per line. 1242 // Note that the first line has already been read from the InputStream. 1243 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1244 String[] tokens = line.split(" "); 1245 if (tokens.length != 2) { 1246 throw new IOException("Failed to parse " + line + 1247 " as package-timestamp pair."); 1248 } 1249 1250 String packageName = tokens[0]; 1251 PackageParser.Package pkg = mPackages.get(packageName); 1252 if (pkg == null) { 1253 continue; 1254 } 1255 1256 long timestamp = parseAsLong(tokens[1]); 1257 for (int reason = 0; 1258 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1259 reason++) { 1260 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1261 } 1262 } 1263 } 1264 1265 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1266 // Version 1 of the file started with the corresponding version 1267 // number and then stored a package name and eight timestamps per line. 1268 String line; 1269 while ((line = readLine(in, sb)) != null) { 1270 String[] tokens = line.split(" "); 1271 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1272 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1273 } 1274 1275 String packageName = tokens[0]; 1276 PackageParser.Package pkg = mPackages.get(packageName); 1277 if (pkg == null) { 1278 continue; 1279 } 1280 1281 for (int reason = 0; 1282 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1283 reason++) { 1284 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1285 } 1286 } 1287 } 1288 1289 private long parseAsLong(String token) throws IOException { 1290 try { 1291 return Long.parseLong(token); 1292 } catch (NumberFormatException e) { 1293 throw new IOException("Failed to parse " + token + " as a long.", e); 1294 } 1295 } 1296 1297 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1298 return readToken(in, sb, '\n'); 1299 } 1300 1301 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1302 throws IOException { 1303 sb.setLength(0); 1304 while (true) { 1305 int ch = in.read(); 1306 if (ch == -1) { 1307 if (sb.length() == 0) { 1308 return null; 1309 } 1310 throw new IOException("Unexpected EOF"); 1311 } 1312 if (ch == endOfToken) { 1313 return sb.toString(); 1314 } 1315 sb.append((char)ch); 1316 } 1317 } 1318 1319 private AtomicFile getFile() { 1320 File dataDir = Environment.getDataDirectory(); 1321 File systemDir = new File(dataDir, "system"); 1322 File fname = new File(systemDir, "package-usage.list"); 1323 return new AtomicFile(fname); 1324 } 1325 1326 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1327 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1328 } 1329 1330 class PackageHandler extends Handler { 1331 private boolean mBound = false; 1332 final ArrayList<HandlerParams> mPendingInstalls = 1333 new ArrayList<HandlerParams>(); 1334 1335 private boolean connectToService() { 1336 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1337 " DefaultContainerService"); 1338 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1341 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1342 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1343 mBound = true; 1344 return true; 1345 } 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1347 return false; 1348 } 1349 1350 private void disconnectService() { 1351 mContainerService = null; 1352 mBound = false; 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1354 mContext.unbindService(mDefContainerConn); 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1356 } 1357 1358 PackageHandler(Looper looper) { 1359 super(looper); 1360 } 1361 1362 public void handleMessage(Message msg) { 1363 try { 1364 doHandleMessage(msg); 1365 } finally { 1366 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1367 } 1368 } 1369 1370 void doHandleMessage(Message msg) { 1371 switch (msg.what) { 1372 case INIT_COPY: { 1373 HandlerParams params = (HandlerParams) msg.obj; 1374 int idx = mPendingInstalls.size(); 1375 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1376 // If a bind was already initiated we dont really 1377 // need to do anything. The pending install 1378 // will be processed later on. 1379 if (!mBound) { 1380 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1381 System.identityHashCode(mHandler)); 1382 // If this is the only one pending we might 1383 // have to bind to the service again. 1384 if (!connectToService()) { 1385 Slog.e(TAG, "Failed to bind to media container service"); 1386 params.serviceError(); 1387 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1388 System.identityHashCode(mHandler)); 1389 if (params.traceMethod != null) { 1390 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1391 params.traceCookie); 1392 } 1393 return; 1394 } else { 1395 // Once we bind to the service, the first 1396 // pending request will be processed. 1397 mPendingInstalls.add(idx, params); 1398 } 1399 } else { 1400 mPendingInstalls.add(idx, params); 1401 // Already bound to the service. Just make 1402 // sure we trigger off processing the first request. 1403 if (idx == 0) { 1404 mHandler.sendEmptyMessage(MCS_BOUND); 1405 } 1406 } 1407 break; 1408 } 1409 case MCS_BOUND: { 1410 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1411 if (msg.obj != null) { 1412 mContainerService = (IMediaContainerService) msg.obj; 1413 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1414 System.identityHashCode(mHandler)); 1415 } 1416 if (mContainerService == null) { 1417 if (!mBound) { 1418 // Something seriously wrong since we are not bound and we are not 1419 // waiting for connection. Bail out. 1420 Slog.e(TAG, "Cannot bind to media container service"); 1421 for (HandlerParams params : mPendingInstalls) { 1422 // Indicate service bind error 1423 params.serviceError(); 1424 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1425 System.identityHashCode(params)); 1426 if (params.traceMethod != null) { 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1428 params.traceMethod, params.traceCookie); 1429 } 1430 return; 1431 } 1432 mPendingInstalls.clear(); 1433 } else { 1434 Slog.w(TAG, "Waiting to connect to media container service"); 1435 } 1436 } else if (mPendingInstalls.size() > 0) { 1437 HandlerParams params = mPendingInstalls.get(0); 1438 if (params != null) { 1439 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1440 System.identityHashCode(params)); 1441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1442 if (params.startCopy()) { 1443 // We are done... look for more work or to 1444 // go idle. 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, 1446 "Checking for more work or unbind..."); 1447 // Delete pending install 1448 if (mPendingInstalls.size() > 0) { 1449 mPendingInstalls.remove(0); 1450 } 1451 if (mPendingInstalls.size() == 0) { 1452 if (mBound) { 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, 1454 "Posting delayed MCS_UNBIND"); 1455 removeMessages(MCS_UNBIND); 1456 Message ubmsg = obtainMessage(MCS_UNBIND); 1457 // Unbind after a little delay, to avoid 1458 // continual thrashing. 1459 sendMessageDelayed(ubmsg, 10000); 1460 } 1461 } else { 1462 // There are more pending requests in queue. 1463 // Just post MCS_BOUND message to trigger processing 1464 // of next pending install. 1465 if (DEBUG_SD_INSTALL) Log.i(TAG, 1466 "Posting MCS_BOUND for next work"); 1467 mHandler.sendEmptyMessage(MCS_BOUND); 1468 } 1469 } 1470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1471 } 1472 } else { 1473 // Should never happen ideally. 1474 Slog.w(TAG, "Empty queue"); 1475 } 1476 break; 1477 } 1478 case MCS_RECONNECT: { 1479 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1480 if (mPendingInstalls.size() > 0) { 1481 if (mBound) { 1482 disconnectService(); 1483 } 1484 if (!connectToService()) { 1485 Slog.e(TAG, "Failed to bind to media container service"); 1486 for (HandlerParams params : mPendingInstalls) { 1487 // Indicate service bind error 1488 params.serviceError(); 1489 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1490 System.identityHashCode(params)); 1491 } 1492 mPendingInstalls.clear(); 1493 } 1494 } 1495 break; 1496 } 1497 case MCS_UNBIND: { 1498 // If there is no actual work left, then time to unbind. 1499 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1500 1501 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1502 if (mBound) { 1503 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1504 1505 disconnectService(); 1506 } 1507 } else if (mPendingInstalls.size() > 0) { 1508 // There are more pending requests in queue. 1509 // Just post MCS_BOUND message to trigger processing 1510 // of next pending install. 1511 mHandler.sendEmptyMessage(MCS_BOUND); 1512 } 1513 1514 break; 1515 } 1516 case MCS_GIVE_UP: { 1517 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1518 HandlerParams params = mPendingInstalls.remove(0); 1519 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1520 System.identityHashCode(params)); 1521 break; 1522 } 1523 case SEND_PENDING_BROADCAST: { 1524 String packages[]; 1525 ArrayList<String> components[]; 1526 int size = 0; 1527 int uids[]; 1528 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1529 synchronized (mPackages) { 1530 if (mPendingBroadcasts == null) { 1531 return; 1532 } 1533 size = mPendingBroadcasts.size(); 1534 if (size <= 0) { 1535 // Nothing to be done. Just return 1536 return; 1537 } 1538 packages = new String[size]; 1539 components = new ArrayList[size]; 1540 uids = new int[size]; 1541 int i = 0; // filling out the above arrays 1542 1543 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1544 int packageUserId = mPendingBroadcasts.userIdAt(n); 1545 Iterator<Map.Entry<String, ArrayList<String>>> it 1546 = mPendingBroadcasts.packagesForUserId(packageUserId) 1547 .entrySet().iterator(); 1548 while (it.hasNext() && i < size) { 1549 Map.Entry<String, ArrayList<String>> ent = it.next(); 1550 packages[i] = ent.getKey(); 1551 components[i] = ent.getValue(); 1552 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1553 uids[i] = (ps != null) 1554 ? UserHandle.getUid(packageUserId, ps.appId) 1555 : -1; 1556 i++; 1557 } 1558 } 1559 size = i; 1560 mPendingBroadcasts.clear(); 1561 } 1562 // Send broadcasts 1563 for (int i = 0; i < size; i++) { 1564 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1565 } 1566 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1567 break; 1568 } 1569 case START_CLEANING_PACKAGE: { 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1571 final String packageName = (String)msg.obj; 1572 final int userId = msg.arg1; 1573 final boolean andCode = msg.arg2 != 0; 1574 synchronized (mPackages) { 1575 if (userId == UserHandle.USER_ALL) { 1576 int[] users = sUserManager.getUserIds(); 1577 for (int user : users) { 1578 mSettings.addPackageToCleanLPw( 1579 new PackageCleanItem(user, packageName, andCode)); 1580 } 1581 } else { 1582 mSettings.addPackageToCleanLPw( 1583 new PackageCleanItem(userId, packageName, andCode)); 1584 } 1585 } 1586 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1587 startCleaningPackages(); 1588 } break; 1589 case POST_INSTALL: { 1590 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1591 1592 PostInstallData data = mRunningInstalls.get(msg.arg1); 1593 final boolean didRestore = (msg.arg2 != 0); 1594 mRunningInstalls.delete(msg.arg1); 1595 1596 if (data != null) { 1597 InstallArgs args = data.args; 1598 PackageInstalledInfo parentRes = data.res; 1599 1600 final boolean grantPermissions = (args.installFlags 1601 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1602 final boolean killApp = (args.installFlags 1603 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1604 final String[] grantedPermissions = args.installGrantPermissions; 1605 1606 // Handle the parent package 1607 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1608 grantedPermissions, didRestore, args.installerPackageName, 1609 args.observer); 1610 1611 // Handle the child packages 1612 final int childCount = (parentRes.addedChildPackages != null) 1613 ? parentRes.addedChildPackages.size() : 0; 1614 for (int i = 0; i < childCount; i++) { 1615 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1616 handlePackagePostInstall(childRes, grantPermissions, killApp, 1617 grantedPermissions, false, args.installerPackageName, 1618 args.observer); 1619 } 1620 1621 // Log tracing if needed 1622 if (args.traceMethod != null) { 1623 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1624 args.traceCookie); 1625 } 1626 } else { 1627 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1628 } 1629 1630 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1631 } break; 1632 case UPDATED_MEDIA_STATUS: { 1633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1634 boolean reportStatus = msg.arg1 == 1; 1635 boolean doGc = msg.arg2 == 1; 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1637 if (doGc) { 1638 // Force a gc to clear up stale containers. 1639 Runtime.getRuntime().gc(); 1640 } 1641 if (msg.obj != null) { 1642 @SuppressWarnings("unchecked") 1643 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1644 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1645 // Unload containers 1646 unloadAllContainers(args); 1647 } 1648 if (reportStatus) { 1649 try { 1650 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1651 PackageHelper.getMountService().finishMediaUpdate(); 1652 } catch (RemoteException e) { 1653 Log.e(TAG, "MountService not running?"); 1654 } 1655 } 1656 } break; 1657 case WRITE_SETTINGS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_SETTINGS); 1661 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1662 mSettings.writeLPr(); 1663 mDirtyUsers.clear(); 1664 } 1665 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1666 } break; 1667 case WRITE_PACKAGE_RESTRICTIONS: { 1668 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1669 synchronized (mPackages) { 1670 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1671 for (int userId : mDirtyUsers) { 1672 mSettings.writePackageRestrictionsLPr(userId); 1673 } 1674 mDirtyUsers.clear(); 1675 } 1676 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1677 } break; 1678 case WRITE_PACKAGE_LIST: { 1679 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1680 synchronized (mPackages) { 1681 removeMessages(WRITE_PACKAGE_LIST); 1682 mSettings.writePackageListLPr(msg.arg1); 1683 } 1684 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1685 } break; 1686 case CHECK_PENDING_VERIFICATION: { 1687 final int verificationId = msg.arg1; 1688 final PackageVerificationState state = mPendingVerification.get(verificationId); 1689 1690 if ((state != null) && !state.timeoutExtended()) { 1691 final InstallArgs args = state.getInstallArgs(); 1692 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1693 1694 Slog.i(TAG, "Verification timed out for " + originUri); 1695 mPendingVerification.remove(verificationId); 1696 1697 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1698 1699 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1700 Slog.i(TAG, "Continuing with installation of " + originUri); 1701 state.setVerifierResponse(Binder.getCallingUid(), 1702 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1703 broadcastPackageVerified(verificationId, originUri, 1704 PackageManager.VERIFICATION_ALLOW, 1705 state.getInstallArgs().getUser()); 1706 try { 1707 ret = args.copyApk(mContainerService, true); 1708 } catch (RemoteException e) { 1709 Slog.e(TAG, "Could not contact the ContainerService"); 1710 } 1711 } else { 1712 broadcastPackageVerified(verificationId, originUri, 1713 PackageManager.VERIFICATION_REJECT, 1714 state.getInstallArgs().getUser()); 1715 } 1716 1717 Trace.asyncTraceEnd( 1718 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1719 1720 processPendingInstall(args, ret); 1721 mHandler.sendEmptyMessage(MCS_UNBIND); 1722 } 1723 break; 1724 } 1725 case PACKAGE_VERIFIED: { 1726 final int verificationId = msg.arg1; 1727 1728 final PackageVerificationState state = mPendingVerification.get(verificationId); 1729 if (state == null) { 1730 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1731 break; 1732 } 1733 1734 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1735 1736 state.setVerifierResponse(response.callerUid, response.code); 1737 1738 if (state.isVerificationComplete()) { 1739 mPendingVerification.remove(verificationId); 1740 1741 final InstallArgs args = state.getInstallArgs(); 1742 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1743 1744 int ret; 1745 if (state.isInstallAllowed()) { 1746 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1747 broadcastPackageVerified(verificationId, originUri, 1748 response.code, state.getInstallArgs().getUser()); 1749 try { 1750 ret = args.copyApk(mContainerService, true); 1751 } catch (RemoteException e) { 1752 Slog.e(TAG, "Could not contact the ContainerService"); 1753 } 1754 } else { 1755 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1756 } 1757 1758 Trace.asyncTraceEnd( 1759 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1760 1761 processPendingInstall(args, ret); 1762 mHandler.sendEmptyMessage(MCS_UNBIND); 1763 } 1764 1765 break; 1766 } 1767 case START_INTENT_FILTER_VERIFICATIONS: { 1768 IFVerificationParams params = (IFVerificationParams) msg.obj; 1769 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1770 params.replacing, params.pkg); 1771 break; 1772 } 1773 case INTENT_FILTER_VERIFIED: { 1774 final int verificationId = msg.arg1; 1775 1776 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1777 verificationId); 1778 if (state == null) { 1779 Slog.w(TAG, "Invalid IntentFilter verification token " 1780 + verificationId + " received"); 1781 break; 1782 } 1783 1784 final int userId = state.getUserId(); 1785 1786 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1787 "Processing IntentFilter verification with token:" 1788 + verificationId + " and userId:" + userId); 1789 1790 final IntentFilterVerificationResponse response = 1791 (IntentFilterVerificationResponse) msg.obj; 1792 1793 state.setVerifierResponse(response.callerUid, response.code); 1794 1795 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1796 "IntentFilter verification with token:" + verificationId 1797 + " and userId:" + userId 1798 + " is settings verifier response with response code:" 1799 + response.code); 1800 1801 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1803 + response.getFailedDomainsString()); 1804 } 1805 1806 if (state.isVerificationComplete()) { 1807 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1808 } else { 1809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1810 "IntentFilter verification with token:" + verificationId 1811 + " was not said to be complete"); 1812 } 1813 1814 break; 1815 } 1816 } 1817 } 1818 } 1819 1820 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1821 boolean killApp, String[] grantedPermissions, 1822 boolean launchedForRestore, String installerPackage, 1823 IPackageInstallObserver2 installObserver) { 1824 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1825 // Send the removed broadcasts 1826 if (res.removedInfo != null) { 1827 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1828 } 1829 1830 // Now that we successfully installed the package, grant runtime 1831 // permissions if requested before broadcasting the install. 1832 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1833 >= Build.VERSION_CODES.M) { 1834 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1835 } 1836 1837 final boolean update = res.removedInfo != null 1838 && res.removedInfo.removedPackage != null; 1839 1840 // If this is the first time we have child packages for a disabled privileged 1841 // app that had no children, we grant requested runtime permissions to the new 1842 // children if the parent on the system image had them already granted. 1843 if (res.pkg.parentPackage != null) { 1844 synchronized (mPackages) { 1845 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1846 } 1847 } 1848 1849 synchronized (mPackages) { 1850 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1851 } 1852 1853 final String packageName = res.pkg.applicationInfo.packageName; 1854 Bundle extras = new Bundle(1); 1855 extras.putInt(Intent.EXTRA_UID, res.uid); 1856 1857 // Determine the set of users who are adding this package for 1858 // the first time vs. those who are seeing an update. 1859 int[] firstUsers = EMPTY_INT_ARRAY; 1860 int[] updateUsers = EMPTY_INT_ARRAY; 1861 if (res.origUsers == null || res.origUsers.length == 0) { 1862 firstUsers = res.newUsers; 1863 } else { 1864 for (int newUser : res.newUsers) { 1865 boolean isNew = true; 1866 for (int origUser : res.origUsers) { 1867 if (origUser == newUser) { 1868 isNew = false; 1869 break; 1870 } 1871 } 1872 if (isNew) { 1873 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1874 } else { 1875 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1876 } 1877 } 1878 } 1879 1880 // Send installed broadcasts if the install/update is not ephemeral 1881 if (!isEphemeral(res.pkg)) { 1882 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1883 1884 // Send added for users that see the package for the first time 1885 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1886 extras, 0 /*flags*/, null /*targetPackage*/, 1887 null /*finishedReceiver*/, firstUsers); 1888 1889 // Send added for users that don't see the package for the first time 1890 if (update) { 1891 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1892 } 1893 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1894 extras, 0 /*flags*/, null /*targetPackage*/, 1895 null /*finishedReceiver*/, updateUsers); 1896 1897 // Send replaced for users that don't see the package for the first time 1898 if (update) { 1899 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1900 packageName, extras, 0 /*flags*/, 1901 null /*targetPackage*/, null /*finishedReceiver*/, 1902 updateUsers); 1903 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1904 null /*package*/, null /*extras*/, 0 /*flags*/, 1905 packageName /*targetPackage*/, 1906 null /*finishedReceiver*/, updateUsers); 1907 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1908 // First-install and we did a restore, so we're responsible for the 1909 // first-launch broadcast. 1910 if (DEBUG_BACKUP) { 1911 Slog.i(TAG, "Post-restore of " + packageName 1912 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1913 } 1914 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1915 } 1916 1917 // Send broadcast package appeared if forward locked/external for all users 1918 // treat asec-hosted packages like removable media on upgrade 1919 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1920 if (DEBUG_INSTALL) { 1921 Slog.i(TAG, "upgrading pkg " + res.pkg 1922 + " is ASEC-hosted -> AVAILABLE"); 1923 } 1924 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1925 ArrayList<String> pkgList = new ArrayList<>(1); 1926 pkgList.add(packageName); 1927 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1928 } 1929 } 1930 1931 // Work that needs to happen on first install within each user 1932 if (firstUsers != null && firstUsers.length > 0) { 1933 synchronized (mPackages) { 1934 for (int userId : firstUsers) { 1935 // If this app is a browser and it's newly-installed for some 1936 // users, clear any default-browser state in those users. The 1937 // app's nature doesn't depend on the user, so we can just check 1938 // its browser nature in any user and generalize. 1939 if (packageIsBrowser(packageName, userId)) { 1940 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1941 } 1942 1943 // We may also need to apply pending (restored) runtime 1944 // permission grants within these users. 1945 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1946 } 1947 } 1948 } 1949 1950 // Log current value of "unknown sources" setting 1951 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1952 getUnknownSourcesSettings()); 1953 1954 // Force a gc to clear up things 1955 Runtime.getRuntime().gc(); 1956 1957 // Remove the replaced package's older resources safely now 1958 // We delete after a gc for applications on sdcard. 1959 if (res.removedInfo != null && res.removedInfo.args != null) { 1960 synchronized (mInstallLock) { 1961 res.removedInfo.args.doPostDeleteLI(true); 1962 } 1963 } 1964 } 1965 1966 // If someone is watching installs - notify them 1967 if (installObserver != null) { 1968 try { 1969 Bundle extras = extrasForInstallResult(res); 1970 installObserver.onPackageInstalled(res.name, res.returnCode, 1971 res.returnMsg, extras); 1972 } catch (RemoteException e) { 1973 Slog.i(TAG, "Observer no longer exists."); 1974 } 1975 } 1976 } 1977 1978 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1979 PackageParser.Package pkg) { 1980 if (pkg.parentPackage == null) { 1981 return; 1982 } 1983 if (pkg.requestedPermissions == null) { 1984 return; 1985 } 1986 final PackageSetting disabledSysParentPs = mSettings 1987 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1988 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1989 || !disabledSysParentPs.isPrivileged() 1990 || (disabledSysParentPs.childPackageNames != null 1991 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1992 return; 1993 } 1994 final int[] allUserIds = sUserManager.getUserIds(); 1995 final int permCount = pkg.requestedPermissions.size(); 1996 for (int i = 0; i < permCount; i++) { 1997 String permission = pkg.requestedPermissions.get(i); 1998 BasePermission bp = mSettings.mPermissions.get(permission); 1999 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2000 continue; 2001 } 2002 for (int userId : allUserIds) { 2003 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2004 permission, userId)) { 2005 grantRuntimePermission(pkg.packageName, permission, userId); 2006 } 2007 } 2008 } 2009 } 2010 2011 private StorageEventListener mStorageListener = new StorageEventListener() { 2012 @Override 2013 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2014 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2015 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2016 final String volumeUuid = vol.getFsUuid(); 2017 2018 // Clean up any users or apps that were removed or recreated 2019 // while this volume was missing 2020 reconcileUsers(volumeUuid); 2021 reconcileApps(volumeUuid); 2022 2023 // Clean up any install sessions that expired or were 2024 // cancelled while this volume was missing 2025 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2026 2027 loadPrivatePackages(vol); 2028 2029 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2030 unloadPrivatePackages(vol); 2031 } 2032 } 2033 2034 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2035 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2036 updateExternalMediaStatus(true, false); 2037 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2038 updateExternalMediaStatus(false, false); 2039 } 2040 } 2041 } 2042 2043 @Override 2044 public void onVolumeForgotten(String fsUuid) { 2045 if (TextUtils.isEmpty(fsUuid)) { 2046 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2047 return; 2048 } 2049 2050 // Remove any apps installed on the forgotten volume 2051 synchronized (mPackages) { 2052 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2053 for (PackageSetting ps : packages) { 2054 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2055 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2056 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2057 } 2058 2059 mSettings.onVolumeForgotten(fsUuid); 2060 mSettings.writeLPr(); 2061 } 2062 } 2063 }; 2064 2065 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2066 String[] grantedPermissions) { 2067 for (int userId : userIds) { 2068 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2069 } 2070 2071 // We could have touched GID membership, so flush out packages.list 2072 synchronized (mPackages) { 2073 mSettings.writePackageListLPr(); 2074 } 2075 } 2076 2077 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2078 String[] grantedPermissions) { 2079 SettingBase sb = (SettingBase) pkg.mExtras; 2080 if (sb == null) { 2081 return; 2082 } 2083 2084 PermissionsState permissionsState = sb.getPermissionsState(); 2085 2086 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2087 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2088 2089 for (String permission : pkg.requestedPermissions) { 2090 final BasePermission bp; 2091 synchronized (mPackages) { 2092 bp = mSettings.mPermissions.get(permission); 2093 } 2094 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2095 && (grantedPermissions == null 2096 || ArrayUtils.contains(grantedPermissions, permission))) { 2097 final int flags = permissionsState.getPermissionFlags(permission, userId); 2098 // Installer cannot change immutable permissions. 2099 if ((flags & immutableFlags) == 0) { 2100 grantRuntimePermission(pkg.packageName, permission, userId); 2101 } 2102 } 2103 } 2104 } 2105 2106 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2107 Bundle extras = null; 2108 switch (res.returnCode) { 2109 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2110 extras = new Bundle(); 2111 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2112 res.origPermission); 2113 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2114 res.origPackage); 2115 break; 2116 } 2117 case PackageManager.INSTALL_SUCCEEDED: { 2118 extras = new Bundle(); 2119 extras.putBoolean(Intent.EXTRA_REPLACING, 2120 res.removedInfo != null && res.removedInfo.removedPackage != null); 2121 break; 2122 } 2123 } 2124 return extras; 2125 } 2126 2127 void scheduleWriteSettingsLocked() { 2128 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2129 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2130 } 2131 } 2132 2133 void scheduleWritePackageListLocked(int userId) { 2134 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2135 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2136 msg.arg1 = userId; 2137 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2138 } 2139 } 2140 2141 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2142 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2143 scheduleWritePackageRestrictionsLocked(userId); 2144 } 2145 2146 void scheduleWritePackageRestrictionsLocked(int userId) { 2147 final int[] userIds = (userId == UserHandle.USER_ALL) 2148 ? sUserManager.getUserIds() : new int[]{userId}; 2149 for (int nextUserId : userIds) { 2150 if (!sUserManager.exists(nextUserId)) return; 2151 mDirtyUsers.add(nextUserId); 2152 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2153 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2154 } 2155 } 2156 } 2157 2158 public static PackageManagerService main(Context context, Installer installer, 2159 boolean factoryTest, boolean onlyCore) { 2160 // Self-check for initial settings. 2161 PackageManagerServiceCompilerMapping.checkProperties(); 2162 2163 PackageManagerService m = new PackageManagerService(context, installer, 2164 factoryTest, onlyCore); 2165 m.enableSystemUserPackages(); 2166 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2167 // disabled after already being started. 2168 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2169 UserHandle.USER_SYSTEM); 2170 ServiceManager.addService("package", m); 2171 return m; 2172 } 2173 2174 private void enableSystemUserPackages() { 2175 if (!UserManager.isSplitSystemUser()) { 2176 return; 2177 } 2178 // For system user, enable apps based on the following conditions: 2179 // - app is whitelisted or belong to one of these groups: 2180 // -- system app which has no launcher icons 2181 // -- system app which has INTERACT_ACROSS_USERS permission 2182 // -- system IME app 2183 // - app is not in the blacklist 2184 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2185 Set<String> enableApps = new ArraySet<>(); 2186 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2187 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2188 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2189 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2190 enableApps.addAll(wlApps); 2191 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2192 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2193 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2194 enableApps.removeAll(blApps); 2195 Log.i(TAG, "Applications installed for system user: " + enableApps); 2196 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2197 UserHandle.SYSTEM); 2198 final int allAppsSize = allAps.size(); 2199 synchronized (mPackages) { 2200 for (int i = 0; i < allAppsSize; i++) { 2201 String pName = allAps.get(i); 2202 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2203 // Should not happen, but we shouldn't be failing if it does 2204 if (pkgSetting == null) { 2205 continue; 2206 } 2207 boolean install = enableApps.contains(pName); 2208 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2209 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2210 + " for system user"); 2211 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2212 } 2213 } 2214 } 2215 } 2216 2217 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2218 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2219 Context.DISPLAY_SERVICE); 2220 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2221 } 2222 2223 public PackageManagerService(Context context, Installer installer, 2224 boolean factoryTest, boolean onlyCore) { 2225 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2226 SystemClock.uptimeMillis()); 2227 2228 if (mSdkVersion <= 0) { 2229 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2230 } 2231 2232 mContext = context; 2233 mFactoryTest = factoryTest; 2234 mOnlyCore = onlyCore; 2235 mMetrics = new DisplayMetrics(); 2236 mSettings = new Settings(mPackages); 2237 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2242 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2243 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2244 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2245 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2246 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2247 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2248 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2249 2250 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2251 if (separateProcesses != null && separateProcesses.length() > 0) { 2252 if ("*".equals(separateProcesses)) { 2253 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2254 mSeparateProcesses = null; 2255 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2256 } else { 2257 mDefParseFlags = 0; 2258 mSeparateProcesses = separateProcesses.split(","); 2259 Slog.w(TAG, "Running with debug.separate_processes: " 2260 + separateProcesses); 2261 } 2262 } else { 2263 mDefParseFlags = 0; 2264 mSeparateProcesses = null; 2265 } 2266 2267 mInstaller = installer; 2268 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2269 "*dexopt*"); 2270 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2271 2272 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2273 FgThread.get().getLooper()); 2274 2275 getDefaultDisplayMetrics(context, mMetrics); 2276 2277 SystemConfig systemConfig = SystemConfig.getInstance(); 2278 mGlobalGids = systemConfig.getGlobalGids(); 2279 mSystemPermissions = systemConfig.getSystemPermissions(); 2280 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2281 2282 synchronized (mInstallLock) { 2283 // writer 2284 synchronized (mPackages) { 2285 mHandlerThread = new ServiceThread(TAG, 2286 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2287 mHandlerThread.start(); 2288 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2289 mProcessLoggingHandler = new ProcessLoggingHandler(); 2290 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2291 2292 File dataDir = Environment.getDataDirectory(); 2293 mAppInstallDir = new File(dataDir, "app"); 2294 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2295 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2296 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2297 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2298 2299 sUserManager = new UserManagerService(context, this, mPackages); 2300 2301 // Propagate permission configuration in to package manager. 2302 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2303 = systemConfig.getPermissions(); 2304 for (int i=0; i<permConfig.size(); i++) { 2305 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2306 BasePermission bp = mSettings.mPermissions.get(perm.name); 2307 if (bp == null) { 2308 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2309 mSettings.mPermissions.put(perm.name, bp); 2310 } 2311 if (perm.gids != null) { 2312 bp.setGids(perm.gids, perm.perUser); 2313 } 2314 } 2315 2316 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2317 for (int i=0; i<libConfig.size(); i++) { 2318 mSharedLibraries.put(libConfig.keyAt(i), 2319 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2320 } 2321 2322 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2323 2324 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2325 2326 String customResolverActivity = Resources.getSystem().getString( 2327 R.string.config_customResolverActivity); 2328 if (TextUtils.isEmpty(customResolverActivity)) { 2329 customResolverActivity = null; 2330 } else { 2331 mCustomResolverComponentName = ComponentName.unflattenFromString( 2332 customResolverActivity); 2333 } 2334 2335 long startTime = SystemClock.uptimeMillis(); 2336 2337 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2338 startTime); 2339 2340 // Set flag to monitor and not change apk file paths when 2341 // scanning install directories. 2342 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2343 2344 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2345 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2346 2347 if (bootClassPath == null) { 2348 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2349 } 2350 2351 if (systemServerClassPath == null) { 2352 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2353 } 2354 2355 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2356 final String[] dexCodeInstructionSets = 2357 getDexCodeInstructionSets( 2358 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2359 2360 /** 2361 * Ensure all external libraries have had dexopt run on them. 2362 */ 2363 if (mSharedLibraries.size() > 0) { 2364 // NOTE: For now, we're compiling these system "shared libraries" 2365 // (and framework jars) into all available architectures. It's possible 2366 // to compile them only when we come across an app that uses them (there's 2367 // already logic for that in scanPackageLI) but that adds some complexity. 2368 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2369 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2370 final String lib = libEntry.path; 2371 if (lib == null) { 2372 continue; 2373 } 2374 2375 try { 2376 // Shared libraries do not have profiles so we perform a full 2377 // AOT compilation (if needed). 2378 int dexoptNeeded = DexFile.getDexOptNeeded( 2379 lib, dexCodeInstructionSet, 2380 getCompilerFilterForReason(REASON_SHARED_APK), 2381 false /* newProfile */); 2382 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2383 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2384 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2385 getCompilerFilterForReason(REASON_SHARED_APK), 2386 StorageManager.UUID_PRIVATE_INTERNAL, 2387 SKIP_SHARED_LIBRARY_CHECK); 2388 } 2389 } catch (FileNotFoundException e) { 2390 Slog.w(TAG, "Library not found: " + lib); 2391 } catch (IOException | InstallerException e) { 2392 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2393 + e.getMessage()); 2394 } 2395 } 2396 } 2397 } 2398 2399 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2400 2401 final VersionInfo ver = mSettings.getInternalVersion(); 2402 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2403 2404 // when upgrading from pre-M, promote system app permissions from install to runtime 2405 mPromoteSystemApps = 2406 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2407 2408 // When upgrading from pre-N, we need to handle package extraction like first boot, 2409 // as there is no profiling data available. 2410 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2411 2412 // save off the names of pre-existing system packages prior to scanning; we don't 2413 // want to automatically grant runtime permissions for new system apps 2414 if (mPromoteSystemApps) { 2415 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2416 while (pkgSettingIter.hasNext()) { 2417 PackageSetting ps = pkgSettingIter.next(); 2418 if (isSystemApp(ps)) { 2419 mExistingSystemPackages.add(ps.name); 2420 } 2421 } 2422 } 2423 2424 // Collect vendor overlay packages. 2425 // (Do this before scanning any apps.) 2426 // For security and version matching reason, only consider 2427 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2428 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2429 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2430 | PackageParser.PARSE_IS_SYSTEM 2431 | PackageParser.PARSE_IS_SYSTEM_DIR 2432 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2433 2434 // Find base frameworks (resource packages without code). 2435 scanDirTracedLI(frameworkDir, mDefParseFlags 2436 | PackageParser.PARSE_IS_SYSTEM 2437 | PackageParser.PARSE_IS_SYSTEM_DIR 2438 | PackageParser.PARSE_IS_PRIVILEGED, 2439 scanFlags | SCAN_NO_DEX, 0); 2440 2441 // Collected privileged system packages. 2442 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2443 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR 2446 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2447 2448 // Collect ordinary system packages. 2449 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2450 scanDirTracedLI(systemAppDir, mDefParseFlags 2451 | PackageParser.PARSE_IS_SYSTEM 2452 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2453 2454 // Collect all vendor packages. 2455 File vendorAppDir = new File("/vendor/app"); 2456 try { 2457 vendorAppDir = vendorAppDir.getCanonicalFile(); 2458 } catch (IOException e) { 2459 // failed to look up canonical path, continue with original one 2460 } 2461 scanDirTracedLI(vendorAppDir, mDefParseFlags 2462 | PackageParser.PARSE_IS_SYSTEM 2463 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2464 2465 // Collect all OEM packages. 2466 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2467 scanDirTracedLI(oemAppDir, mDefParseFlags 2468 | PackageParser.PARSE_IS_SYSTEM 2469 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2470 2471 // Prune any system packages that no longer exist. 2472 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2473 if (!mOnlyCore) { 2474 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2475 while (psit.hasNext()) { 2476 PackageSetting ps = psit.next(); 2477 2478 /* 2479 * If this is not a system app, it can't be a 2480 * disable system app. 2481 */ 2482 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2483 continue; 2484 } 2485 2486 /* 2487 * If the package is scanned, it's not erased. 2488 */ 2489 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2490 if (scannedPkg != null) { 2491 /* 2492 * If the system app is both scanned and in the 2493 * disabled packages list, then it must have been 2494 * added via OTA. Remove it from the currently 2495 * scanned package so the previously user-installed 2496 * application can be scanned. 2497 */ 2498 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2499 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2500 + ps.name + "; removing system app. Last known codePath=" 2501 + ps.codePathString + ", installStatus=" + ps.installStatus 2502 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2503 + scannedPkg.mVersionCode); 2504 removePackageLI(scannedPkg, true); 2505 mExpectingBetter.put(ps.name, ps.codePath); 2506 } 2507 2508 continue; 2509 } 2510 2511 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2512 psit.remove(); 2513 logCriticalInfo(Log.WARN, "System package " + ps.name 2514 + " no longer exists; it's data will be wiped"); 2515 // Actual deletion of code and data will be handled by later 2516 // reconciliation step 2517 } else { 2518 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2519 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2520 possiblyDeletedUpdatedSystemApps.add(ps.name); 2521 } 2522 } 2523 } 2524 } 2525 2526 //look for any incomplete package installations 2527 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2528 for (int i = 0; i < deletePkgsList.size(); i++) { 2529 // Actual deletion of code and data will be handled by later 2530 // reconciliation step 2531 final String packageName = deletePkgsList.get(i).name; 2532 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2533 synchronized (mPackages) { 2534 mSettings.removePackageLPw(packageName); 2535 } 2536 } 2537 2538 //delete tmp files 2539 deleteTempPackageFiles(); 2540 2541 // Remove any shared userIDs that have no associated packages 2542 mSettings.pruneSharedUsersLPw(); 2543 2544 if (!mOnlyCore) { 2545 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2546 SystemClock.uptimeMillis()); 2547 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2548 2549 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2550 | PackageParser.PARSE_FORWARD_LOCK, 2551 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2552 2553 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2554 | PackageParser.PARSE_IS_EPHEMERAL, 2555 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2556 2557 /** 2558 * Remove disable package settings for any updated system 2559 * apps that were removed via an OTA. If they're not a 2560 * previously-updated app, remove them completely. 2561 * Otherwise, just revoke their system-level permissions. 2562 */ 2563 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2564 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2565 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2566 2567 String msg; 2568 if (deletedPkg == null) { 2569 msg = "Updated system package " + deletedAppName 2570 + " no longer exists; it's data will be wiped"; 2571 // Actual deletion of code and data will be handled by later 2572 // reconciliation step 2573 } else { 2574 msg = "Updated system app + " + deletedAppName 2575 + " no longer present; removing system privileges for " 2576 + deletedAppName; 2577 2578 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2579 2580 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2581 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2582 } 2583 logCriticalInfo(Log.WARN, msg); 2584 } 2585 2586 /** 2587 * Make sure all system apps that we expected to appear on 2588 * the userdata partition actually showed up. If they never 2589 * appeared, crawl back and revive the system version. 2590 */ 2591 for (int i = 0; i < mExpectingBetter.size(); i++) { 2592 final String packageName = mExpectingBetter.keyAt(i); 2593 if (!mPackages.containsKey(packageName)) { 2594 final File scanFile = mExpectingBetter.valueAt(i); 2595 2596 logCriticalInfo(Log.WARN, "Expected better " + packageName 2597 + " but never showed up; reverting to system"); 2598 2599 int reparseFlags = mDefParseFlags; 2600 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2601 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2602 | PackageParser.PARSE_IS_SYSTEM_DIR 2603 | PackageParser.PARSE_IS_PRIVILEGED; 2604 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2605 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2606 | PackageParser.PARSE_IS_SYSTEM_DIR; 2607 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2608 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2609 | PackageParser.PARSE_IS_SYSTEM_DIR; 2610 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2611 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2612 | PackageParser.PARSE_IS_SYSTEM_DIR; 2613 } else { 2614 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2615 continue; 2616 } 2617 2618 mSettings.enableSystemPackageLPw(packageName); 2619 2620 try { 2621 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2622 } catch (PackageManagerException e) { 2623 Slog.e(TAG, "Failed to parse original system package: " 2624 + e.getMessage()); 2625 } 2626 } 2627 } 2628 } 2629 mExpectingBetter.clear(); 2630 2631 // Resolve protected action filters. Only the setup wizard is allowed to 2632 // have a high priority filter for these actions. 2633 mSetupWizardPackage = getSetupWizardPackageName(); 2634 if (mProtectedFilters.size() > 0) { 2635 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2636 Slog.i(TAG, "No setup wizard;" 2637 + " All protected intents capped to priority 0"); 2638 } 2639 for (ActivityIntentInfo filter : mProtectedFilters) { 2640 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2641 if (DEBUG_FILTERS) { 2642 Slog.i(TAG, "Found setup wizard;" 2643 + " allow priority " + filter.getPriority() + ";" 2644 + " package: " + filter.activity.info.packageName 2645 + " activity: " + filter.activity.className 2646 + " priority: " + filter.getPriority()); 2647 } 2648 // skip setup wizard; allow it to keep the high priority filter 2649 continue; 2650 } 2651 Slog.w(TAG, "Protected action; cap priority to 0;" 2652 + " package: " + filter.activity.info.packageName 2653 + " activity: " + filter.activity.className 2654 + " origPrio: " + filter.getPriority()); 2655 filter.setPriority(0); 2656 } 2657 } 2658 mDeferProtectedFilters = false; 2659 mProtectedFilters.clear(); 2660 2661 // Now that we know all of the shared libraries, update all clients to have 2662 // the correct library paths. 2663 updateAllSharedLibrariesLPw(); 2664 2665 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2666 // NOTE: We ignore potential failures here during a system scan (like 2667 // the rest of the commands above) because there's precious little we 2668 // can do about it. A settings error is reported, though. 2669 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2670 false /* boot complete */); 2671 } 2672 2673 // Now that we know all the packages we are keeping, 2674 // read and update their last usage times. 2675 mPackageUsage.readLP(); 2676 2677 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2678 SystemClock.uptimeMillis()); 2679 Slog.i(TAG, "Time to scan packages: " 2680 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2681 + " seconds"); 2682 2683 // If the platform SDK has changed since the last time we booted, 2684 // we need to re-grant app permission to catch any new ones that 2685 // appear. This is really a hack, and means that apps can in some 2686 // cases get permissions that the user didn't initially explicitly 2687 // allow... it would be nice to have some better way to handle 2688 // this situation. 2689 int updateFlags = UPDATE_PERMISSIONS_ALL; 2690 if (ver.sdkVersion != mSdkVersion) { 2691 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2692 + mSdkVersion + "; regranting permissions for internal storage"); 2693 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2694 } 2695 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2696 ver.sdkVersion = mSdkVersion; 2697 2698 // If this is the first boot or an update from pre-M, and it is a normal 2699 // boot, then we need to initialize the default preferred apps across 2700 // all defined users. 2701 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2702 for (UserInfo user : sUserManager.getUsers(true)) { 2703 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2704 applyFactoryDefaultBrowserLPw(user.id); 2705 primeDomainVerificationsLPw(user.id); 2706 } 2707 } 2708 2709 // Prepare storage for system user really early during boot, 2710 // since core system apps like SettingsProvider and SystemUI 2711 // can't wait for user to start 2712 final int storageFlags; 2713 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2714 storageFlags = StorageManager.FLAG_STORAGE_DE; 2715 } else { 2716 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2717 } 2718 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2719 storageFlags); 2720 2721 // If this is first boot after an OTA, and a normal boot, then 2722 // we need to clear code cache directories. 2723 // Note that we do *not* clear the application profiles. These remain valid 2724 // across OTAs and are used to drive profile verification (post OTA) and 2725 // profile compilation (without waiting to collect a fresh set of profiles). 2726 if (mIsUpgrade && !onlyCore) { 2727 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2728 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2729 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2730 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2731 // No apps are running this early, so no need to freeze 2732 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2733 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2734 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2735 } 2736 } 2737 ver.fingerprint = Build.FINGERPRINT; 2738 } 2739 2740 checkDefaultBrowser(); 2741 2742 // clear only after permissions and other defaults have been updated 2743 mExistingSystemPackages.clear(); 2744 mPromoteSystemApps = false; 2745 2746 // All the changes are done during package scanning. 2747 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2748 2749 // can downgrade to reader 2750 mSettings.writeLPr(); 2751 2752 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2753 // early on (before the package manager declares itself as early) because other 2754 // components in the system server might ask for package contexts for these apps. 2755 // 2756 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2757 // (i.e, that the data partition is unavailable). 2758 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2759 long start = System.nanoTime(); 2760 List<PackageParser.Package> coreApps = new ArrayList<>(); 2761 for (PackageParser.Package pkg : mPackages.values()) { 2762 if (pkg.coreApp) { 2763 coreApps.add(pkg); 2764 } 2765 } 2766 2767 int[] stats = performDexOpt(coreApps, false, 2768 getCompilerFilterForReason(REASON_CORE_APP)); 2769 2770 final int elapsedTimeSeconds = 2771 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2772 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2773 2774 if (DEBUG_DEXOPT) { 2775 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2776 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2777 } 2778 2779 2780 // TODO: Should we log these stats to tron too ? 2781 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2782 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2783 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2784 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2785 } 2786 2787 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2788 SystemClock.uptimeMillis()); 2789 2790 if (!mOnlyCore) { 2791 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2792 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2793 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2794 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2795 mIntentFilterVerifierComponent); 2796 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2797 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2798 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2799 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2800 } else { 2801 mRequiredVerifierPackage = null; 2802 mRequiredInstallerPackage = null; 2803 mIntentFilterVerifierComponent = null; 2804 mIntentFilterVerifier = null; 2805 mServicesSystemSharedLibraryPackageName = null; 2806 mSharedSystemSharedLibraryPackageName = null; 2807 } 2808 2809 mInstallerService = new PackageInstallerService(context, this); 2810 2811 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2812 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2813 // both the installer and resolver must be present to enable ephemeral 2814 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2815 if (DEBUG_EPHEMERAL) { 2816 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2817 + " installer:" + ephemeralInstallerComponent); 2818 } 2819 mEphemeralResolverComponent = ephemeralResolverComponent; 2820 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2821 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2822 mEphemeralResolverConnection = 2823 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2824 } else { 2825 if (DEBUG_EPHEMERAL) { 2826 final String missingComponent = 2827 (ephemeralResolverComponent == null) 2828 ? (ephemeralInstallerComponent == null) 2829 ? "resolver and installer" 2830 : "resolver" 2831 : "installer"; 2832 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2833 } 2834 mEphemeralResolverComponent = null; 2835 mEphemeralInstallerComponent = null; 2836 mEphemeralResolverConnection = null; 2837 } 2838 2839 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2840 } // synchronized (mPackages) 2841 } // synchronized (mInstallLock) 2842 2843 // Now after opening every single application zip, make sure they 2844 // are all flushed. Not really needed, but keeps things nice and 2845 // tidy. 2846 Runtime.getRuntime().gc(); 2847 2848 // The initial scanning above does many calls into installd while 2849 // holding the mPackages lock, but we're mostly interested in yelling 2850 // once we have a booted system. 2851 mInstaller.setWarnIfHeld(mPackages); 2852 2853 // Expose private service for system components to use. 2854 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2855 } 2856 2857 @Override 2858 public boolean isFirstBoot() { 2859 return !mRestoredSettings; 2860 } 2861 2862 @Override 2863 public boolean isOnlyCoreApps() { 2864 return mOnlyCore; 2865 } 2866 2867 @Override 2868 public boolean isUpgrade() { 2869 return mIsUpgrade; 2870 } 2871 2872 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2873 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2874 2875 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2876 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2877 UserHandle.USER_SYSTEM); 2878 if (matches.size() == 1) { 2879 return matches.get(0).getComponentInfo().packageName; 2880 } else { 2881 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2882 return null; 2883 } 2884 } 2885 2886 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2887 synchronized (mPackages) { 2888 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2889 if (libraryEntry == null) { 2890 throw new IllegalStateException("Missing required shared library:" + libraryName); 2891 } 2892 return libraryEntry.apk; 2893 } 2894 } 2895 2896 private @NonNull String getRequiredInstallerLPr() { 2897 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2898 intent.addCategory(Intent.CATEGORY_DEFAULT); 2899 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2900 2901 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2902 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2903 UserHandle.USER_SYSTEM); 2904 if (matches.size() == 1) { 2905 ResolveInfo resolveInfo = matches.get(0); 2906 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2907 throw new RuntimeException("The installer must be a privileged app"); 2908 } 2909 return matches.get(0).getComponentInfo().packageName; 2910 } else { 2911 throw new RuntimeException("There must be exactly one installer; found " + matches); 2912 } 2913 } 2914 2915 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2916 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2917 2918 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2919 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2920 UserHandle.USER_SYSTEM); 2921 ResolveInfo best = null; 2922 final int N = matches.size(); 2923 for (int i = 0; i < N; i++) { 2924 final ResolveInfo cur = matches.get(i); 2925 final String packageName = cur.getComponentInfo().packageName; 2926 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2927 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2928 continue; 2929 } 2930 2931 if (best == null || cur.priority > best.priority) { 2932 best = cur; 2933 } 2934 } 2935 2936 if (best != null) { 2937 return best.getComponentInfo().getComponentName(); 2938 } else { 2939 throw new RuntimeException("There must be at least one intent filter verifier"); 2940 } 2941 } 2942 2943 private @Nullable ComponentName getEphemeralResolverLPr() { 2944 final String[] packageArray = 2945 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2946 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2947 if (DEBUG_EPHEMERAL) { 2948 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2949 } 2950 return null; 2951 } 2952 2953 final int resolveFlags = 2954 MATCH_DIRECT_BOOT_AWARE 2955 | MATCH_DIRECT_BOOT_UNAWARE 2956 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2957 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2958 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2959 resolveFlags, UserHandle.USER_SYSTEM); 2960 2961 final int N = resolvers.size(); 2962 if (N == 0) { 2963 if (DEBUG_EPHEMERAL) { 2964 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2965 } 2966 return null; 2967 } 2968 2969 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2970 for (int i = 0; i < N; i++) { 2971 final ResolveInfo info = resolvers.get(i); 2972 2973 if (info.serviceInfo == null) { 2974 continue; 2975 } 2976 2977 final String packageName = info.serviceInfo.packageName; 2978 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2979 if (DEBUG_EPHEMERAL) { 2980 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2981 + " pkg: " + packageName + ", info:" + info); 2982 } 2983 continue; 2984 } 2985 2986 if (DEBUG_EPHEMERAL) { 2987 Slog.v(TAG, "Ephemeral resolver found;" 2988 + " pkg: " + packageName + ", info:" + info); 2989 } 2990 return new ComponentName(packageName, info.serviceInfo.name); 2991 } 2992 if (DEBUG_EPHEMERAL) { 2993 Slog.v(TAG, "Ephemeral resolver NOT found"); 2994 } 2995 return null; 2996 } 2997 2998 private @Nullable ComponentName getEphemeralInstallerLPr() { 2999 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3000 intent.addCategory(Intent.CATEGORY_DEFAULT); 3001 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3002 3003 final int resolveFlags = 3004 MATCH_DIRECT_BOOT_AWARE 3005 | MATCH_DIRECT_BOOT_UNAWARE 3006 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3007 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3008 resolveFlags, UserHandle.USER_SYSTEM); 3009 if (matches.size() == 0) { 3010 return null; 3011 } else if (matches.size() == 1) { 3012 return matches.get(0).getComponentInfo().getComponentName(); 3013 } else { 3014 throw new RuntimeException( 3015 "There must be at most one ephemeral installer; found " + matches); 3016 } 3017 } 3018 3019 private void primeDomainVerificationsLPw(int userId) { 3020 if (DEBUG_DOMAIN_VERIFICATION) { 3021 Slog.d(TAG, "Priming domain verifications in user " + userId); 3022 } 3023 3024 SystemConfig systemConfig = SystemConfig.getInstance(); 3025 ArraySet<String> packages = systemConfig.getLinkedApps(); 3026 ArraySet<String> domains = new ArraySet<String>(); 3027 3028 for (String packageName : packages) { 3029 PackageParser.Package pkg = mPackages.get(packageName); 3030 if (pkg != null) { 3031 if (!pkg.isSystemApp()) { 3032 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3033 continue; 3034 } 3035 3036 domains.clear(); 3037 for (PackageParser.Activity a : pkg.activities) { 3038 for (ActivityIntentInfo filter : a.intents) { 3039 if (hasValidDomains(filter)) { 3040 domains.addAll(filter.getHostsList()); 3041 } 3042 } 3043 } 3044 3045 if (domains.size() > 0) { 3046 if (DEBUG_DOMAIN_VERIFICATION) { 3047 Slog.v(TAG, " + " + packageName); 3048 } 3049 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3050 // state w.r.t. the formal app-linkage "no verification attempted" state; 3051 // and then 'always' in the per-user state actually used for intent resolution. 3052 final IntentFilterVerificationInfo ivi; 3053 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3054 new ArrayList<String>(domains)); 3055 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3056 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3057 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3058 } else { 3059 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3060 + "' does not handle web links"); 3061 } 3062 } else { 3063 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3064 } 3065 } 3066 3067 scheduleWritePackageRestrictionsLocked(userId); 3068 scheduleWriteSettingsLocked(); 3069 } 3070 3071 private void applyFactoryDefaultBrowserLPw(int userId) { 3072 // The default browser app's package name is stored in a string resource, 3073 // with a product-specific overlay used for vendor customization. 3074 String browserPkg = mContext.getResources().getString( 3075 com.android.internal.R.string.default_browser); 3076 if (!TextUtils.isEmpty(browserPkg)) { 3077 // non-empty string => required to be a known package 3078 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3079 if (ps == null) { 3080 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3081 browserPkg = null; 3082 } else { 3083 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3084 } 3085 } 3086 3087 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3088 // default. If there's more than one, just leave everything alone. 3089 if (browserPkg == null) { 3090 calculateDefaultBrowserLPw(userId); 3091 } 3092 } 3093 3094 private void calculateDefaultBrowserLPw(int userId) { 3095 List<String> allBrowsers = resolveAllBrowserApps(userId); 3096 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3097 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3098 } 3099 3100 private List<String> resolveAllBrowserApps(int userId) { 3101 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3102 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3103 PackageManager.MATCH_ALL, userId); 3104 3105 final int count = list.size(); 3106 List<String> result = new ArrayList<String>(count); 3107 for (int i=0; i<count; i++) { 3108 ResolveInfo info = list.get(i); 3109 if (info.activityInfo == null 3110 || !info.handleAllWebDataURI 3111 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3112 || result.contains(info.activityInfo.packageName)) { 3113 continue; 3114 } 3115 result.add(info.activityInfo.packageName); 3116 } 3117 3118 return result; 3119 } 3120 3121 private boolean packageIsBrowser(String packageName, int userId) { 3122 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3123 PackageManager.MATCH_ALL, userId); 3124 final int N = list.size(); 3125 for (int i = 0; i < N; i++) { 3126 ResolveInfo info = list.get(i); 3127 if (packageName.equals(info.activityInfo.packageName)) { 3128 return true; 3129 } 3130 } 3131 return false; 3132 } 3133 3134 private void checkDefaultBrowser() { 3135 final int myUserId = UserHandle.myUserId(); 3136 final String packageName = getDefaultBrowserPackageName(myUserId); 3137 if (packageName != null) { 3138 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3139 if (info == null) { 3140 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3141 synchronized (mPackages) { 3142 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3143 } 3144 } 3145 } 3146 } 3147 3148 @Override 3149 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3150 throws RemoteException { 3151 try { 3152 return super.onTransact(code, data, reply, flags); 3153 } catch (RuntimeException e) { 3154 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3155 Slog.wtf(TAG, "Package Manager Crash", e); 3156 } 3157 throw e; 3158 } 3159 } 3160 3161 static int[] appendInts(int[] cur, int[] add) { 3162 if (add == null) return cur; 3163 if (cur == null) return add; 3164 final int N = add.length; 3165 for (int i=0; i<N; i++) { 3166 cur = appendInt(cur, add[i]); 3167 } 3168 return cur; 3169 } 3170 3171 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3172 if (!sUserManager.exists(userId)) return null; 3173 if (ps == null) { 3174 return null; 3175 } 3176 final PackageParser.Package p = ps.pkg; 3177 if (p == null) { 3178 return null; 3179 } 3180 3181 final PermissionsState permissionsState = ps.getPermissionsState(); 3182 3183 final int[] gids = permissionsState.computeGids(userId); 3184 final Set<String> permissions = permissionsState.getPermissions(userId); 3185 final PackageUserState state = ps.readUserState(userId); 3186 3187 return PackageParser.generatePackageInfo(p, gids, flags, 3188 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3189 } 3190 3191 @Override 3192 public void checkPackageStartable(String packageName, int userId) { 3193 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3194 3195 synchronized (mPackages) { 3196 final PackageSetting ps = mSettings.mPackages.get(packageName); 3197 if (ps == null) { 3198 throw new SecurityException("Package " + packageName + " was not found!"); 3199 } 3200 3201 if (!ps.getInstalled(userId)) { 3202 throw new SecurityException( 3203 "Package " + packageName + " was not installed for user " + userId + "!"); 3204 } 3205 3206 if (mSafeMode && !ps.isSystem()) { 3207 throw new SecurityException("Package " + packageName + " not a system app!"); 3208 } 3209 3210 if (mFrozenPackages.contains(packageName)) { 3211 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3212 } 3213 3214 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3215 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3216 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3217 } 3218 } 3219 } 3220 3221 @Override 3222 public boolean isPackageAvailable(String packageName, int userId) { 3223 if (!sUserManager.exists(userId)) return false; 3224 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3225 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3226 synchronized (mPackages) { 3227 PackageParser.Package p = mPackages.get(packageName); 3228 if (p != null) { 3229 final PackageSetting ps = (PackageSetting) p.mExtras; 3230 if (ps != null) { 3231 final PackageUserState state = ps.readUserState(userId); 3232 if (state != null) { 3233 return PackageParser.isAvailable(state); 3234 } 3235 } 3236 } 3237 } 3238 return false; 3239 } 3240 3241 @Override 3242 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3243 if (!sUserManager.exists(userId)) return null; 3244 flags = updateFlagsForPackage(flags, userId, packageName); 3245 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3246 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3247 // reader 3248 synchronized (mPackages) { 3249 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3250 PackageParser.Package p = null; 3251 if (matchFactoryOnly) { 3252 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3253 if (ps != null) { 3254 return generatePackageInfo(ps, flags, userId); 3255 } 3256 } 3257 if (p == null) { 3258 p = mPackages.get(packageName); 3259 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3260 return null; 3261 } 3262 } 3263 if (DEBUG_PACKAGE_INFO) 3264 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3265 if (p != null) { 3266 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3267 } 3268 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3269 final PackageSetting ps = mSettings.mPackages.get(packageName); 3270 return generatePackageInfo(ps, flags, userId); 3271 } 3272 } 3273 return null; 3274 } 3275 3276 @Override 3277 public String[] currentToCanonicalPackageNames(String[] names) { 3278 String[] out = new String[names.length]; 3279 // reader 3280 synchronized (mPackages) { 3281 for (int i=names.length-1; i>=0; i--) { 3282 PackageSetting ps = mSettings.mPackages.get(names[i]); 3283 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3284 } 3285 } 3286 return out; 3287 } 3288 3289 @Override 3290 public String[] canonicalToCurrentPackageNames(String[] names) { 3291 String[] out = new String[names.length]; 3292 // reader 3293 synchronized (mPackages) { 3294 for (int i=names.length-1; i>=0; i--) { 3295 String cur = mSettings.mRenamedPackages.get(names[i]); 3296 out[i] = cur != null ? cur : names[i]; 3297 } 3298 } 3299 return out; 3300 } 3301 3302 @Override 3303 public int getPackageUid(String packageName, int flags, int userId) { 3304 if (!sUserManager.exists(userId)) return -1; 3305 flags = updateFlagsForPackage(flags, userId, packageName); 3306 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3307 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3308 3309 // reader 3310 synchronized (mPackages) { 3311 final PackageParser.Package p = mPackages.get(packageName); 3312 if (p != null && p.isMatch(flags)) { 3313 return UserHandle.getUid(userId, p.applicationInfo.uid); 3314 } 3315 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3316 final PackageSetting ps = mSettings.mPackages.get(packageName); 3317 if (ps != null && ps.isMatch(flags)) { 3318 return UserHandle.getUid(userId, ps.appId); 3319 } 3320 } 3321 } 3322 3323 return -1; 3324 } 3325 3326 @Override 3327 public int[] getPackageGids(String packageName, int flags, int userId) { 3328 if (!sUserManager.exists(userId)) return null; 3329 flags = updateFlagsForPackage(flags, userId, packageName); 3330 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3331 false /* requireFullPermission */, false /* checkShell */, 3332 "getPackageGids"); 3333 3334 // reader 3335 synchronized (mPackages) { 3336 final PackageParser.Package p = mPackages.get(packageName); 3337 if (p != null && p.isMatch(flags)) { 3338 PackageSetting ps = (PackageSetting) p.mExtras; 3339 return ps.getPermissionsState().computeGids(userId); 3340 } 3341 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3342 final PackageSetting ps = mSettings.mPackages.get(packageName); 3343 if (ps != null && ps.isMatch(flags)) { 3344 return ps.getPermissionsState().computeGids(userId); 3345 } 3346 } 3347 } 3348 3349 return null; 3350 } 3351 3352 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3353 if (bp.perm != null) { 3354 return PackageParser.generatePermissionInfo(bp.perm, flags); 3355 } 3356 PermissionInfo pi = new PermissionInfo(); 3357 pi.name = bp.name; 3358 pi.packageName = bp.sourcePackage; 3359 pi.nonLocalizedLabel = bp.name; 3360 pi.protectionLevel = bp.protectionLevel; 3361 return pi; 3362 } 3363 3364 @Override 3365 public PermissionInfo getPermissionInfo(String name, int flags) { 3366 // reader 3367 synchronized (mPackages) { 3368 final BasePermission p = mSettings.mPermissions.get(name); 3369 if (p != null) { 3370 return generatePermissionInfo(p, flags); 3371 } 3372 return null; 3373 } 3374 } 3375 3376 @Override 3377 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3378 int flags) { 3379 // reader 3380 synchronized (mPackages) { 3381 if (group != null && !mPermissionGroups.containsKey(group)) { 3382 // This is thrown as NameNotFoundException 3383 return null; 3384 } 3385 3386 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3387 for (BasePermission p : mSettings.mPermissions.values()) { 3388 if (group == null) { 3389 if (p.perm == null || p.perm.info.group == null) { 3390 out.add(generatePermissionInfo(p, flags)); 3391 } 3392 } else { 3393 if (p.perm != null && group.equals(p.perm.info.group)) { 3394 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3395 } 3396 } 3397 } 3398 return new ParceledListSlice<>(out); 3399 } 3400 } 3401 3402 @Override 3403 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3404 // reader 3405 synchronized (mPackages) { 3406 return PackageParser.generatePermissionGroupInfo( 3407 mPermissionGroups.get(name), flags); 3408 } 3409 } 3410 3411 @Override 3412 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3413 // reader 3414 synchronized (mPackages) { 3415 final int N = mPermissionGroups.size(); 3416 ArrayList<PermissionGroupInfo> out 3417 = new ArrayList<PermissionGroupInfo>(N); 3418 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3419 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3420 } 3421 return new ParceledListSlice<>(out); 3422 } 3423 } 3424 3425 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3426 int userId) { 3427 if (!sUserManager.exists(userId)) return null; 3428 PackageSetting ps = mSettings.mPackages.get(packageName); 3429 if (ps != null) { 3430 if (ps.pkg == null) { 3431 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3432 if (pInfo != null) { 3433 return pInfo.applicationInfo; 3434 } 3435 return null; 3436 } 3437 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3438 ps.readUserState(userId), userId); 3439 } 3440 return null; 3441 } 3442 3443 @Override 3444 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3445 if (!sUserManager.exists(userId)) return null; 3446 flags = updateFlagsForApplication(flags, userId, packageName); 3447 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3448 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3449 // writer 3450 synchronized (mPackages) { 3451 PackageParser.Package p = mPackages.get(packageName); 3452 if (DEBUG_PACKAGE_INFO) Log.v( 3453 TAG, "getApplicationInfo " + packageName 3454 + ": " + p); 3455 if (p != null) { 3456 PackageSetting ps = mSettings.mPackages.get(packageName); 3457 if (ps == null) return null; 3458 // Note: isEnabledLP() does not apply here - always return info 3459 return PackageParser.generateApplicationInfo( 3460 p, flags, ps.readUserState(userId), userId); 3461 } 3462 if ("android".equals(packageName)||"system".equals(packageName)) { 3463 return mAndroidApplication; 3464 } 3465 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3466 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3467 } 3468 } 3469 return null; 3470 } 3471 3472 @Override 3473 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3474 final IPackageDataObserver observer) { 3475 mContext.enforceCallingOrSelfPermission( 3476 android.Manifest.permission.CLEAR_APP_CACHE, null); 3477 // Queue up an async operation since clearing cache may take a little while. 3478 mHandler.post(new Runnable() { 3479 public void run() { 3480 mHandler.removeCallbacks(this); 3481 boolean success = true; 3482 synchronized (mInstallLock) { 3483 try { 3484 mInstaller.freeCache(volumeUuid, freeStorageSize); 3485 } catch (InstallerException e) { 3486 Slog.w(TAG, "Couldn't clear application caches: " + e); 3487 success = false; 3488 } 3489 } 3490 if (observer != null) { 3491 try { 3492 observer.onRemoveCompleted(null, success); 3493 } catch (RemoteException e) { 3494 Slog.w(TAG, "RemoveException when invoking call back"); 3495 } 3496 } 3497 } 3498 }); 3499 } 3500 3501 @Override 3502 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3503 final IntentSender pi) { 3504 mContext.enforceCallingOrSelfPermission( 3505 android.Manifest.permission.CLEAR_APP_CACHE, null); 3506 // Queue up an async operation since clearing cache may take a little while. 3507 mHandler.post(new Runnable() { 3508 public void run() { 3509 mHandler.removeCallbacks(this); 3510 boolean success = true; 3511 synchronized (mInstallLock) { 3512 try { 3513 mInstaller.freeCache(volumeUuid, freeStorageSize); 3514 } catch (InstallerException e) { 3515 Slog.w(TAG, "Couldn't clear application caches: " + e); 3516 success = false; 3517 } 3518 } 3519 if(pi != null) { 3520 try { 3521 // Callback via pending intent 3522 int code = success ? 1 : 0; 3523 pi.sendIntent(null, code, null, 3524 null, null); 3525 } catch (SendIntentException e1) { 3526 Slog.i(TAG, "Failed to send pending intent"); 3527 } 3528 } 3529 } 3530 }); 3531 } 3532 3533 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3534 synchronized (mInstallLock) { 3535 try { 3536 mInstaller.freeCache(volumeUuid, freeStorageSize); 3537 } catch (InstallerException e) { 3538 throw new IOException("Failed to free enough space", e); 3539 } 3540 } 3541 } 3542 3543 /** 3544 * Update given flags based on encryption status of current user. 3545 */ 3546 private int updateFlags(int flags, int userId) { 3547 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3548 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3549 // Caller expressed an explicit opinion about what encryption 3550 // aware/unaware components they want to see, so fall through and 3551 // give them what they want 3552 } else { 3553 // Caller expressed no opinion, so match based on user state 3554 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3555 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3556 } else { 3557 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3558 } 3559 } 3560 return flags; 3561 } 3562 3563 private UserManagerInternal getUserManagerInternal() { 3564 if (mUserManagerInternal == null) { 3565 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3566 } 3567 return mUserManagerInternal; 3568 } 3569 3570 /** 3571 * Update given flags when being used to request {@link PackageInfo}. 3572 */ 3573 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3574 boolean triaged = true; 3575 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3576 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3577 // Caller is asking for component details, so they'd better be 3578 // asking for specific encryption matching behavior, or be triaged 3579 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3580 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3581 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3582 triaged = false; 3583 } 3584 } 3585 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3586 | PackageManager.MATCH_SYSTEM_ONLY 3587 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3588 triaged = false; 3589 } 3590 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3591 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3592 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3593 } 3594 return updateFlags(flags, userId); 3595 } 3596 3597 /** 3598 * Update given flags when being used to request {@link ApplicationInfo}. 3599 */ 3600 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3601 return updateFlagsForPackage(flags, userId, cookie); 3602 } 3603 3604 /** 3605 * Update given flags when being used to request {@link ComponentInfo}. 3606 */ 3607 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3608 if (cookie instanceof Intent) { 3609 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3610 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3611 } 3612 } 3613 3614 boolean triaged = true; 3615 // Caller is asking for component details, so they'd better be 3616 // asking for specific encryption matching behavior, or be triaged 3617 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3618 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3619 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3620 triaged = false; 3621 } 3622 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3623 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3624 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3625 } 3626 3627 return updateFlags(flags, userId); 3628 } 3629 3630 /** 3631 * Update given flags when being used to request {@link ResolveInfo}. 3632 */ 3633 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3634 // Safe mode means we shouldn't match any third-party components 3635 if (mSafeMode) { 3636 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3637 } 3638 3639 return updateFlagsForComponent(flags, userId, cookie); 3640 } 3641 3642 @Override 3643 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3644 if (!sUserManager.exists(userId)) return null; 3645 flags = updateFlagsForComponent(flags, userId, component); 3646 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3647 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3648 synchronized (mPackages) { 3649 PackageParser.Activity a = mActivities.mActivities.get(component); 3650 3651 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3652 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3653 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3654 if (ps == null) return null; 3655 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3656 userId); 3657 } 3658 if (mResolveComponentName.equals(component)) { 3659 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3660 new PackageUserState(), userId); 3661 } 3662 } 3663 return null; 3664 } 3665 3666 @Override 3667 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3668 String resolvedType) { 3669 synchronized (mPackages) { 3670 if (component.equals(mResolveComponentName)) { 3671 // The resolver supports EVERYTHING! 3672 return true; 3673 } 3674 PackageParser.Activity a = mActivities.mActivities.get(component); 3675 if (a == null) { 3676 return false; 3677 } 3678 for (int i=0; i<a.intents.size(); i++) { 3679 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3680 intent.getData(), intent.getCategories(), TAG) >= 0) { 3681 return true; 3682 } 3683 } 3684 return false; 3685 } 3686 } 3687 3688 @Override 3689 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3690 if (!sUserManager.exists(userId)) return null; 3691 flags = updateFlagsForComponent(flags, userId, component); 3692 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3693 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3694 synchronized (mPackages) { 3695 PackageParser.Activity a = mReceivers.mActivities.get(component); 3696 if (DEBUG_PACKAGE_INFO) Log.v( 3697 TAG, "getReceiverInfo " + component + ": " + a); 3698 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3699 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3700 if (ps == null) return null; 3701 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3702 userId); 3703 } 3704 } 3705 return null; 3706 } 3707 3708 @Override 3709 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3710 if (!sUserManager.exists(userId)) return null; 3711 flags = updateFlagsForComponent(flags, userId, component); 3712 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3713 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3714 synchronized (mPackages) { 3715 PackageParser.Service s = mServices.mServices.get(component); 3716 if (DEBUG_PACKAGE_INFO) Log.v( 3717 TAG, "getServiceInfo " + component + ": " + s); 3718 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3719 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3720 if (ps == null) return null; 3721 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3722 userId); 3723 } 3724 } 3725 return null; 3726 } 3727 3728 @Override 3729 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3730 if (!sUserManager.exists(userId)) return null; 3731 flags = updateFlagsForComponent(flags, userId, component); 3732 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3733 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3734 synchronized (mPackages) { 3735 PackageParser.Provider p = mProviders.mProviders.get(component); 3736 if (DEBUG_PACKAGE_INFO) Log.v( 3737 TAG, "getProviderInfo " + component + ": " + p); 3738 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3739 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3740 if (ps == null) return null; 3741 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3742 userId); 3743 } 3744 } 3745 return null; 3746 } 3747 3748 @Override 3749 public String[] getSystemSharedLibraryNames() { 3750 Set<String> libSet; 3751 synchronized (mPackages) { 3752 libSet = mSharedLibraries.keySet(); 3753 int size = libSet.size(); 3754 if (size > 0) { 3755 String[] libs = new String[size]; 3756 libSet.toArray(libs); 3757 return libs; 3758 } 3759 } 3760 return null; 3761 } 3762 3763 @Override 3764 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3765 synchronized (mPackages) { 3766 return mServicesSystemSharedLibraryPackageName; 3767 } 3768 } 3769 3770 @Override 3771 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3772 synchronized (mPackages) { 3773 return mSharedSystemSharedLibraryPackageName; 3774 } 3775 } 3776 3777 @Override 3778 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3779 synchronized (mPackages) { 3780 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3781 3782 final FeatureInfo fi = new FeatureInfo(); 3783 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3784 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3785 res.add(fi); 3786 3787 return new ParceledListSlice<>(res); 3788 } 3789 } 3790 3791 @Override 3792 public boolean hasSystemFeature(String name, int version) { 3793 synchronized (mPackages) { 3794 final FeatureInfo feat = mAvailableFeatures.get(name); 3795 if (feat == null) { 3796 return false; 3797 } else { 3798 return feat.version >= version; 3799 } 3800 } 3801 } 3802 3803 @Override 3804 public int checkPermission(String permName, String pkgName, int userId) { 3805 if (!sUserManager.exists(userId)) { 3806 return PackageManager.PERMISSION_DENIED; 3807 } 3808 3809 synchronized (mPackages) { 3810 final PackageParser.Package p = mPackages.get(pkgName); 3811 if (p != null && p.mExtras != null) { 3812 final PackageSetting ps = (PackageSetting) p.mExtras; 3813 final PermissionsState permissionsState = ps.getPermissionsState(); 3814 if (permissionsState.hasPermission(permName, userId)) { 3815 return PackageManager.PERMISSION_GRANTED; 3816 } 3817 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3818 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3819 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3820 return PackageManager.PERMISSION_GRANTED; 3821 } 3822 } 3823 } 3824 3825 return PackageManager.PERMISSION_DENIED; 3826 } 3827 3828 @Override 3829 public int checkUidPermission(String permName, int uid) { 3830 final int userId = UserHandle.getUserId(uid); 3831 3832 if (!sUserManager.exists(userId)) { 3833 return PackageManager.PERMISSION_DENIED; 3834 } 3835 3836 synchronized (mPackages) { 3837 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3838 if (obj != null) { 3839 final SettingBase ps = (SettingBase) obj; 3840 final PermissionsState permissionsState = ps.getPermissionsState(); 3841 if (permissionsState.hasPermission(permName, userId)) { 3842 return PackageManager.PERMISSION_GRANTED; 3843 } 3844 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3845 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3846 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3847 return PackageManager.PERMISSION_GRANTED; 3848 } 3849 } else { 3850 ArraySet<String> perms = mSystemPermissions.get(uid); 3851 if (perms != null) { 3852 if (perms.contains(permName)) { 3853 return PackageManager.PERMISSION_GRANTED; 3854 } 3855 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3856 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3857 return PackageManager.PERMISSION_GRANTED; 3858 } 3859 } 3860 } 3861 } 3862 3863 return PackageManager.PERMISSION_DENIED; 3864 } 3865 3866 @Override 3867 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3868 if (UserHandle.getCallingUserId() != userId) { 3869 mContext.enforceCallingPermission( 3870 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3871 "isPermissionRevokedByPolicy for user " + userId); 3872 } 3873 3874 if (checkPermission(permission, packageName, userId) 3875 == PackageManager.PERMISSION_GRANTED) { 3876 return false; 3877 } 3878 3879 final long identity = Binder.clearCallingIdentity(); 3880 try { 3881 final int flags = getPermissionFlags(permission, packageName, userId); 3882 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3883 } finally { 3884 Binder.restoreCallingIdentity(identity); 3885 } 3886 } 3887 3888 @Override 3889 public String getPermissionControllerPackageName() { 3890 synchronized (mPackages) { 3891 return mRequiredInstallerPackage; 3892 } 3893 } 3894 3895 /** 3896 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3897 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3898 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3899 * @param message the message to log on security exception 3900 */ 3901 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3902 boolean checkShell, String message) { 3903 if (userId < 0) { 3904 throw new IllegalArgumentException("Invalid userId " + userId); 3905 } 3906 if (checkShell) { 3907 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3908 } 3909 if (userId == UserHandle.getUserId(callingUid)) return; 3910 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3911 if (requireFullPermission) { 3912 mContext.enforceCallingOrSelfPermission( 3913 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3914 } else { 3915 try { 3916 mContext.enforceCallingOrSelfPermission( 3917 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3918 } catch (SecurityException se) { 3919 mContext.enforceCallingOrSelfPermission( 3920 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3921 } 3922 } 3923 } 3924 } 3925 3926 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3927 if (callingUid == Process.SHELL_UID) { 3928 if (userHandle >= 0 3929 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3930 throw new SecurityException("Shell does not have permission to access user " 3931 + userHandle); 3932 } else if (userHandle < 0) { 3933 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3934 + Debug.getCallers(3)); 3935 } 3936 } 3937 } 3938 3939 private BasePermission findPermissionTreeLP(String permName) { 3940 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3941 if (permName.startsWith(bp.name) && 3942 permName.length() > bp.name.length() && 3943 permName.charAt(bp.name.length()) == '.') { 3944 return bp; 3945 } 3946 } 3947 return null; 3948 } 3949 3950 private BasePermission checkPermissionTreeLP(String permName) { 3951 if (permName != null) { 3952 BasePermission bp = findPermissionTreeLP(permName); 3953 if (bp != null) { 3954 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3955 return bp; 3956 } 3957 throw new SecurityException("Calling uid " 3958 + Binder.getCallingUid() 3959 + " is not allowed to add to permission tree " 3960 + bp.name + " owned by uid " + bp.uid); 3961 } 3962 } 3963 throw new SecurityException("No permission tree found for " + permName); 3964 } 3965 3966 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3967 if (s1 == null) { 3968 return s2 == null; 3969 } 3970 if (s2 == null) { 3971 return false; 3972 } 3973 if (s1.getClass() != s2.getClass()) { 3974 return false; 3975 } 3976 return s1.equals(s2); 3977 } 3978 3979 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3980 if (pi1.icon != pi2.icon) return false; 3981 if (pi1.logo != pi2.logo) return false; 3982 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3983 if (!compareStrings(pi1.name, pi2.name)) return false; 3984 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3985 // We'll take care of setting this one. 3986 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3987 // These are not currently stored in settings. 3988 //if (!compareStrings(pi1.group, pi2.group)) return false; 3989 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3990 //if (pi1.labelRes != pi2.labelRes) return false; 3991 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3992 return true; 3993 } 3994 3995 int permissionInfoFootprint(PermissionInfo info) { 3996 int size = info.name.length(); 3997 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3998 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3999 return size; 4000 } 4001 4002 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4003 int size = 0; 4004 for (BasePermission perm : mSettings.mPermissions.values()) { 4005 if (perm.uid == tree.uid) { 4006 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4007 } 4008 } 4009 return size; 4010 } 4011 4012 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4013 // We calculate the max size of permissions defined by this uid and throw 4014 // if that plus the size of 'info' would exceed our stated maximum. 4015 if (tree.uid != Process.SYSTEM_UID) { 4016 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4017 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4018 throw new SecurityException("Permission tree size cap exceeded"); 4019 } 4020 } 4021 } 4022 4023 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4024 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4025 throw new SecurityException("Label must be specified in permission"); 4026 } 4027 BasePermission tree = checkPermissionTreeLP(info.name); 4028 BasePermission bp = mSettings.mPermissions.get(info.name); 4029 boolean added = bp == null; 4030 boolean changed = true; 4031 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4032 if (added) { 4033 enforcePermissionCapLocked(info, tree); 4034 bp = new BasePermission(info.name, tree.sourcePackage, 4035 BasePermission.TYPE_DYNAMIC); 4036 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4037 throw new SecurityException( 4038 "Not allowed to modify non-dynamic permission " 4039 + info.name); 4040 } else { 4041 if (bp.protectionLevel == fixedLevel 4042 && bp.perm.owner.equals(tree.perm.owner) 4043 && bp.uid == tree.uid 4044 && comparePermissionInfos(bp.perm.info, info)) { 4045 changed = false; 4046 } 4047 } 4048 bp.protectionLevel = fixedLevel; 4049 info = new PermissionInfo(info); 4050 info.protectionLevel = fixedLevel; 4051 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4052 bp.perm.info.packageName = tree.perm.info.packageName; 4053 bp.uid = tree.uid; 4054 if (added) { 4055 mSettings.mPermissions.put(info.name, bp); 4056 } 4057 if (changed) { 4058 if (!async) { 4059 mSettings.writeLPr(); 4060 } else { 4061 scheduleWriteSettingsLocked(); 4062 } 4063 } 4064 return added; 4065 } 4066 4067 @Override 4068 public boolean addPermission(PermissionInfo info) { 4069 synchronized (mPackages) { 4070 return addPermissionLocked(info, false); 4071 } 4072 } 4073 4074 @Override 4075 public boolean addPermissionAsync(PermissionInfo info) { 4076 synchronized (mPackages) { 4077 return addPermissionLocked(info, true); 4078 } 4079 } 4080 4081 @Override 4082 public void removePermission(String name) { 4083 synchronized (mPackages) { 4084 checkPermissionTreeLP(name); 4085 BasePermission bp = mSettings.mPermissions.get(name); 4086 if (bp != null) { 4087 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4088 throw new SecurityException( 4089 "Not allowed to modify non-dynamic permission " 4090 + name); 4091 } 4092 mSettings.mPermissions.remove(name); 4093 mSettings.writeLPr(); 4094 } 4095 } 4096 } 4097 4098 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4099 BasePermission bp) { 4100 int index = pkg.requestedPermissions.indexOf(bp.name); 4101 if (index == -1) { 4102 throw new SecurityException("Package " + pkg.packageName 4103 + " has not requested permission " + bp.name); 4104 } 4105 if (!bp.isRuntime() && !bp.isDevelopment()) { 4106 throw new SecurityException("Permission " + bp.name 4107 + " is not a changeable permission type"); 4108 } 4109 } 4110 4111 @Override 4112 public void grantRuntimePermission(String packageName, String name, final int userId) { 4113 if (!sUserManager.exists(userId)) { 4114 Log.e(TAG, "No such user:" + userId); 4115 return; 4116 } 4117 4118 mContext.enforceCallingOrSelfPermission( 4119 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4120 "grantRuntimePermission"); 4121 4122 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4123 true /* requireFullPermission */, true /* checkShell */, 4124 "grantRuntimePermission"); 4125 4126 final int uid; 4127 final SettingBase sb; 4128 4129 synchronized (mPackages) { 4130 final PackageParser.Package pkg = mPackages.get(packageName); 4131 if (pkg == null) { 4132 throw new IllegalArgumentException("Unknown package: " + packageName); 4133 } 4134 4135 final BasePermission bp = mSettings.mPermissions.get(name); 4136 if (bp == null) { 4137 throw new IllegalArgumentException("Unknown permission: " + name); 4138 } 4139 4140 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4141 4142 // If a permission review is required for legacy apps we represent 4143 // their permissions as always granted runtime ones since we need 4144 // to keep the review required permission flag per user while an 4145 // install permission's state is shared across all users. 4146 if (Build.PERMISSIONS_REVIEW_REQUIRED 4147 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4148 && bp.isRuntime()) { 4149 return; 4150 } 4151 4152 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4153 sb = (SettingBase) pkg.mExtras; 4154 if (sb == null) { 4155 throw new IllegalArgumentException("Unknown package: " + packageName); 4156 } 4157 4158 final PermissionsState permissionsState = sb.getPermissionsState(); 4159 4160 final int flags = permissionsState.getPermissionFlags(name, userId); 4161 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4162 throw new SecurityException("Cannot grant system fixed permission " 4163 + name + " for package " + packageName); 4164 } 4165 4166 if (bp.isDevelopment()) { 4167 // Development permissions must be handled specially, since they are not 4168 // normal runtime permissions. For now they apply to all users. 4169 if (permissionsState.grantInstallPermission(bp) != 4170 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4171 scheduleWriteSettingsLocked(); 4172 } 4173 return; 4174 } 4175 4176 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4177 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4178 return; 4179 } 4180 4181 final int result = permissionsState.grantRuntimePermission(bp, userId); 4182 switch (result) { 4183 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4184 return; 4185 } 4186 4187 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4188 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4189 mHandler.post(new Runnable() { 4190 @Override 4191 public void run() { 4192 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4193 } 4194 }); 4195 } 4196 break; 4197 } 4198 4199 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4200 4201 // Not critical if that is lost - app has to request again. 4202 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4203 } 4204 4205 // Only need to do this if user is initialized. Otherwise it's a new user 4206 // and there are no processes running as the user yet and there's no need 4207 // to make an expensive call to remount processes for the changed permissions. 4208 if (READ_EXTERNAL_STORAGE.equals(name) 4209 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4210 final long token = Binder.clearCallingIdentity(); 4211 try { 4212 if (sUserManager.isInitialized(userId)) { 4213 MountServiceInternal mountServiceInternal = LocalServices.getService( 4214 MountServiceInternal.class); 4215 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4216 } 4217 } finally { 4218 Binder.restoreCallingIdentity(token); 4219 } 4220 } 4221 } 4222 4223 @Override 4224 public void revokeRuntimePermission(String packageName, String name, int userId) { 4225 if (!sUserManager.exists(userId)) { 4226 Log.e(TAG, "No such user:" + userId); 4227 return; 4228 } 4229 4230 mContext.enforceCallingOrSelfPermission( 4231 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4232 "revokeRuntimePermission"); 4233 4234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4235 true /* requireFullPermission */, true /* checkShell */, 4236 "revokeRuntimePermission"); 4237 4238 final int appId; 4239 4240 synchronized (mPackages) { 4241 final PackageParser.Package pkg = mPackages.get(packageName); 4242 if (pkg == null) { 4243 throw new IllegalArgumentException("Unknown package: " + packageName); 4244 } 4245 4246 final BasePermission bp = mSettings.mPermissions.get(name); 4247 if (bp == null) { 4248 throw new IllegalArgumentException("Unknown permission: " + name); 4249 } 4250 4251 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4252 4253 // If a permission review is required for legacy apps we represent 4254 // their permissions as always granted runtime ones since we need 4255 // to keep the review required permission flag per user while an 4256 // install permission's state is shared across all users. 4257 if (Build.PERMISSIONS_REVIEW_REQUIRED 4258 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4259 && bp.isRuntime()) { 4260 return; 4261 } 4262 4263 SettingBase sb = (SettingBase) pkg.mExtras; 4264 if (sb == null) { 4265 throw new IllegalArgumentException("Unknown package: " + packageName); 4266 } 4267 4268 final PermissionsState permissionsState = sb.getPermissionsState(); 4269 4270 final int flags = permissionsState.getPermissionFlags(name, userId); 4271 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4272 throw new SecurityException("Cannot revoke system fixed permission " 4273 + name + " for package " + packageName); 4274 } 4275 4276 if (bp.isDevelopment()) { 4277 // Development permissions must be handled specially, since they are not 4278 // normal runtime permissions. For now they apply to all users. 4279 if (permissionsState.revokeInstallPermission(bp) != 4280 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4281 scheduleWriteSettingsLocked(); 4282 } 4283 return; 4284 } 4285 4286 if (permissionsState.revokeRuntimePermission(bp, userId) == 4287 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4288 return; 4289 } 4290 4291 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4292 4293 // Critical, after this call app should never have the permission. 4294 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4295 4296 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4297 } 4298 4299 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4300 } 4301 4302 @Override 4303 public void resetRuntimePermissions() { 4304 mContext.enforceCallingOrSelfPermission( 4305 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4306 "revokeRuntimePermission"); 4307 4308 int callingUid = Binder.getCallingUid(); 4309 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4310 mContext.enforceCallingOrSelfPermission( 4311 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4312 "resetRuntimePermissions"); 4313 } 4314 4315 synchronized (mPackages) { 4316 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4317 for (int userId : UserManagerService.getInstance().getUserIds()) { 4318 final int packageCount = mPackages.size(); 4319 for (int i = 0; i < packageCount; i++) { 4320 PackageParser.Package pkg = mPackages.valueAt(i); 4321 if (!(pkg.mExtras instanceof PackageSetting)) { 4322 continue; 4323 } 4324 PackageSetting ps = (PackageSetting) pkg.mExtras; 4325 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4326 } 4327 } 4328 } 4329 } 4330 4331 @Override 4332 public int getPermissionFlags(String name, String packageName, int userId) { 4333 if (!sUserManager.exists(userId)) { 4334 return 0; 4335 } 4336 4337 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4338 4339 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4340 true /* requireFullPermission */, false /* checkShell */, 4341 "getPermissionFlags"); 4342 4343 synchronized (mPackages) { 4344 final PackageParser.Package pkg = mPackages.get(packageName); 4345 if (pkg == null) { 4346 return 0; 4347 } 4348 4349 final BasePermission bp = mSettings.mPermissions.get(name); 4350 if (bp == null) { 4351 return 0; 4352 } 4353 4354 SettingBase sb = (SettingBase) pkg.mExtras; 4355 if (sb == null) { 4356 return 0; 4357 } 4358 4359 PermissionsState permissionsState = sb.getPermissionsState(); 4360 return permissionsState.getPermissionFlags(name, userId); 4361 } 4362 } 4363 4364 @Override 4365 public void updatePermissionFlags(String name, String packageName, int flagMask, 4366 int flagValues, int userId) { 4367 if (!sUserManager.exists(userId)) { 4368 return; 4369 } 4370 4371 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4372 4373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4374 true /* requireFullPermission */, true /* checkShell */, 4375 "updatePermissionFlags"); 4376 4377 // Only the system can change these flags and nothing else. 4378 if (getCallingUid() != Process.SYSTEM_UID) { 4379 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4380 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4381 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4382 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4383 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4384 } 4385 4386 synchronized (mPackages) { 4387 final PackageParser.Package pkg = mPackages.get(packageName); 4388 if (pkg == null) { 4389 throw new IllegalArgumentException("Unknown package: " + packageName); 4390 } 4391 4392 final BasePermission bp = mSettings.mPermissions.get(name); 4393 if (bp == null) { 4394 throw new IllegalArgumentException("Unknown permission: " + name); 4395 } 4396 4397 SettingBase sb = (SettingBase) pkg.mExtras; 4398 if (sb == null) { 4399 throw new IllegalArgumentException("Unknown package: " + packageName); 4400 } 4401 4402 PermissionsState permissionsState = sb.getPermissionsState(); 4403 4404 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4405 4406 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4407 // Install and runtime permissions are stored in different places, 4408 // so figure out what permission changed and persist the change. 4409 if (permissionsState.getInstallPermissionState(name) != null) { 4410 scheduleWriteSettingsLocked(); 4411 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4412 || hadState) { 4413 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4414 } 4415 } 4416 } 4417 } 4418 4419 /** 4420 * Update the permission flags for all packages and runtime permissions of a user in order 4421 * to allow device or profile owner to remove POLICY_FIXED. 4422 */ 4423 @Override 4424 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4425 if (!sUserManager.exists(userId)) { 4426 return; 4427 } 4428 4429 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4430 4431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4432 true /* requireFullPermission */, true /* checkShell */, 4433 "updatePermissionFlagsForAllApps"); 4434 4435 // Only the system can change system fixed flags. 4436 if (getCallingUid() != Process.SYSTEM_UID) { 4437 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4438 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4439 } 4440 4441 synchronized (mPackages) { 4442 boolean changed = false; 4443 final int packageCount = mPackages.size(); 4444 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4445 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4446 SettingBase sb = (SettingBase) pkg.mExtras; 4447 if (sb == null) { 4448 continue; 4449 } 4450 PermissionsState permissionsState = sb.getPermissionsState(); 4451 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4452 userId, flagMask, flagValues); 4453 } 4454 if (changed) { 4455 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4456 } 4457 } 4458 } 4459 4460 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4461 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4462 != PackageManager.PERMISSION_GRANTED 4463 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4464 != PackageManager.PERMISSION_GRANTED) { 4465 throw new SecurityException(message + " requires " 4466 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4467 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4468 } 4469 } 4470 4471 @Override 4472 public boolean shouldShowRequestPermissionRationale(String permissionName, 4473 String packageName, int userId) { 4474 if (UserHandle.getCallingUserId() != userId) { 4475 mContext.enforceCallingPermission( 4476 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4477 "canShowRequestPermissionRationale for user " + userId); 4478 } 4479 4480 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4481 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4482 return false; 4483 } 4484 4485 if (checkPermission(permissionName, packageName, userId) 4486 == PackageManager.PERMISSION_GRANTED) { 4487 return false; 4488 } 4489 4490 final int flags; 4491 4492 final long identity = Binder.clearCallingIdentity(); 4493 try { 4494 flags = getPermissionFlags(permissionName, 4495 packageName, userId); 4496 } finally { 4497 Binder.restoreCallingIdentity(identity); 4498 } 4499 4500 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4501 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4502 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4503 4504 if ((flags & fixedFlags) != 0) { 4505 return false; 4506 } 4507 4508 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4509 } 4510 4511 @Override 4512 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4513 mContext.enforceCallingOrSelfPermission( 4514 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4515 "addOnPermissionsChangeListener"); 4516 4517 synchronized (mPackages) { 4518 mOnPermissionChangeListeners.addListenerLocked(listener); 4519 } 4520 } 4521 4522 @Override 4523 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4524 synchronized (mPackages) { 4525 mOnPermissionChangeListeners.removeListenerLocked(listener); 4526 } 4527 } 4528 4529 @Override 4530 public boolean isProtectedBroadcast(String actionName) { 4531 synchronized (mPackages) { 4532 if (mProtectedBroadcasts.contains(actionName)) { 4533 return true; 4534 } else if (actionName != null) { 4535 // TODO: remove these terrible hacks 4536 if (actionName.startsWith("android.net.netmon.lingerExpired") 4537 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4538 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4539 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4540 return true; 4541 } 4542 } 4543 } 4544 return false; 4545 } 4546 4547 @Override 4548 public int checkSignatures(String pkg1, String pkg2) { 4549 synchronized (mPackages) { 4550 final PackageParser.Package p1 = mPackages.get(pkg1); 4551 final PackageParser.Package p2 = mPackages.get(pkg2); 4552 if (p1 == null || p1.mExtras == null 4553 || p2 == null || p2.mExtras == null) { 4554 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4555 } 4556 return compareSignatures(p1.mSignatures, p2.mSignatures); 4557 } 4558 } 4559 4560 @Override 4561 public int checkUidSignatures(int uid1, int uid2) { 4562 // Map to base uids. 4563 uid1 = UserHandle.getAppId(uid1); 4564 uid2 = UserHandle.getAppId(uid2); 4565 // reader 4566 synchronized (mPackages) { 4567 Signature[] s1; 4568 Signature[] s2; 4569 Object obj = mSettings.getUserIdLPr(uid1); 4570 if (obj != null) { 4571 if (obj instanceof SharedUserSetting) { 4572 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4573 } else if (obj instanceof PackageSetting) { 4574 s1 = ((PackageSetting)obj).signatures.mSignatures; 4575 } else { 4576 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4577 } 4578 } else { 4579 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4580 } 4581 obj = mSettings.getUserIdLPr(uid2); 4582 if (obj != null) { 4583 if (obj instanceof SharedUserSetting) { 4584 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4585 } else if (obj instanceof PackageSetting) { 4586 s2 = ((PackageSetting)obj).signatures.mSignatures; 4587 } else { 4588 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4589 } 4590 } else { 4591 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4592 } 4593 return compareSignatures(s1, s2); 4594 } 4595 } 4596 4597 /** 4598 * This method should typically only be used when granting or revoking 4599 * permissions, since the app may immediately restart after this call. 4600 * <p> 4601 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4602 * guard your work against the app being relaunched. 4603 */ 4604 private void killUid(int appId, int userId, String reason) { 4605 final long identity = Binder.clearCallingIdentity(); 4606 try { 4607 IActivityManager am = ActivityManagerNative.getDefault(); 4608 if (am != null) { 4609 try { 4610 am.killUid(appId, userId, reason); 4611 } catch (RemoteException e) { 4612 /* ignore - same process */ 4613 } 4614 } 4615 } finally { 4616 Binder.restoreCallingIdentity(identity); 4617 } 4618 } 4619 4620 /** 4621 * Compares two sets of signatures. Returns: 4622 * <br /> 4623 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4624 * <br /> 4625 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4626 * <br /> 4627 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4628 * <br /> 4629 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4630 * <br /> 4631 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4632 */ 4633 static int compareSignatures(Signature[] s1, Signature[] s2) { 4634 if (s1 == null) { 4635 return s2 == null 4636 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4637 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4638 } 4639 4640 if (s2 == null) { 4641 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4642 } 4643 4644 if (s1.length != s2.length) { 4645 return PackageManager.SIGNATURE_NO_MATCH; 4646 } 4647 4648 // Since both signature sets are of size 1, we can compare without HashSets. 4649 if (s1.length == 1) { 4650 return s1[0].equals(s2[0]) ? 4651 PackageManager.SIGNATURE_MATCH : 4652 PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4656 for (Signature sig : s1) { 4657 set1.add(sig); 4658 } 4659 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4660 for (Signature sig : s2) { 4661 set2.add(sig); 4662 } 4663 // Make sure s2 contains all signatures in s1. 4664 if (set1.equals(set2)) { 4665 return PackageManager.SIGNATURE_MATCH; 4666 } 4667 return PackageManager.SIGNATURE_NO_MATCH; 4668 } 4669 4670 /** 4671 * If the database version for this type of package (internal storage or 4672 * external storage) is less than the version where package signatures 4673 * were updated, return true. 4674 */ 4675 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4676 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4677 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4678 } 4679 4680 /** 4681 * Used for backward compatibility to make sure any packages with 4682 * certificate chains get upgraded to the new style. {@code existingSigs} 4683 * will be in the old format (since they were stored on disk from before the 4684 * system upgrade) and {@code scannedSigs} will be in the newer format. 4685 */ 4686 private int compareSignaturesCompat(PackageSignatures existingSigs, 4687 PackageParser.Package scannedPkg) { 4688 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4689 return PackageManager.SIGNATURE_NO_MATCH; 4690 } 4691 4692 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4693 for (Signature sig : existingSigs.mSignatures) { 4694 existingSet.add(sig); 4695 } 4696 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4697 for (Signature sig : scannedPkg.mSignatures) { 4698 try { 4699 Signature[] chainSignatures = sig.getChainSignatures(); 4700 for (Signature chainSig : chainSignatures) { 4701 scannedCompatSet.add(chainSig); 4702 } 4703 } catch (CertificateEncodingException e) { 4704 scannedCompatSet.add(sig); 4705 } 4706 } 4707 /* 4708 * Make sure the expanded scanned set contains all signatures in the 4709 * existing one. 4710 */ 4711 if (scannedCompatSet.equals(existingSet)) { 4712 // Migrate the old signatures to the new scheme. 4713 existingSigs.assignSignatures(scannedPkg.mSignatures); 4714 // The new KeySets will be re-added later in the scanning process. 4715 synchronized (mPackages) { 4716 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4717 } 4718 return PackageManager.SIGNATURE_MATCH; 4719 } 4720 return PackageManager.SIGNATURE_NO_MATCH; 4721 } 4722 4723 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4724 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4725 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4726 } 4727 4728 private int compareSignaturesRecover(PackageSignatures existingSigs, 4729 PackageParser.Package scannedPkg) { 4730 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4731 return PackageManager.SIGNATURE_NO_MATCH; 4732 } 4733 4734 String msg = null; 4735 try { 4736 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4737 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4738 + scannedPkg.packageName); 4739 return PackageManager.SIGNATURE_MATCH; 4740 } 4741 } catch (CertificateException e) { 4742 msg = e.getMessage(); 4743 } 4744 4745 logCriticalInfo(Log.INFO, 4746 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4747 return PackageManager.SIGNATURE_NO_MATCH; 4748 } 4749 4750 @Override 4751 public List<String> getAllPackages() { 4752 synchronized (mPackages) { 4753 return new ArrayList<String>(mPackages.keySet()); 4754 } 4755 } 4756 4757 @Override 4758 public String[] getPackagesForUid(int uid) { 4759 uid = UserHandle.getAppId(uid); 4760 // reader 4761 synchronized (mPackages) { 4762 Object obj = mSettings.getUserIdLPr(uid); 4763 if (obj instanceof SharedUserSetting) { 4764 final SharedUserSetting sus = (SharedUserSetting) obj; 4765 final int N = sus.packages.size(); 4766 final String[] res = new String[N]; 4767 for (int i = 0; i < N; i++) { 4768 res[i] = sus.packages.valueAt(i).name; 4769 } 4770 return res; 4771 } else if (obj instanceof PackageSetting) { 4772 final PackageSetting ps = (PackageSetting) obj; 4773 return new String[] { ps.name }; 4774 } 4775 } 4776 return null; 4777 } 4778 4779 @Override 4780 public String getNameForUid(int uid) { 4781 // reader 4782 synchronized (mPackages) { 4783 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4784 if (obj instanceof SharedUserSetting) { 4785 final SharedUserSetting sus = (SharedUserSetting) obj; 4786 return sus.name + ":" + sus.userId; 4787 } else if (obj instanceof PackageSetting) { 4788 final PackageSetting ps = (PackageSetting) obj; 4789 return ps.name; 4790 } 4791 } 4792 return null; 4793 } 4794 4795 @Override 4796 public int getUidForSharedUser(String sharedUserName) { 4797 if(sharedUserName == null) { 4798 return -1; 4799 } 4800 // reader 4801 synchronized (mPackages) { 4802 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4803 if (suid == null) { 4804 return -1; 4805 } 4806 return suid.userId; 4807 } 4808 } 4809 4810 @Override 4811 public int getFlagsForUid(int uid) { 4812 synchronized (mPackages) { 4813 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4814 if (obj instanceof SharedUserSetting) { 4815 final SharedUserSetting sus = (SharedUserSetting) obj; 4816 return sus.pkgFlags; 4817 } else if (obj instanceof PackageSetting) { 4818 final PackageSetting ps = (PackageSetting) obj; 4819 return ps.pkgFlags; 4820 } 4821 } 4822 return 0; 4823 } 4824 4825 @Override 4826 public int getPrivateFlagsForUid(int uid) { 4827 synchronized (mPackages) { 4828 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4829 if (obj instanceof SharedUserSetting) { 4830 final SharedUserSetting sus = (SharedUserSetting) obj; 4831 return sus.pkgPrivateFlags; 4832 } else if (obj instanceof PackageSetting) { 4833 final PackageSetting ps = (PackageSetting) obj; 4834 return ps.pkgPrivateFlags; 4835 } 4836 } 4837 return 0; 4838 } 4839 4840 @Override 4841 public boolean isUidPrivileged(int uid) { 4842 uid = UserHandle.getAppId(uid); 4843 // reader 4844 synchronized (mPackages) { 4845 Object obj = mSettings.getUserIdLPr(uid); 4846 if (obj instanceof SharedUserSetting) { 4847 final SharedUserSetting sus = (SharedUserSetting) obj; 4848 final Iterator<PackageSetting> it = sus.packages.iterator(); 4849 while (it.hasNext()) { 4850 if (it.next().isPrivileged()) { 4851 return true; 4852 } 4853 } 4854 } else if (obj instanceof PackageSetting) { 4855 final PackageSetting ps = (PackageSetting) obj; 4856 return ps.isPrivileged(); 4857 } 4858 } 4859 return false; 4860 } 4861 4862 @Override 4863 public String[] getAppOpPermissionPackages(String permissionName) { 4864 synchronized (mPackages) { 4865 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4866 if (pkgs == null) { 4867 return null; 4868 } 4869 return pkgs.toArray(new String[pkgs.size()]); 4870 } 4871 } 4872 4873 @Override 4874 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4875 int flags, int userId) { 4876 try { 4877 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4878 4879 if (!sUserManager.exists(userId)) return null; 4880 flags = updateFlagsForResolve(flags, userId, intent); 4881 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4882 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4883 4884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4885 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4886 flags, userId); 4887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4888 4889 final ResolveInfo bestChoice = 4890 chooseBestActivity(intent, resolvedType, flags, query, userId); 4891 4892 if (isEphemeralAllowed(intent, query, userId)) { 4893 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4894 final EphemeralResolveInfo ai = 4895 getEphemeralResolveInfo(intent, resolvedType, userId); 4896 if (ai != null) { 4897 if (DEBUG_EPHEMERAL) { 4898 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4899 } 4900 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4901 bestChoice.ephemeralResolveInfo = ai; 4902 } 4903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4904 } 4905 return bestChoice; 4906 } finally { 4907 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4908 } 4909 } 4910 4911 @Override 4912 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4913 IntentFilter filter, int match, ComponentName activity) { 4914 final int userId = UserHandle.getCallingUserId(); 4915 if (DEBUG_PREFERRED) { 4916 Log.v(TAG, "setLastChosenActivity intent=" + intent 4917 + " resolvedType=" + resolvedType 4918 + " flags=" + flags 4919 + " filter=" + filter 4920 + " match=" + match 4921 + " activity=" + activity); 4922 filter.dump(new PrintStreamPrinter(System.out), " "); 4923 } 4924 intent.setComponent(null); 4925 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4926 userId); 4927 // Find any earlier preferred or last chosen entries and nuke them 4928 findPreferredActivity(intent, resolvedType, 4929 flags, query, 0, false, true, false, userId); 4930 // Add the new activity as the last chosen for this filter 4931 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4932 "Setting last chosen"); 4933 } 4934 4935 @Override 4936 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4937 final int userId = UserHandle.getCallingUserId(); 4938 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4939 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4940 userId); 4941 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4942 false, false, false, userId); 4943 } 4944 4945 4946 private boolean isEphemeralAllowed( 4947 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4948 // Short circuit and return early if possible. 4949 if (DISABLE_EPHEMERAL_APPS) { 4950 return false; 4951 } 4952 final int callingUser = UserHandle.getCallingUserId(); 4953 if (callingUser != UserHandle.USER_SYSTEM) { 4954 return false; 4955 } 4956 if (mEphemeralResolverConnection == null) { 4957 return false; 4958 } 4959 if (intent.getComponent() != null) { 4960 return false; 4961 } 4962 if (intent.getPackage() != null) { 4963 return false; 4964 } 4965 final boolean isWebUri = hasWebURI(intent); 4966 if (!isWebUri) { 4967 return false; 4968 } 4969 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4970 synchronized (mPackages) { 4971 final int count = resolvedActivites.size(); 4972 for (int n = 0; n < count; n++) { 4973 ResolveInfo info = resolvedActivites.get(n); 4974 String packageName = info.activityInfo.packageName; 4975 PackageSetting ps = mSettings.mPackages.get(packageName); 4976 if (ps != null) { 4977 // Try to get the status from User settings first 4978 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4979 int status = (int) (packedStatus >> 32); 4980 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4981 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4982 if (DEBUG_EPHEMERAL) { 4983 Slog.v(TAG, "DENY ephemeral apps;" 4984 + " pkg: " + packageName + ", status: " + status); 4985 } 4986 return false; 4987 } 4988 } 4989 } 4990 } 4991 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4992 return true; 4993 } 4994 4995 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4996 int userId) { 4997 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 4998 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4999 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5000 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5001 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixCount); 5002 final int[] shaPrefix = digest.getDigestPrefix(); 5003 final byte[][] digestBytes = digest.getDigestBytes(); 5004 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5005 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5006 shaPrefix, ephemeralPrefixMask); 5007 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5008 // No hash prefix match; there are no ephemeral apps for this domain. 5009 return null; 5010 } 5011 5012 // Go in reverse order so we match the narrowest scope first. 5013 for (int i = shaPrefix.length; i >= 0 ; --i) { 5014 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5015 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5016 continue; 5017 } 5018 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5019 // No filters; this should never happen. 5020 if (filters.isEmpty()) { 5021 continue; 5022 } 5023 // We have a domain match; resolve the filters to see if anything matches. 5024 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5025 for (int j = filters.size() - 1; j >= 0; --j) { 5026 final EphemeralResolveIntentInfo intentInfo = 5027 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5028 ephemeralResolver.addFilter(intentInfo); 5029 } 5030 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5031 intent, resolvedType, false /*defaultOnly*/, userId); 5032 if (!matchedResolveInfoList.isEmpty()) { 5033 return matchedResolveInfoList.get(0); 5034 } 5035 } 5036 } 5037 // Hash or filter mis-match; no ephemeral apps for this domain. 5038 return null; 5039 } 5040 5041 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5042 int flags, List<ResolveInfo> query, int userId) { 5043 if (query != null) { 5044 final int N = query.size(); 5045 if (N == 1) { 5046 return query.get(0); 5047 } else if (N > 1) { 5048 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5049 // If there is more than one activity with the same priority, 5050 // then let the user decide between them. 5051 ResolveInfo r0 = query.get(0); 5052 ResolveInfo r1 = query.get(1); 5053 if (DEBUG_INTENT_MATCHING || debug) { 5054 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5055 + r1.activityInfo.name + "=" + r1.priority); 5056 } 5057 // If the first activity has a higher priority, or a different 5058 // default, then it is always desirable to pick it. 5059 if (r0.priority != r1.priority 5060 || r0.preferredOrder != r1.preferredOrder 5061 || r0.isDefault != r1.isDefault) { 5062 return query.get(0); 5063 } 5064 // If we have saved a preference for a preferred activity for 5065 // this Intent, use that. 5066 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5067 flags, query, r0.priority, true, false, debug, userId); 5068 if (ri != null) { 5069 return ri; 5070 } 5071 ri = new ResolveInfo(mResolveInfo); 5072 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5073 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5074 // If all of the options come from the same package, show the application's 5075 // label and icon instead of the generic resolver's. 5076 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5077 // and then throw away the ResolveInfo itself, meaning that the caller loses 5078 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5079 // a fallback for this case; we only set the target package's resources on 5080 // the ResolveInfo, not the ActivityInfo. 5081 final String intentPackage = intent.getPackage(); 5082 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5083 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5084 ri.resolvePackageName = intentPackage; 5085 if (userNeedsBadging(userId)) { 5086 ri.noResourceId = true; 5087 } else { 5088 ri.icon = appi.icon; 5089 } 5090 ri.iconResourceId = appi.icon; 5091 ri.labelRes = appi.labelRes; 5092 } 5093 ri.activityInfo.applicationInfo = new ApplicationInfo( 5094 ri.activityInfo.applicationInfo); 5095 if (userId != 0) { 5096 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5097 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5098 } 5099 // Make sure that the resolver is displayable in car mode 5100 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5101 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5102 return ri; 5103 } 5104 } 5105 return null; 5106 } 5107 5108 /** 5109 * Return true if the given list is not empty and all of its contents have 5110 * an activityInfo with the given package name. 5111 */ 5112 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5113 if (ArrayUtils.isEmpty(list)) { 5114 return false; 5115 } 5116 for (int i = 0, N = list.size(); i < N; i++) { 5117 final ResolveInfo ri = list.get(i); 5118 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5119 if (ai == null || !packageName.equals(ai.packageName)) { 5120 return false; 5121 } 5122 } 5123 return true; 5124 } 5125 5126 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5127 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5128 final int N = query.size(); 5129 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5130 .get(userId); 5131 // Get the list of persistent preferred activities that handle the intent 5132 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5133 List<PersistentPreferredActivity> pprefs = ppir != null 5134 ? ppir.queryIntent(intent, resolvedType, 5135 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5136 : null; 5137 if (pprefs != null && pprefs.size() > 0) { 5138 final int M = pprefs.size(); 5139 for (int i=0; i<M; i++) { 5140 final PersistentPreferredActivity ppa = pprefs.get(i); 5141 if (DEBUG_PREFERRED || debug) { 5142 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5143 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5144 + "\n component=" + ppa.mComponent); 5145 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5146 } 5147 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5148 flags | MATCH_DISABLED_COMPONENTS, userId); 5149 if (DEBUG_PREFERRED || debug) { 5150 Slog.v(TAG, "Found persistent preferred activity:"); 5151 if (ai != null) { 5152 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5153 } else { 5154 Slog.v(TAG, " null"); 5155 } 5156 } 5157 if (ai == null) { 5158 // This previously registered persistent preferred activity 5159 // component is no longer known. Ignore it and do NOT remove it. 5160 continue; 5161 } 5162 for (int j=0; j<N; j++) { 5163 final ResolveInfo ri = query.get(j); 5164 if (!ri.activityInfo.applicationInfo.packageName 5165 .equals(ai.applicationInfo.packageName)) { 5166 continue; 5167 } 5168 if (!ri.activityInfo.name.equals(ai.name)) { 5169 continue; 5170 } 5171 // Found a persistent preference that can handle the intent. 5172 if (DEBUG_PREFERRED || debug) { 5173 Slog.v(TAG, "Returning persistent preferred activity: " + 5174 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5175 } 5176 return ri; 5177 } 5178 } 5179 } 5180 return null; 5181 } 5182 5183 // TODO: handle preferred activities missing while user has amnesia 5184 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5185 List<ResolveInfo> query, int priority, boolean always, 5186 boolean removeMatches, boolean debug, int userId) { 5187 if (!sUserManager.exists(userId)) return null; 5188 flags = updateFlagsForResolve(flags, userId, intent); 5189 // writer 5190 synchronized (mPackages) { 5191 if (intent.getSelector() != null) { 5192 intent = intent.getSelector(); 5193 } 5194 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5195 5196 // Try to find a matching persistent preferred activity. 5197 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5198 debug, userId); 5199 5200 // If a persistent preferred activity matched, use it. 5201 if (pri != null) { 5202 return pri; 5203 } 5204 5205 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5206 // Get the list of preferred activities that handle the intent 5207 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5208 List<PreferredActivity> prefs = pir != null 5209 ? pir.queryIntent(intent, resolvedType, 5210 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5211 : null; 5212 if (prefs != null && prefs.size() > 0) { 5213 boolean changed = false; 5214 try { 5215 // First figure out how good the original match set is. 5216 // We will only allow preferred activities that came 5217 // from the same match quality. 5218 int match = 0; 5219 5220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5221 5222 final int N = query.size(); 5223 for (int j=0; j<N; j++) { 5224 final ResolveInfo ri = query.get(j); 5225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5226 + ": 0x" + Integer.toHexString(match)); 5227 if (ri.match > match) { 5228 match = ri.match; 5229 } 5230 } 5231 5232 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5233 + Integer.toHexString(match)); 5234 5235 match &= IntentFilter.MATCH_CATEGORY_MASK; 5236 final int M = prefs.size(); 5237 for (int i=0; i<M; i++) { 5238 final PreferredActivity pa = prefs.get(i); 5239 if (DEBUG_PREFERRED || debug) { 5240 Slog.v(TAG, "Checking PreferredActivity ds=" 5241 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5242 + "\n component=" + pa.mPref.mComponent); 5243 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5244 } 5245 if (pa.mPref.mMatch != match) { 5246 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5247 + Integer.toHexString(pa.mPref.mMatch)); 5248 continue; 5249 } 5250 // If it's not an "always" type preferred activity and that's what we're 5251 // looking for, skip it. 5252 if (always && !pa.mPref.mAlways) { 5253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5254 continue; 5255 } 5256 final ActivityInfo ai = getActivityInfo( 5257 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5258 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5259 userId); 5260 if (DEBUG_PREFERRED || debug) { 5261 Slog.v(TAG, "Found preferred activity:"); 5262 if (ai != null) { 5263 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5264 } else { 5265 Slog.v(TAG, " null"); 5266 } 5267 } 5268 if (ai == null) { 5269 // This previously registered preferred activity 5270 // component is no longer known. Most likely an update 5271 // to the app was installed and in the new version this 5272 // component no longer exists. Clean it up by removing 5273 // it from the preferred activities list, and skip it. 5274 Slog.w(TAG, "Removing dangling preferred activity: " 5275 + pa.mPref.mComponent); 5276 pir.removeFilter(pa); 5277 changed = true; 5278 continue; 5279 } 5280 for (int j=0; j<N; j++) { 5281 final ResolveInfo ri = query.get(j); 5282 if (!ri.activityInfo.applicationInfo.packageName 5283 .equals(ai.applicationInfo.packageName)) { 5284 continue; 5285 } 5286 if (!ri.activityInfo.name.equals(ai.name)) { 5287 continue; 5288 } 5289 5290 if (removeMatches) { 5291 pir.removeFilter(pa); 5292 changed = true; 5293 if (DEBUG_PREFERRED) { 5294 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5295 } 5296 break; 5297 } 5298 5299 // Okay we found a previously set preferred or last chosen app. 5300 // If the result set is different from when this 5301 // was created, we need to clear it and re-ask the 5302 // user their preference, if we're looking for an "always" type entry. 5303 if (always && !pa.mPref.sameSet(query)) { 5304 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5305 + intent + " type " + resolvedType); 5306 if (DEBUG_PREFERRED) { 5307 Slog.v(TAG, "Removing preferred activity since set changed " 5308 + pa.mPref.mComponent); 5309 } 5310 pir.removeFilter(pa); 5311 // Re-add the filter as a "last chosen" entry (!always) 5312 PreferredActivity lastChosen = new PreferredActivity( 5313 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5314 pir.addFilter(lastChosen); 5315 changed = true; 5316 return null; 5317 } 5318 5319 // Yay! Either the set matched or we're looking for the last chosen 5320 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5321 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5322 return ri; 5323 } 5324 } 5325 } finally { 5326 if (changed) { 5327 if (DEBUG_PREFERRED) { 5328 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5329 } 5330 scheduleWritePackageRestrictionsLocked(userId); 5331 } 5332 } 5333 } 5334 } 5335 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5336 return null; 5337 } 5338 5339 /* 5340 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5341 */ 5342 @Override 5343 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5344 int targetUserId) { 5345 mContext.enforceCallingOrSelfPermission( 5346 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5347 List<CrossProfileIntentFilter> matches = 5348 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5349 if (matches != null) { 5350 int size = matches.size(); 5351 for (int i = 0; i < size; i++) { 5352 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5353 } 5354 } 5355 if (hasWebURI(intent)) { 5356 // cross-profile app linking works only towards the parent. 5357 final UserInfo parent = getProfileParent(sourceUserId); 5358 synchronized(mPackages) { 5359 int flags = updateFlagsForResolve(0, parent.id, intent); 5360 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5361 intent, resolvedType, flags, sourceUserId, parent.id); 5362 return xpDomainInfo != null; 5363 } 5364 } 5365 return false; 5366 } 5367 5368 private UserInfo getProfileParent(int userId) { 5369 final long identity = Binder.clearCallingIdentity(); 5370 try { 5371 return sUserManager.getProfileParent(userId); 5372 } finally { 5373 Binder.restoreCallingIdentity(identity); 5374 } 5375 } 5376 5377 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5378 String resolvedType, int userId) { 5379 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5380 if (resolver != null) { 5381 return resolver.queryIntent(intent, resolvedType, false, userId); 5382 } 5383 return null; 5384 } 5385 5386 @Override 5387 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5388 String resolvedType, int flags, int userId) { 5389 try { 5390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5391 5392 return new ParceledListSlice<>( 5393 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5394 } finally { 5395 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5396 } 5397 } 5398 5399 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5400 String resolvedType, int flags, int userId) { 5401 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5402 flags = updateFlagsForResolve(flags, userId, intent); 5403 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5404 false /* requireFullPermission */, false /* checkShell */, 5405 "query intent activities"); 5406 ComponentName comp = intent.getComponent(); 5407 if (comp == null) { 5408 if (intent.getSelector() != null) { 5409 intent = intent.getSelector(); 5410 comp = intent.getComponent(); 5411 } 5412 } 5413 5414 if (comp != null) { 5415 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5416 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5417 if (ai != null) { 5418 final ResolveInfo ri = new ResolveInfo(); 5419 ri.activityInfo = ai; 5420 list.add(ri); 5421 } 5422 return list; 5423 } 5424 5425 // reader 5426 synchronized (mPackages) { 5427 final String pkgName = intent.getPackage(); 5428 if (pkgName == null) { 5429 List<CrossProfileIntentFilter> matchingFilters = 5430 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5431 // Check for results that need to skip the current profile. 5432 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5433 resolvedType, flags, userId); 5434 if (xpResolveInfo != null) { 5435 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5436 result.add(xpResolveInfo); 5437 return filterIfNotSystemUser(result, userId); 5438 } 5439 5440 // Check for results in the current profile. 5441 List<ResolveInfo> result = mActivities.queryIntent( 5442 intent, resolvedType, flags, userId); 5443 result = filterIfNotSystemUser(result, userId); 5444 5445 // Check for cross profile results. 5446 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5447 xpResolveInfo = queryCrossProfileIntents( 5448 matchingFilters, intent, resolvedType, flags, userId, 5449 hasNonNegativePriorityResult); 5450 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5451 boolean isVisibleToUser = filterIfNotSystemUser( 5452 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5453 if (isVisibleToUser) { 5454 result.add(xpResolveInfo); 5455 Collections.sort(result, mResolvePrioritySorter); 5456 } 5457 } 5458 if (hasWebURI(intent)) { 5459 CrossProfileDomainInfo xpDomainInfo = null; 5460 final UserInfo parent = getProfileParent(userId); 5461 if (parent != null) { 5462 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5463 flags, userId, parent.id); 5464 } 5465 if (xpDomainInfo != null) { 5466 if (xpResolveInfo != null) { 5467 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5468 // in the result. 5469 result.remove(xpResolveInfo); 5470 } 5471 if (result.size() == 0) { 5472 result.add(xpDomainInfo.resolveInfo); 5473 return result; 5474 } 5475 } else if (result.size() <= 1) { 5476 return result; 5477 } 5478 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5479 xpDomainInfo, userId); 5480 Collections.sort(result, mResolvePrioritySorter); 5481 } 5482 return result; 5483 } 5484 final PackageParser.Package pkg = mPackages.get(pkgName); 5485 if (pkg != null) { 5486 return filterIfNotSystemUser( 5487 mActivities.queryIntentForPackage( 5488 intent, resolvedType, flags, pkg.activities, userId), 5489 userId); 5490 } 5491 return new ArrayList<ResolveInfo>(); 5492 } 5493 } 5494 5495 private static class CrossProfileDomainInfo { 5496 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5497 ResolveInfo resolveInfo; 5498 /* Best domain verification status of the activities found in the other profile */ 5499 int bestDomainVerificationStatus; 5500 } 5501 5502 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5503 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5504 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5505 sourceUserId)) { 5506 return null; 5507 } 5508 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5509 resolvedType, flags, parentUserId); 5510 5511 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5512 return null; 5513 } 5514 CrossProfileDomainInfo result = null; 5515 int size = resultTargetUser.size(); 5516 for (int i = 0; i < size; i++) { 5517 ResolveInfo riTargetUser = resultTargetUser.get(i); 5518 // Intent filter verification is only for filters that specify a host. So don't return 5519 // those that handle all web uris. 5520 if (riTargetUser.handleAllWebDataURI) { 5521 continue; 5522 } 5523 String packageName = riTargetUser.activityInfo.packageName; 5524 PackageSetting ps = mSettings.mPackages.get(packageName); 5525 if (ps == null) { 5526 continue; 5527 } 5528 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5529 int status = (int)(verificationState >> 32); 5530 if (result == null) { 5531 result = new CrossProfileDomainInfo(); 5532 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5533 sourceUserId, parentUserId); 5534 result.bestDomainVerificationStatus = status; 5535 } else { 5536 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5537 result.bestDomainVerificationStatus); 5538 } 5539 } 5540 // Don't consider matches with status NEVER across profiles. 5541 if (result != null && result.bestDomainVerificationStatus 5542 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5543 return null; 5544 } 5545 return result; 5546 } 5547 5548 /** 5549 * Verification statuses are ordered from the worse to the best, except for 5550 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5551 */ 5552 private int bestDomainVerificationStatus(int status1, int status2) { 5553 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5554 return status2; 5555 } 5556 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5557 return status1; 5558 } 5559 return (int) MathUtils.max(status1, status2); 5560 } 5561 5562 private boolean isUserEnabled(int userId) { 5563 long callingId = Binder.clearCallingIdentity(); 5564 try { 5565 UserInfo userInfo = sUserManager.getUserInfo(userId); 5566 return userInfo != null && userInfo.isEnabled(); 5567 } finally { 5568 Binder.restoreCallingIdentity(callingId); 5569 } 5570 } 5571 5572 /** 5573 * Filter out activities with systemUserOnly flag set, when current user is not System. 5574 * 5575 * @return filtered list 5576 */ 5577 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5578 if (userId == UserHandle.USER_SYSTEM) { 5579 return resolveInfos; 5580 } 5581 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5582 ResolveInfo info = resolveInfos.get(i); 5583 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5584 resolveInfos.remove(i); 5585 } 5586 } 5587 return resolveInfos; 5588 } 5589 5590 /** 5591 * @param resolveInfos list of resolve infos in descending priority order 5592 * @return if the list contains a resolve info with non-negative priority 5593 */ 5594 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5595 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5596 } 5597 5598 private static boolean hasWebURI(Intent intent) { 5599 if (intent.getData() == null) { 5600 return false; 5601 } 5602 final String scheme = intent.getScheme(); 5603 if (TextUtils.isEmpty(scheme)) { 5604 return false; 5605 } 5606 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5607 } 5608 5609 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5610 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5611 int userId) { 5612 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5613 5614 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5615 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5616 candidates.size()); 5617 } 5618 5619 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5620 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5621 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5622 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5623 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5624 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5625 5626 synchronized (mPackages) { 5627 final int count = candidates.size(); 5628 // First, try to use linked apps. Partition the candidates into four lists: 5629 // one for the final results, one for the "do not use ever", one for "undefined status" 5630 // and finally one for "browser app type". 5631 for (int n=0; n<count; n++) { 5632 ResolveInfo info = candidates.get(n); 5633 String packageName = info.activityInfo.packageName; 5634 PackageSetting ps = mSettings.mPackages.get(packageName); 5635 if (ps != null) { 5636 // Add to the special match all list (Browser use case) 5637 if (info.handleAllWebDataURI) { 5638 matchAllList.add(info); 5639 continue; 5640 } 5641 // Try to get the status from User settings first 5642 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5643 int status = (int)(packedStatus >> 32); 5644 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5645 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5646 if (DEBUG_DOMAIN_VERIFICATION) { 5647 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5648 + " : linkgen=" + linkGeneration); 5649 } 5650 // Use link-enabled generation as preferredOrder, i.e. 5651 // prefer newly-enabled over earlier-enabled. 5652 info.preferredOrder = linkGeneration; 5653 alwaysList.add(info); 5654 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5655 if (DEBUG_DOMAIN_VERIFICATION) { 5656 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5657 } 5658 neverList.add(info); 5659 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5660 if (DEBUG_DOMAIN_VERIFICATION) { 5661 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5662 } 5663 alwaysAskList.add(info); 5664 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5665 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5666 if (DEBUG_DOMAIN_VERIFICATION) { 5667 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5668 } 5669 undefinedList.add(info); 5670 } 5671 } 5672 } 5673 5674 // We'll want to include browser possibilities in a few cases 5675 boolean includeBrowser = false; 5676 5677 // First try to add the "always" resolution(s) for the current user, if any 5678 if (alwaysList.size() > 0) { 5679 result.addAll(alwaysList); 5680 } else { 5681 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5682 result.addAll(undefinedList); 5683 // Maybe add one for the other profile. 5684 if (xpDomainInfo != null && ( 5685 xpDomainInfo.bestDomainVerificationStatus 5686 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5687 result.add(xpDomainInfo.resolveInfo); 5688 } 5689 includeBrowser = true; 5690 } 5691 5692 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5693 // If there were 'always' entries their preferred order has been set, so we also 5694 // back that off to make the alternatives equivalent 5695 if (alwaysAskList.size() > 0) { 5696 for (ResolveInfo i : result) { 5697 i.preferredOrder = 0; 5698 } 5699 result.addAll(alwaysAskList); 5700 includeBrowser = true; 5701 } 5702 5703 if (includeBrowser) { 5704 // Also add browsers (all of them or only the default one) 5705 if (DEBUG_DOMAIN_VERIFICATION) { 5706 Slog.v(TAG, " ...including browsers in candidate set"); 5707 } 5708 if ((matchFlags & MATCH_ALL) != 0) { 5709 result.addAll(matchAllList); 5710 } else { 5711 // Browser/generic handling case. If there's a default browser, go straight 5712 // to that (but only if there is no other higher-priority match). 5713 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5714 int maxMatchPrio = 0; 5715 ResolveInfo defaultBrowserMatch = null; 5716 final int numCandidates = matchAllList.size(); 5717 for (int n = 0; n < numCandidates; n++) { 5718 ResolveInfo info = matchAllList.get(n); 5719 // track the highest overall match priority... 5720 if (info.priority > maxMatchPrio) { 5721 maxMatchPrio = info.priority; 5722 } 5723 // ...and the highest-priority default browser match 5724 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5725 if (defaultBrowserMatch == null 5726 || (defaultBrowserMatch.priority < info.priority)) { 5727 if (debug) { 5728 Slog.v(TAG, "Considering default browser match " + info); 5729 } 5730 defaultBrowserMatch = info; 5731 } 5732 } 5733 } 5734 if (defaultBrowserMatch != null 5735 && defaultBrowserMatch.priority >= maxMatchPrio 5736 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5737 { 5738 if (debug) { 5739 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5740 } 5741 result.add(defaultBrowserMatch); 5742 } else { 5743 result.addAll(matchAllList); 5744 } 5745 } 5746 5747 // If there is nothing selected, add all candidates and remove the ones that the user 5748 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5749 if (result.size() == 0) { 5750 result.addAll(candidates); 5751 result.removeAll(neverList); 5752 } 5753 } 5754 } 5755 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5756 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5757 result.size()); 5758 for (ResolveInfo info : result) { 5759 Slog.v(TAG, " + " + info.activityInfo); 5760 } 5761 } 5762 return result; 5763 } 5764 5765 // Returns a packed value as a long: 5766 // 5767 // high 'int'-sized word: link status: undefined/ask/never/always. 5768 // low 'int'-sized word: relative priority among 'always' results. 5769 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5770 long result = ps.getDomainVerificationStatusForUser(userId); 5771 // if none available, get the master status 5772 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5773 if (ps.getIntentFilterVerificationInfo() != null) { 5774 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5775 } 5776 } 5777 return result; 5778 } 5779 5780 private ResolveInfo querySkipCurrentProfileIntents( 5781 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5782 int flags, int sourceUserId) { 5783 if (matchingFilters != null) { 5784 int size = matchingFilters.size(); 5785 for (int i = 0; i < size; i ++) { 5786 CrossProfileIntentFilter filter = matchingFilters.get(i); 5787 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5788 // Checking if there are activities in the target user that can handle the 5789 // intent. 5790 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5791 resolvedType, flags, sourceUserId); 5792 if (resolveInfo != null) { 5793 return resolveInfo; 5794 } 5795 } 5796 } 5797 } 5798 return null; 5799 } 5800 5801 // Return matching ResolveInfo in target user if any. 5802 private ResolveInfo queryCrossProfileIntents( 5803 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5804 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5805 if (matchingFilters != null) { 5806 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5807 // match the same intent. For performance reasons, it is better not to 5808 // run queryIntent twice for the same userId 5809 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5810 int size = matchingFilters.size(); 5811 for (int i = 0; i < size; i++) { 5812 CrossProfileIntentFilter filter = matchingFilters.get(i); 5813 int targetUserId = filter.getTargetUserId(); 5814 boolean skipCurrentProfile = 5815 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5816 boolean skipCurrentProfileIfNoMatchFound = 5817 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5818 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5819 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5820 // Checking if there are activities in the target user that can handle the 5821 // intent. 5822 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5823 resolvedType, flags, sourceUserId); 5824 if (resolveInfo != null) return resolveInfo; 5825 alreadyTriedUserIds.put(targetUserId, true); 5826 } 5827 } 5828 } 5829 return null; 5830 } 5831 5832 /** 5833 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5834 * will forward the intent to the filter's target user. 5835 * Otherwise, returns null. 5836 */ 5837 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5838 String resolvedType, int flags, int sourceUserId) { 5839 int targetUserId = filter.getTargetUserId(); 5840 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5841 resolvedType, flags, targetUserId); 5842 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5843 // If all the matches in the target profile are suspended, return null. 5844 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5845 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5846 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5847 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5848 targetUserId); 5849 } 5850 } 5851 } 5852 return null; 5853 } 5854 5855 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5856 int sourceUserId, int targetUserId) { 5857 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5858 long ident = Binder.clearCallingIdentity(); 5859 boolean targetIsProfile; 5860 try { 5861 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5862 } finally { 5863 Binder.restoreCallingIdentity(ident); 5864 } 5865 String className; 5866 if (targetIsProfile) { 5867 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5868 } else { 5869 className = FORWARD_INTENT_TO_PARENT; 5870 } 5871 ComponentName forwardingActivityComponentName = new ComponentName( 5872 mAndroidApplication.packageName, className); 5873 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5874 sourceUserId); 5875 if (!targetIsProfile) { 5876 forwardingActivityInfo.showUserIcon = targetUserId; 5877 forwardingResolveInfo.noResourceId = true; 5878 } 5879 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5880 forwardingResolveInfo.priority = 0; 5881 forwardingResolveInfo.preferredOrder = 0; 5882 forwardingResolveInfo.match = 0; 5883 forwardingResolveInfo.isDefault = true; 5884 forwardingResolveInfo.filter = filter; 5885 forwardingResolveInfo.targetUserId = targetUserId; 5886 return forwardingResolveInfo; 5887 } 5888 5889 @Override 5890 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5891 Intent[] specifics, String[] specificTypes, Intent intent, 5892 String resolvedType, int flags, int userId) { 5893 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5894 specificTypes, intent, resolvedType, flags, userId)); 5895 } 5896 5897 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5898 Intent[] specifics, String[] specificTypes, Intent intent, 5899 String resolvedType, int flags, int userId) { 5900 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5901 flags = updateFlagsForResolve(flags, userId, intent); 5902 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5903 false /* requireFullPermission */, false /* checkShell */, 5904 "query intent activity options"); 5905 final String resultsAction = intent.getAction(); 5906 5907 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5908 | PackageManager.GET_RESOLVED_FILTER, userId); 5909 5910 if (DEBUG_INTENT_MATCHING) { 5911 Log.v(TAG, "Query " + intent + ": " + results); 5912 } 5913 5914 int specificsPos = 0; 5915 int N; 5916 5917 // todo: note that the algorithm used here is O(N^2). This 5918 // isn't a problem in our current environment, but if we start running 5919 // into situations where we have more than 5 or 10 matches then this 5920 // should probably be changed to something smarter... 5921 5922 // First we go through and resolve each of the specific items 5923 // that were supplied, taking care of removing any corresponding 5924 // duplicate items in the generic resolve list. 5925 if (specifics != null) { 5926 for (int i=0; i<specifics.length; i++) { 5927 final Intent sintent = specifics[i]; 5928 if (sintent == null) { 5929 continue; 5930 } 5931 5932 if (DEBUG_INTENT_MATCHING) { 5933 Log.v(TAG, "Specific #" + i + ": " + sintent); 5934 } 5935 5936 String action = sintent.getAction(); 5937 if (resultsAction != null && resultsAction.equals(action)) { 5938 // If this action was explicitly requested, then don't 5939 // remove things that have it. 5940 action = null; 5941 } 5942 5943 ResolveInfo ri = null; 5944 ActivityInfo ai = null; 5945 5946 ComponentName comp = sintent.getComponent(); 5947 if (comp == null) { 5948 ri = resolveIntent( 5949 sintent, 5950 specificTypes != null ? specificTypes[i] : null, 5951 flags, userId); 5952 if (ri == null) { 5953 continue; 5954 } 5955 if (ri == mResolveInfo) { 5956 // ACK! Must do something better with this. 5957 } 5958 ai = ri.activityInfo; 5959 comp = new ComponentName(ai.applicationInfo.packageName, 5960 ai.name); 5961 } else { 5962 ai = getActivityInfo(comp, flags, userId); 5963 if (ai == null) { 5964 continue; 5965 } 5966 } 5967 5968 // Look for any generic query activities that are duplicates 5969 // of this specific one, and remove them from the results. 5970 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5971 N = results.size(); 5972 int j; 5973 for (j=specificsPos; j<N; j++) { 5974 ResolveInfo sri = results.get(j); 5975 if ((sri.activityInfo.name.equals(comp.getClassName()) 5976 && sri.activityInfo.applicationInfo.packageName.equals( 5977 comp.getPackageName())) 5978 || (action != null && sri.filter.matchAction(action))) { 5979 results.remove(j); 5980 if (DEBUG_INTENT_MATCHING) Log.v( 5981 TAG, "Removing duplicate item from " + j 5982 + " due to specific " + specificsPos); 5983 if (ri == null) { 5984 ri = sri; 5985 } 5986 j--; 5987 N--; 5988 } 5989 } 5990 5991 // Add this specific item to its proper place. 5992 if (ri == null) { 5993 ri = new ResolveInfo(); 5994 ri.activityInfo = ai; 5995 } 5996 results.add(specificsPos, ri); 5997 ri.specificIndex = i; 5998 specificsPos++; 5999 } 6000 } 6001 6002 // Now we go through the remaining generic results and remove any 6003 // duplicate actions that are found here. 6004 N = results.size(); 6005 for (int i=specificsPos; i<N-1; i++) { 6006 final ResolveInfo rii = results.get(i); 6007 if (rii.filter == null) { 6008 continue; 6009 } 6010 6011 // Iterate over all of the actions of this result's intent 6012 // filter... typically this should be just one. 6013 final Iterator<String> it = rii.filter.actionsIterator(); 6014 if (it == null) { 6015 continue; 6016 } 6017 while (it.hasNext()) { 6018 final String action = it.next(); 6019 if (resultsAction != null && resultsAction.equals(action)) { 6020 // If this action was explicitly requested, then don't 6021 // remove things that have it. 6022 continue; 6023 } 6024 for (int j=i+1; j<N; j++) { 6025 final ResolveInfo rij = results.get(j); 6026 if (rij.filter != null && rij.filter.hasAction(action)) { 6027 results.remove(j); 6028 if (DEBUG_INTENT_MATCHING) Log.v( 6029 TAG, "Removing duplicate item from " + j 6030 + " due to action " + action + " at " + i); 6031 j--; 6032 N--; 6033 } 6034 } 6035 } 6036 6037 // If the caller didn't request filter information, drop it now 6038 // so we don't have to marshall/unmarshall it. 6039 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6040 rii.filter = null; 6041 } 6042 } 6043 6044 // Filter out the caller activity if so requested. 6045 if (caller != null) { 6046 N = results.size(); 6047 for (int i=0; i<N; i++) { 6048 ActivityInfo ainfo = results.get(i).activityInfo; 6049 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6050 && caller.getClassName().equals(ainfo.name)) { 6051 results.remove(i); 6052 break; 6053 } 6054 } 6055 } 6056 6057 // If the caller didn't request filter information, 6058 // drop them now so we don't have to 6059 // marshall/unmarshall it. 6060 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6061 N = results.size(); 6062 for (int i=0; i<N; i++) { 6063 results.get(i).filter = null; 6064 } 6065 } 6066 6067 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6068 return results; 6069 } 6070 6071 @Override 6072 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6073 String resolvedType, int flags, int userId) { 6074 return new ParceledListSlice<>( 6075 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6076 } 6077 6078 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6079 String resolvedType, int flags, int userId) { 6080 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6081 flags = updateFlagsForResolve(flags, userId, intent); 6082 ComponentName comp = intent.getComponent(); 6083 if (comp == null) { 6084 if (intent.getSelector() != null) { 6085 intent = intent.getSelector(); 6086 comp = intent.getComponent(); 6087 } 6088 } 6089 if (comp != null) { 6090 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6091 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6092 if (ai != null) { 6093 ResolveInfo ri = new ResolveInfo(); 6094 ri.activityInfo = ai; 6095 list.add(ri); 6096 } 6097 return list; 6098 } 6099 6100 // reader 6101 synchronized (mPackages) { 6102 String pkgName = intent.getPackage(); 6103 if (pkgName == null) { 6104 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6105 } 6106 final PackageParser.Package pkg = mPackages.get(pkgName); 6107 if (pkg != null) { 6108 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6109 userId); 6110 } 6111 return Collections.emptyList(); 6112 } 6113 } 6114 6115 @Override 6116 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6117 if (!sUserManager.exists(userId)) return null; 6118 flags = updateFlagsForResolve(flags, userId, intent); 6119 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6120 if (query != null) { 6121 if (query.size() >= 1) { 6122 // If there is more than one service with the same priority, 6123 // just arbitrarily pick the first one. 6124 return query.get(0); 6125 } 6126 } 6127 return null; 6128 } 6129 6130 @Override 6131 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6132 String resolvedType, int flags, int userId) { 6133 return new ParceledListSlice<>( 6134 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6135 } 6136 6137 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6138 String resolvedType, int flags, int userId) { 6139 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6140 flags = updateFlagsForResolve(flags, userId, intent); 6141 ComponentName comp = intent.getComponent(); 6142 if (comp == null) { 6143 if (intent.getSelector() != null) { 6144 intent = intent.getSelector(); 6145 comp = intent.getComponent(); 6146 } 6147 } 6148 if (comp != null) { 6149 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6150 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6151 if (si != null) { 6152 final ResolveInfo ri = new ResolveInfo(); 6153 ri.serviceInfo = si; 6154 list.add(ri); 6155 } 6156 return list; 6157 } 6158 6159 // reader 6160 synchronized (mPackages) { 6161 String pkgName = intent.getPackage(); 6162 if (pkgName == null) { 6163 return mServices.queryIntent(intent, resolvedType, flags, userId); 6164 } 6165 final PackageParser.Package pkg = mPackages.get(pkgName); 6166 if (pkg != null) { 6167 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6168 userId); 6169 } 6170 return Collections.emptyList(); 6171 } 6172 } 6173 6174 @Override 6175 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6176 String resolvedType, int flags, int userId) { 6177 return new ParceledListSlice<>( 6178 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6179 } 6180 6181 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6182 Intent intent, String resolvedType, int flags, int userId) { 6183 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6184 flags = updateFlagsForResolve(flags, userId, intent); 6185 ComponentName comp = intent.getComponent(); 6186 if (comp == null) { 6187 if (intent.getSelector() != null) { 6188 intent = intent.getSelector(); 6189 comp = intent.getComponent(); 6190 } 6191 } 6192 if (comp != null) { 6193 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6194 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6195 if (pi != null) { 6196 final ResolveInfo ri = new ResolveInfo(); 6197 ri.providerInfo = pi; 6198 list.add(ri); 6199 } 6200 return list; 6201 } 6202 6203 // reader 6204 synchronized (mPackages) { 6205 String pkgName = intent.getPackage(); 6206 if (pkgName == null) { 6207 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6208 } 6209 final PackageParser.Package pkg = mPackages.get(pkgName); 6210 if (pkg != null) { 6211 return mProviders.queryIntentForPackage( 6212 intent, resolvedType, flags, pkg.providers, userId); 6213 } 6214 return Collections.emptyList(); 6215 } 6216 } 6217 6218 @Override 6219 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6220 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6221 flags = updateFlagsForPackage(flags, userId, null); 6222 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6224 true /* requireFullPermission */, false /* checkShell */, 6225 "get installed packages"); 6226 6227 // writer 6228 synchronized (mPackages) { 6229 ArrayList<PackageInfo> list; 6230 if (listUninstalled) { 6231 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6232 for (PackageSetting ps : mSettings.mPackages.values()) { 6233 final PackageInfo pi; 6234 if (ps.pkg != null) { 6235 pi = generatePackageInfo(ps, flags, userId); 6236 } else { 6237 pi = generatePackageInfo(ps, flags, userId); 6238 } 6239 if (pi != null) { 6240 list.add(pi); 6241 } 6242 } 6243 } else { 6244 list = new ArrayList<PackageInfo>(mPackages.size()); 6245 for (PackageParser.Package p : mPackages.values()) { 6246 final PackageInfo pi = 6247 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6248 if (pi != null) { 6249 list.add(pi); 6250 } 6251 } 6252 } 6253 6254 return new ParceledListSlice<PackageInfo>(list); 6255 } 6256 } 6257 6258 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6259 String[] permissions, boolean[] tmp, int flags, int userId) { 6260 int numMatch = 0; 6261 final PermissionsState permissionsState = ps.getPermissionsState(); 6262 for (int i=0; i<permissions.length; i++) { 6263 final String permission = permissions[i]; 6264 if (permissionsState.hasPermission(permission, userId)) { 6265 tmp[i] = true; 6266 numMatch++; 6267 } else { 6268 tmp[i] = false; 6269 } 6270 } 6271 if (numMatch == 0) { 6272 return; 6273 } 6274 final PackageInfo pi; 6275 if (ps.pkg != null) { 6276 pi = generatePackageInfo(ps, flags, userId); 6277 } else { 6278 pi = generatePackageInfo(ps, flags, userId); 6279 } 6280 // The above might return null in cases of uninstalled apps or install-state 6281 // skew across users/profiles. 6282 if (pi != null) { 6283 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6284 if (numMatch == permissions.length) { 6285 pi.requestedPermissions = permissions; 6286 } else { 6287 pi.requestedPermissions = new String[numMatch]; 6288 numMatch = 0; 6289 for (int i=0; i<permissions.length; i++) { 6290 if (tmp[i]) { 6291 pi.requestedPermissions[numMatch] = permissions[i]; 6292 numMatch++; 6293 } 6294 } 6295 } 6296 } 6297 list.add(pi); 6298 } 6299 } 6300 6301 @Override 6302 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6303 String[] permissions, int flags, int userId) { 6304 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6305 flags = updateFlagsForPackage(flags, userId, permissions); 6306 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6307 6308 // writer 6309 synchronized (mPackages) { 6310 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6311 boolean[] tmpBools = new boolean[permissions.length]; 6312 if (listUninstalled) { 6313 for (PackageSetting ps : mSettings.mPackages.values()) { 6314 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6315 } 6316 } else { 6317 for (PackageParser.Package pkg : mPackages.values()) { 6318 PackageSetting ps = (PackageSetting)pkg.mExtras; 6319 if (ps != null) { 6320 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6321 userId); 6322 } 6323 } 6324 } 6325 6326 return new ParceledListSlice<PackageInfo>(list); 6327 } 6328 } 6329 6330 @Override 6331 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6332 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6333 flags = updateFlagsForApplication(flags, userId, null); 6334 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6335 6336 // writer 6337 synchronized (mPackages) { 6338 ArrayList<ApplicationInfo> list; 6339 if (listUninstalled) { 6340 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6341 for (PackageSetting ps : mSettings.mPackages.values()) { 6342 ApplicationInfo ai; 6343 if (ps.pkg != null) { 6344 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6345 ps.readUserState(userId), userId); 6346 } else { 6347 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6348 } 6349 if (ai != null) { 6350 list.add(ai); 6351 } 6352 } 6353 } else { 6354 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6355 for (PackageParser.Package p : mPackages.values()) { 6356 if (p.mExtras != null) { 6357 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6358 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6359 if (ai != null) { 6360 list.add(ai); 6361 } 6362 } 6363 } 6364 } 6365 6366 return new ParceledListSlice<ApplicationInfo>(list); 6367 } 6368 } 6369 6370 @Override 6371 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6372 if (DISABLE_EPHEMERAL_APPS) { 6373 return null; 6374 } 6375 6376 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6377 "getEphemeralApplications"); 6378 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6379 true /* requireFullPermission */, false /* checkShell */, 6380 "getEphemeralApplications"); 6381 synchronized (mPackages) { 6382 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6383 .getEphemeralApplicationsLPw(userId); 6384 if (ephemeralApps != null) { 6385 return new ParceledListSlice<>(ephemeralApps); 6386 } 6387 } 6388 return null; 6389 } 6390 6391 @Override 6392 public boolean isEphemeralApplication(String packageName, int userId) { 6393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6394 true /* requireFullPermission */, false /* checkShell */, 6395 "isEphemeral"); 6396 if (DISABLE_EPHEMERAL_APPS) { 6397 return false; 6398 } 6399 6400 if (!isCallerSameApp(packageName)) { 6401 return false; 6402 } 6403 synchronized (mPackages) { 6404 PackageParser.Package pkg = mPackages.get(packageName); 6405 if (pkg != null) { 6406 return pkg.applicationInfo.isEphemeralApp(); 6407 } 6408 } 6409 return false; 6410 } 6411 6412 @Override 6413 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6414 if (DISABLE_EPHEMERAL_APPS) { 6415 return null; 6416 } 6417 6418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6419 true /* requireFullPermission */, false /* checkShell */, 6420 "getCookie"); 6421 if (!isCallerSameApp(packageName)) { 6422 return null; 6423 } 6424 synchronized (mPackages) { 6425 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6426 packageName, userId); 6427 } 6428 } 6429 6430 @Override 6431 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6432 if (DISABLE_EPHEMERAL_APPS) { 6433 return true; 6434 } 6435 6436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6437 true /* requireFullPermission */, true /* checkShell */, 6438 "setCookie"); 6439 if (!isCallerSameApp(packageName)) { 6440 return false; 6441 } 6442 synchronized (mPackages) { 6443 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6444 packageName, cookie, userId); 6445 } 6446 } 6447 6448 @Override 6449 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6450 if (DISABLE_EPHEMERAL_APPS) { 6451 return null; 6452 } 6453 6454 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6455 "getEphemeralApplicationIcon"); 6456 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6457 true /* requireFullPermission */, false /* checkShell */, 6458 "getEphemeralApplicationIcon"); 6459 synchronized (mPackages) { 6460 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6461 packageName, userId); 6462 } 6463 } 6464 6465 private boolean isCallerSameApp(String packageName) { 6466 PackageParser.Package pkg = mPackages.get(packageName); 6467 return pkg != null 6468 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6469 } 6470 6471 @Override 6472 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6473 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6474 } 6475 6476 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6477 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6478 6479 // reader 6480 synchronized (mPackages) { 6481 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6482 final int userId = UserHandle.getCallingUserId(); 6483 while (i.hasNext()) { 6484 final PackageParser.Package p = i.next(); 6485 if (p.applicationInfo == null) continue; 6486 6487 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6488 && !p.applicationInfo.isDirectBootAware(); 6489 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6490 && p.applicationInfo.isDirectBootAware(); 6491 6492 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6493 && (!mSafeMode || isSystemApp(p)) 6494 && (matchesUnaware || matchesAware)) { 6495 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6496 if (ps != null) { 6497 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6498 ps.readUserState(userId), userId); 6499 if (ai != null) { 6500 finalList.add(ai); 6501 } 6502 } 6503 } 6504 } 6505 } 6506 6507 return finalList; 6508 } 6509 6510 @Override 6511 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6512 if (!sUserManager.exists(userId)) return null; 6513 flags = updateFlagsForComponent(flags, userId, name); 6514 // reader 6515 synchronized (mPackages) { 6516 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6517 PackageSetting ps = provider != null 6518 ? mSettings.mPackages.get(provider.owner.packageName) 6519 : null; 6520 return ps != null 6521 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6522 ? PackageParser.generateProviderInfo(provider, flags, 6523 ps.readUserState(userId), userId) 6524 : null; 6525 } 6526 } 6527 6528 /** 6529 * @deprecated 6530 */ 6531 @Deprecated 6532 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6533 // reader 6534 synchronized (mPackages) { 6535 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6536 .entrySet().iterator(); 6537 final int userId = UserHandle.getCallingUserId(); 6538 while (i.hasNext()) { 6539 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6540 PackageParser.Provider p = entry.getValue(); 6541 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6542 6543 if (ps != null && p.syncable 6544 && (!mSafeMode || (p.info.applicationInfo.flags 6545 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6546 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6547 ps.readUserState(userId), userId); 6548 if (info != null) { 6549 outNames.add(entry.getKey()); 6550 outInfo.add(info); 6551 } 6552 } 6553 } 6554 } 6555 } 6556 6557 @Override 6558 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6559 int uid, int flags) { 6560 final int userId = processName != null ? UserHandle.getUserId(uid) 6561 : UserHandle.getCallingUserId(); 6562 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6563 flags = updateFlagsForComponent(flags, userId, processName); 6564 6565 ArrayList<ProviderInfo> finalList = null; 6566 // reader 6567 synchronized (mPackages) { 6568 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6569 while (i.hasNext()) { 6570 final PackageParser.Provider p = i.next(); 6571 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6572 if (ps != null && p.info.authority != null 6573 && (processName == null 6574 || (p.info.processName.equals(processName) 6575 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6576 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6577 if (finalList == null) { 6578 finalList = new ArrayList<ProviderInfo>(3); 6579 } 6580 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6581 ps.readUserState(userId), userId); 6582 if (info != null) { 6583 finalList.add(info); 6584 } 6585 } 6586 } 6587 } 6588 6589 if (finalList != null) { 6590 Collections.sort(finalList, mProviderInitOrderSorter); 6591 return new ParceledListSlice<ProviderInfo>(finalList); 6592 } 6593 6594 return ParceledListSlice.emptyList(); 6595 } 6596 6597 @Override 6598 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6599 // reader 6600 synchronized (mPackages) { 6601 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6602 return PackageParser.generateInstrumentationInfo(i, flags); 6603 } 6604 } 6605 6606 @Override 6607 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6608 String targetPackage, int flags) { 6609 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6610 } 6611 6612 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6613 int flags) { 6614 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6615 6616 // reader 6617 synchronized (mPackages) { 6618 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6619 while (i.hasNext()) { 6620 final PackageParser.Instrumentation p = i.next(); 6621 if (targetPackage == null 6622 || targetPackage.equals(p.info.targetPackage)) { 6623 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6624 flags); 6625 if (ii != null) { 6626 finalList.add(ii); 6627 } 6628 } 6629 } 6630 } 6631 6632 return finalList; 6633 } 6634 6635 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6636 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6637 if (overlays == null) { 6638 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6639 return; 6640 } 6641 for (PackageParser.Package opkg : overlays.values()) { 6642 // Not much to do if idmap fails: we already logged the error 6643 // and we certainly don't want to abort installation of pkg simply 6644 // because an overlay didn't fit properly. For these reasons, 6645 // ignore the return value of createIdmapForPackagePairLI. 6646 createIdmapForPackagePairLI(pkg, opkg); 6647 } 6648 } 6649 6650 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6651 PackageParser.Package opkg) { 6652 if (!opkg.mTrustedOverlay) { 6653 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6654 opkg.baseCodePath + ": overlay not trusted"); 6655 return false; 6656 } 6657 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6658 if (overlaySet == null) { 6659 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6660 opkg.baseCodePath + " but target package has no known overlays"); 6661 return false; 6662 } 6663 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6664 // TODO: generate idmap for split APKs 6665 try { 6666 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6667 } catch (InstallerException e) { 6668 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6669 + opkg.baseCodePath); 6670 return false; 6671 } 6672 PackageParser.Package[] overlayArray = 6673 overlaySet.values().toArray(new PackageParser.Package[0]); 6674 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6675 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6676 return p1.mOverlayPriority - p2.mOverlayPriority; 6677 } 6678 }; 6679 Arrays.sort(overlayArray, cmp); 6680 6681 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6682 int i = 0; 6683 for (PackageParser.Package p : overlayArray) { 6684 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6685 } 6686 return true; 6687 } 6688 6689 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6690 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6691 try { 6692 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6693 } finally { 6694 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6695 } 6696 } 6697 6698 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6699 final File[] files = dir.listFiles(); 6700 if (ArrayUtils.isEmpty(files)) { 6701 Log.d(TAG, "No files in app dir " + dir); 6702 return; 6703 } 6704 6705 if (DEBUG_PACKAGE_SCANNING) { 6706 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6707 + " flags=0x" + Integer.toHexString(parseFlags)); 6708 } 6709 6710 for (File file : files) { 6711 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6712 && !PackageInstallerService.isStageName(file.getName()); 6713 if (!isPackage) { 6714 // Ignore entries which are not packages 6715 continue; 6716 } 6717 try { 6718 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6719 scanFlags, currentTime, null); 6720 } catch (PackageManagerException e) { 6721 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6722 6723 // Delete invalid userdata apps 6724 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6725 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6726 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6727 removeCodePathLI(file); 6728 } 6729 } 6730 } 6731 } 6732 6733 private static File getSettingsProblemFile() { 6734 File dataDir = Environment.getDataDirectory(); 6735 File systemDir = new File(dataDir, "system"); 6736 File fname = new File(systemDir, "uiderrors.txt"); 6737 return fname; 6738 } 6739 6740 static void reportSettingsProblem(int priority, String msg) { 6741 logCriticalInfo(priority, msg); 6742 } 6743 6744 static void logCriticalInfo(int priority, String msg) { 6745 Slog.println(priority, TAG, msg); 6746 EventLogTags.writePmCriticalInfo(msg); 6747 try { 6748 File fname = getSettingsProblemFile(); 6749 FileOutputStream out = new FileOutputStream(fname, true); 6750 PrintWriter pw = new FastPrintWriter(out); 6751 SimpleDateFormat formatter = new SimpleDateFormat(); 6752 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6753 pw.println(dateString + ": " + msg); 6754 pw.close(); 6755 FileUtils.setPermissions( 6756 fname.toString(), 6757 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6758 -1, -1); 6759 } catch (java.io.IOException e) { 6760 } 6761 } 6762 6763 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6764 final int policyFlags) throws PackageManagerException { 6765 if (ps != null 6766 && ps.codePath.equals(srcFile) 6767 && ps.timeStamp == srcFile.lastModified() 6768 && !isCompatSignatureUpdateNeeded(pkg) 6769 && !isRecoverSignatureUpdateNeeded(pkg)) { 6770 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6771 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6772 ArraySet<PublicKey> signingKs; 6773 synchronized (mPackages) { 6774 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6775 } 6776 if (ps.signatures.mSignatures != null 6777 && ps.signatures.mSignatures.length != 0 6778 && signingKs != null) { 6779 // Optimization: reuse the existing cached certificates 6780 // if the package appears to be unchanged. 6781 pkg.mSignatures = ps.signatures.mSignatures; 6782 pkg.mSigningKeys = signingKs; 6783 return; 6784 } 6785 6786 Slog.w(TAG, "PackageSetting for " + ps.name 6787 + " is missing signatures. Collecting certs again to recover them."); 6788 } else { 6789 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6790 } 6791 6792 try { 6793 PackageParser.collectCertificates(pkg, policyFlags); 6794 } catch (PackageParserException e) { 6795 throw PackageManagerException.from(e); 6796 } 6797 } 6798 6799 /** 6800 * Traces a package scan. 6801 * @see #scanPackageLI(File, int, int, long, UserHandle) 6802 */ 6803 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6804 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6806 try { 6807 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6808 } finally { 6809 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6810 } 6811 } 6812 6813 /** 6814 * Scans a package and returns the newly parsed package. 6815 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6816 */ 6817 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6818 long currentTime, UserHandle user) throws PackageManagerException { 6819 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6820 PackageParser pp = new PackageParser(); 6821 pp.setSeparateProcesses(mSeparateProcesses); 6822 pp.setOnlyCoreApps(mOnlyCore); 6823 pp.setDisplayMetrics(mMetrics); 6824 6825 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6826 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6827 } 6828 6829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6830 final PackageParser.Package pkg; 6831 try { 6832 pkg = pp.parsePackage(scanFile, parseFlags); 6833 } catch (PackageParserException e) { 6834 throw PackageManagerException.from(e); 6835 } finally { 6836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6837 } 6838 6839 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6840 } 6841 6842 /** 6843 * Scans a package and returns the newly parsed package. 6844 * @throws PackageManagerException on a parse error. 6845 */ 6846 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6847 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6848 throws PackageManagerException { 6849 // If the package has children and this is the first dive in the function 6850 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6851 // packages (parent and children) would be successfully scanned before the 6852 // actual scan since scanning mutates internal state and we want to atomically 6853 // install the package and its children. 6854 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6855 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6856 scanFlags |= SCAN_CHECK_ONLY; 6857 } 6858 } else { 6859 scanFlags &= ~SCAN_CHECK_ONLY; 6860 } 6861 6862 // Scan the parent 6863 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6864 scanFlags, currentTime, user); 6865 6866 // Scan the children 6867 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6868 for (int i = 0; i < childCount; i++) { 6869 PackageParser.Package childPackage = pkg.childPackages.get(i); 6870 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6871 currentTime, user); 6872 } 6873 6874 6875 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6876 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6877 } 6878 6879 return scannedPkg; 6880 } 6881 6882 /** 6883 * Scans a package and returns the newly parsed package. 6884 * @throws PackageManagerException on a parse error. 6885 */ 6886 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6887 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6888 throws PackageManagerException { 6889 PackageSetting ps = null; 6890 PackageSetting updatedPkg; 6891 // reader 6892 synchronized (mPackages) { 6893 // Look to see if we already know about this package. 6894 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6895 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6896 // This package has been renamed to its original name. Let's 6897 // use that. 6898 ps = mSettings.peekPackageLPr(oldName); 6899 } 6900 // If there was no original package, see one for the real package name. 6901 if (ps == null) { 6902 ps = mSettings.peekPackageLPr(pkg.packageName); 6903 } 6904 // Check to see if this package could be hiding/updating a system 6905 // package. Must look for it either under the original or real 6906 // package name depending on our state. 6907 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6908 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6909 6910 // If this is a package we don't know about on the system partition, we 6911 // may need to remove disabled child packages on the system partition 6912 // or may need to not add child packages if the parent apk is updated 6913 // on the data partition and no longer defines this child package. 6914 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6915 // If this is a parent package for an updated system app and this system 6916 // app got an OTA update which no longer defines some of the child packages 6917 // we have to prune them from the disabled system packages. 6918 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6919 if (disabledPs != null) { 6920 final int scannedChildCount = (pkg.childPackages != null) 6921 ? pkg.childPackages.size() : 0; 6922 final int disabledChildCount = disabledPs.childPackageNames != null 6923 ? disabledPs.childPackageNames.size() : 0; 6924 for (int i = 0; i < disabledChildCount; i++) { 6925 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6926 boolean disabledPackageAvailable = false; 6927 for (int j = 0; j < scannedChildCount; j++) { 6928 PackageParser.Package childPkg = pkg.childPackages.get(j); 6929 if (childPkg.packageName.equals(disabledChildPackageName)) { 6930 disabledPackageAvailable = true; 6931 break; 6932 } 6933 } 6934 if (!disabledPackageAvailable) { 6935 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6936 } 6937 } 6938 } 6939 } 6940 } 6941 6942 boolean updatedPkgBetter = false; 6943 // First check if this is a system package that may involve an update 6944 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6945 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6946 // it needs to drop FLAG_PRIVILEGED. 6947 if (locationIsPrivileged(scanFile)) { 6948 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6949 } else { 6950 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6951 } 6952 6953 if (ps != null && !ps.codePath.equals(scanFile)) { 6954 // The path has changed from what was last scanned... check the 6955 // version of the new path against what we have stored to determine 6956 // what to do. 6957 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6958 if (pkg.mVersionCode <= ps.versionCode) { 6959 // The system package has been updated and the code path does not match 6960 // Ignore entry. Skip it. 6961 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6962 + " ignored: updated version " + ps.versionCode 6963 + " better than this " + pkg.mVersionCode); 6964 if (!updatedPkg.codePath.equals(scanFile)) { 6965 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6966 + ps.name + " changing from " + updatedPkg.codePathString 6967 + " to " + scanFile); 6968 updatedPkg.codePath = scanFile; 6969 updatedPkg.codePathString = scanFile.toString(); 6970 updatedPkg.resourcePath = scanFile; 6971 updatedPkg.resourcePathString = scanFile.toString(); 6972 } 6973 updatedPkg.pkg = pkg; 6974 updatedPkg.versionCode = pkg.mVersionCode; 6975 6976 // Update the disabled system child packages to point to the package too. 6977 final int childCount = updatedPkg.childPackageNames != null 6978 ? updatedPkg.childPackageNames.size() : 0; 6979 for (int i = 0; i < childCount; i++) { 6980 String childPackageName = updatedPkg.childPackageNames.get(i); 6981 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6982 childPackageName); 6983 if (updatedChildPkg != null) { 6984 updatedChildPkg.pkg = pkg; 6985 updatedChildPkg.versionCode = pkg.mVersionCode; 6986 } 6987 } 6988 6989 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6990 + scanFile + " ignored: updated version " + ps.versionCode 6991 + " better than this " + pkg.mVersionCode); 6992 } else { 6993 // The current app on the system partition is better than 6994 // what we have updated to on the data partition; switch 6995 // back to the system partition version. 6996 // At this point, its safely assumed that package installation for 6997 // apps in system partition will go through. If not there won't be a working 6998 // version of the app 6999 // writer 7000 synchronized (mPackages) { 7001 // Just remove the loaded entries from package lists. 7002 mPackages.remove(ps.name); 7003 } 7004 7005 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7006 + " reverting from " + ps.codePathString 7007 + ": new version " + pkg.mVersionCode 7008 + " better than installed " + ps.versionCode); 7009 7010 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7011 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7012 synchronized (mInstallLock) { 7013 args.cleanUpResourcesLI(); 7014 } 7015 synchronized (mPackages) { 7016 mSettings.enableSystemPackageLPw(ps.name); 7017 } 7018 updatedPkgBetter = true; 7019 } 7020 } 7021 } 7022 7023 if (updatedPkg != null) { 7024 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7025 // initially 7026 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7027 7028 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7029 // flag set initially 7030 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7031 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7032 } 7033 } 7034 7035 // Verify certificates against what was last scanned 7036 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7037 7038 /* 7039 * A new system app appeared, but we already had a non-system one of the 7040 * same name installed earlier. 7041 */ 7042 boolean shouldHideSystemApp = false; 7043 if (updatedPkg == null && ps != null 7044 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7045 /* 7046 * Check to make sure the signatures match first. If they don't, 7047 * wipe the installed application and its data. 7048 */ 7049 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7050 != PackageManager.SIGNATURE_MATCH) { 7051 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7052 + " signatures don't match existing userdata copy; removing"); 7053 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7054 "scanPackageInternalLI")) { 7055 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7056 } 7057 ps = null; 7058 } else { 7059 /* 7060 * If the newly-added system app is an older version than the 7061 * already installed version, hide it. It will be scanned later 7062 * and re-added like an update. 7063 */ 7064 if (pkg.mVersionCode <= ps.versionCode) { 7065 shouldHideSystemApp = true; 7066 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7067 + " but new version " + pkg.mVersionCode + " better than installed " 7068 + ps.versionCode + "; hiding system"); 7069 } else { 7070 /* 7071 * The newly found system app is a newer version that the 7072 * one previously installed. Simply remove the 7073 * already-installed application and replace it with our own 7074 * while keeping the application data. 7075 */ 7076 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7077 + " reverting from " + ps.codePathString + ": new version " 7078 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7079 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7080 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7081 synchronized (mInstallLock) { 7082 args.cleanUpResourcesLI(); 7083 } 7084 } 7085 } 7086 } 7087 7088 // The apk is forward locked (not public) if its code and resources 7089 // are kept in different files. (except for app in either system or 7090 // vendor path). 7091 // TODO grab this value from PackageSettings 7092 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7093 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7094 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7095 } 7096 } 7097 7098 // TODO: extend to support forward-locked splits 7099 String resourcePath = null; 7100 String baseResourcePath = null; 7101 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7102 if (ps != null && ps.resourcePathString != null) { 7103 resourcePath = ps.resourcePathString; 7104 baseResourcePath = ps.resourcePathString; 7105 } else { 7106 // Should not happen at all. Just log an error. 7107 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7108 } 7109 } else { 7110 resourcePath = pkg.codePath; 7111 baseResourcePath = pkg.baseCodePath; 7112 } 7113 7114 // Set application objects path explicitly. 7115 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7116 pkg.setApplicationInfoCodePath(pkg.codePath); 7117 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7118 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7119 pkg.setApplicationInfoResourcePath(resourcePath); 7120 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7121 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7122 7123 // Note that we invoke the following method only if we are about to unpack an application 7124 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7125 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7126 7127 /* 7128 * If the system app should be overridden by a previously installed 7129 * data, hide the system app now and let the /data/app scan pick it up 7130 * again. 7131 */ 7132 if (shouldHideSystemApp) { 7133 synchronized (mPackages) { 7134 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7135 } 7136 } 7137 7138 return scannedPkg; 7139 } 7140 7141 private static String fixProcessName(String defProcessName, 7142 String processName, int uid) { 7143 if (processName == null) { 7144 return defProcessName; 7145 } 7146 return processName; 7147 } 7148 7149 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7150 throws PackageManagerException { 7151 if (pkgSetting.signatures.mSignatures != null) { 7152 // Already existing package. Make sure signatures match 7153 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7154 == PackageManager.SIGNATURE_MATCH; 7155 if (!match) { 7156 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7157 == PackageManager.SIGNATURE_MATCH; 7158 } 7159 if (!match) { 7160 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7161 == PackageManager.SIGNATURE_MATCH; 7162 } 7163 if (!match) { 7164 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7165 + pkg.packageName + " signatures do not match the " 7166 + "previously installed version; ignoring!"); 7167 } 7168 } 7169 7170 // Check for shared user signatures 7171 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7172 // Already existing package. Make sure signatures match 7173 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7174 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7175 if (!match) { 7176 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7177 == PackageManager.SIGNATURE_MATCH; 7178 } 7179 if (!match) { 7180 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7181 == PackageManager.SIGNATURE_MATCH; 7182 } 7183 if (!match) { 7184 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7185 "Package " + pkg.packageName 7186 + " has no signatures that match those in shared user " 7187 + pkgSetting.sharedUser.name + "; ignoring!"); 7188 } 7189 } 7190 } 7191 7192 /** 7193 * Enforces that only the system UID or root's UID can call a method exposed 7194 * via Binder. 7195 * 7196 * @param message used as message if SecurityException is thrown 7197 * @throws SecurityException if the caller is not system or root 7198 */ 7199 private static final void enforceSystemOrRoot(String message) { 7200 final int uid = Binder.getCallingUid(); 7201 if (uid != Process.SYSTEM_UID && uid != 0) { 7202 throw new SecurityException(message); 7203 } 7204 } 7205 7206 @Override 7207 public void performFstrimIfNeeded() { 7208 enforceSystemOrRoot("Only the system can request fstrim"); 7209 7210 // Before everything else, see whether we need to fstrim. 7211 try { 7212 IMountService ms = PackageHelper.getMountService(); 7213 if (ms != null) { 7214 final boolean isUpgrade = isUpgrade(); 7215 boolean doTrim = isUpgrade; 7216 if (doTrim) { 7217 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7218 } else { 7219 final long interval = android.provider.Settings.Global.getLong( 7220 mContext.getContentResolver(), 7221 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7222 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7223 if (interval > 0) { 7224 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7225 if (timeSinceLast > interval) { 7226 doTrim = true; 7227 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7228 + "; running immediately"); 7229 } 7230 } 7231 } 7232 if (doTrim) { 7233 if (!isFirstBoot()) { 7234 try { 7235 ActivityManagerNative.getDefault().showBootMessage( 7236 mContext.getResources().getString( 7237 R.string.android_upgrading_fstrim), true); 7238 } catch (RemoteException e) { 7239 } 7240 } 7241 ms.runMaintenance(); 7242 } 7243 } else { 7244 Slog.e(TAG, "Mount service unavailable!"); 7245 } 7246 } catch (RemoteException e) { 7247 // Can't happen; MountService is local 7248 } 7249 } 7250 7251 @Override 7252 public void updatePackagesIfNeeded() { 7253 enforceSystemOrRoot("Only the system can request package update"); 7254 7255 // We need to re-extract after an OTA. 7256 boolean causeUpgrade = isUpgrade(); 7257 7258 // First boot or factory reset. 7259 // Note: we also handle devices that are upgrading to N right now as if it is their 7260 // first boot, as they do not have profile data. 7261 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7262 7263 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7264 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7265 7266 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7267 return; 7268 } 7269 7270 List<PackageParser.Package> pkgs; 7271 synchronized (mPackages) { 7272 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7273 } 7274 7275 final long startTime = System.nanoTime(); 7276 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7277 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7278 7279 final int elapsedTimeSeconds = 7280 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7281 7282 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7283 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7284 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7285 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7286 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7287 } 7288 7289 /** 7290 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7291 * containing statistics about the invocation. The array consists of three elements, 7292 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7293 * and {@code numberOfPackagesFailed}. 7294 */ 7295 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7296 String compilerFilter) { 7297 7298 int numberOfPackagesVisited = 0; 7299 int numberOfPackagesOptimized = 0; 7300 int numberOfPackagesSkipped = 0; 7301 int numberOfPackagesFailed = 0; 7302 final int numberOfPackagesToDexopt = pkgs.size(); 7303 7304 for (PackageParser.Package pkg : pkgs) { 7305 numberOfPackagesVisited++; 7306 7307 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7308 if (DEBUG_DEXOPT) { 7309 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7310 } 7311 numberOfPackagesSkipped++; 7312 continue; 7313 } 7314 7315 if (DEBUG_DEXOPT) { 7316 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7317 numberOfPackagesToDexopt + ": " + pkg.packageName); 7318 } 7319 7320 if (showDialog) { 7321 try { 7322 ActivityManagerNative.getDefault().showBootMessage( 7323 mContext.getResources().getString(R.string.android_upgrading_apk, 7324 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7325 } catch (RemoteException e) { 7326 } 7327 } 7328 7329 // checkProfiles is false to avoid merging profiles during boot which 7330 // might interfere with background compilation (b/28612421). 7331 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7332 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7333 // trade-off worth doing to save boot time work. 7334 int dexOptStatus = performDexOptTraced(pkg.packageName, 7335 false /* checkProfiles */, 7336 compilerFilter, 7337 false /* force */); 7338 switch (dexOptStatus) { 7339 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7340 numberOfPackagesOptimized++; 7341 break; 7342 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7343 numberOfPackagesSkipped++; 7344 break; 7345 case PackageDexOptimizer.DEX_OPT_FAILED: 7346 numberOfPackagesFailed++; 7347 break; 7348 default: 7349 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7350 break; 7351 } 7352 } 7353 7354 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7355 numberOfPackagesFailed }; 7356 } 7357 7358 @Override 7359 public void notifyPackageUse(String packageName, int reason) { 7360 synchronized (mPackages) { 7361 PackageParser.Package p = mPackages.get(packageName); 7362 if (p == null) { 7363 return; 7364 } 7365 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7366 } 7367 } 7368 7369 // TODO: this is not used nor needed. Delete it. 7370 @Override 7371 public boolean performDexOptIfNeeded(String packageName) { 7372 int dexOptStatus = performDexOptTraced(packageName, 7373 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7374 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7375 } 7376 7377 @Override 7378 public boolean performDexOpt(String packageName, 7379 boolean checkProfiles, int compileReason, boolean force) { 7380 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7381 getCompilerFilterForReason(compileReason), force); 7382 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7383 } 7384 7385 @Override 7386 public boolean performDexOptMode(String packageName, 7387 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7388 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7389 targetCompilerFilter, force); 7390 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7391 } 7392 7393 private int performDexOptTraced(String packageName, 7394 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7395 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7396 try { 7397 return performDexOptInternal(packageName, checkProfiles, 7398 targetCompilerFilter, force); 7399 } finally { 7400 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7401 } 7402 } 7403 7404 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7405 // if the package can now be considered up to date for the given filter. 7406 private int performDexOptInternal(String packageName, 7407 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7408 PackageParser.Package p; 7409 synchronized (mPackages) { 7410 p = mPackages.get(packageName); 7411 if (p == null) { 7412 // Package could not be found. Report failure. 7413 return PackageDexOptimizer.DEX_OPT_FAILED; 7414 } 7415 mPackageUsage.write(false); 7416 } 7417 long callingId = Binder.clearCallingIdentity(); 7418 try { 7419 synchronized (mInstallLock) { 7420 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7421 targetCompilerFilter, force); 7422 } 7423 } finally { 7424 Binder.restoreCallingIdentity(callingId); 7425 } 7426 } 7427 7428 public ArraySet<String> getOptimizablePackages() { 7429 ArraySet<String> pkgs = new ArraySet<String>(); 7430 synchronized (mPackages) { 7431 for (PackageParser.Package p : mPackages.values()) { 7432 if (PackageDexOptimizer.canOptimizePackage(p)) { 7433 pkgs.add(p.packageName); 7434 } 7435 } 7436 } 7437 return pkgs; 7438 } 7439 7440 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7441 boolean checkProfiles, String targetCompilerFilter, 7442 boolean force) { 7443 // Select the dex optimizer based on the force parameter. 7444 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7445 // allocate an object here. 7446 PackageDexOptimizer pdo = force 7447 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7448 : mPackageDexOptimizer; 7449 7450 // Optimize all dependencies first. Note: we ignore the return value and march on 7451 // on errors. 7452 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7453 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7454 if (!deps.isEmpty()) { 7455 for (PackageParser.Package depPackage : deps) { 7456 // TODO: Analyze and investigate if we (should) profile libraries. 7457 // Currently this will do a full compilation of the library by default. 7458 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7459 false /* checkProfiles */, 7460 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7461 } 7462 } 7463 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7464 targetCompilerFilter); 7465 } 7466 7467 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7468 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7469 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7470 Set<String> collectedNames = new HashSet<>(); 7471 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7472 7473 retValue.remove(p); 7474 7475 return retValue; 7476 } else { 7477 return Collections.emptyList(); 7478 } 7479 } 7480 7481 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7482 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7483 if (!collectedNames.contains(p.packageName)) { 7484 collectedNames.add(p.packageName); 7485 collected.add(p); 7486 7487 if (p.usesLibraries != null) { 7488 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7489 } 7490 if (p.usesOptionalLibraries != null) { 7491 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7492 collectedNames); 7493 } 7494 } 7495 } 7496 7497 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7498 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7499 for (String libName : libs) { 7500 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7501 if (libPkg != null) { 7502 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7503 } 7504 } 7505 } 7506 7507 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7508 synchronized (mPackages) { 7509 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7510 if (lib != null && lib.apk != null) { 7511 return mPackages.get(lib.apk); 7512 } 7513 } 7514 return null; 7515 } 7516 7517 public void shutdown() { 7518 mPackageUsage.write(true); 7519 } 7520 7521 @Override 7522 public void dumpProfiles(String packageName) { 7523 PackageParser.Package pkg; 7524 synchronized (mPackages) { 7525 pkg = mPackages.get(packageName); 7526 if (pkg == null) { 7527 throw new IllegalArgumentException("Unknown package: " + packageName); 7528 } 7529 } 7530 /* Only the shell, root, or the app user should be able to dump profiles. */ 7531 int callingUid = Binder.getCallingUid(); 7532 if (callingUid != Process.SHELL_UID && 7533 callingUid != Process.ROOT_UID && 7534 callingUid != pkg.applicationInfo.uid) { 7535 throw new SecurityException("dumpProfiles"); 7536 } 7537 7538 synchronized (mInstallLock) { 7539 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7540 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7541 try { 7542 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7543 String gid = Integer.toString(sharedGid); 7544 String codePaths = TextUtils.join(";", allCodePaths); 7545 mInstaller.dumpProfiles(gid, packageName, codePaths); 7546 } catch (InstallerException e) { 7547 Slog.w(TAG, "Failed to dump profiles", e); 7548 } 7549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7550 } 7551 } 7552 7553 @Override 7554 public void forceDexOpt(String packageName) { 7555 enforceSystemOrRoot("forceDexOpt"); 7556 7557 PackageParser.Package pkg; 7558 synchronized (mPackages) { 7559 pkg = mPackages.get(packageName); 7560 if (pkg == null) { 7561 throw new IllegalArgumentException("Unknown package: " + packageName); 7562 } 7563 } 7564 7565 synchronized (mInstallLock) { 7566 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7567 7568 // Whoever is calling forceDexOpt wants a fully compiled package. 7569 // Don't use profiles since that may cause compilation to be skipped. 7570 final int res = performDexOptInternalWithDependenciesLI(pkg, 7571 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7572 true /* force */); 7573 7574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7575 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7576 throw new IllegalStateException("Failed to dexopt: " + res); 7577 } 7578 } 7579 } 7580 7581 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7582 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7583 Slog.w(TAG, "Unable to update from " + oldPkg.name 7584 + " to " + newPkg.packageName 7585 + ": old package not in system partition"); 7586 return false; 7587 } else if (mPackages.get(oldPkg.name) != null) { 7588 Slog.w(TAG, "Unable to update from " + oldPkg.name 7589 + " to " + newPkg.packageName 7590 + ": old package still exists"); 7591 return false; 7592 } 7593 return true; 7594 } 7595 7596 void removeCodePathLI(File codePath) { 7597 if (codePath.isDirectory()) { 7598 try { 7599 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7600 } catch (InstallerException e) { 7601 Slog.w(TAG, "Failed to remove code path", e); 7602 } 7603 } else { 7604 codePath.delete(); 7605 } 7606 } 7607 7608 private int[] resolveUserIds(int userId) { 7609 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7610 } 7611 7612 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7613 if (pkg == null) { 7614 Slog.wtf(TAG, "Package was null!", new Throwable()); 7615 return; 7616 } 7617 clearAppDataLeafLIF(pkg, userId, flags); 7618 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7619 for (int i = 0; i < childCount; i++) { 7620 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7621 } 7622 } 7623 7624 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7625 final PackageSetting ps; 7626 synchronized (mPackages) { 7627 ps = mSettings.mPackages.get(pkg.packageName); 7628 } 7629 for (int realUserId : resolveUserIds(userId)) { 7630 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7631 try { 7632 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7633 ceDataInode); 7634 } catch (InstallerException e) { 7635 Slog.w(TAG, String.valueOf(e)); 7636 } 7637 } 7638 } 7639 7640 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7641 if (pkg == null) { 7642 Slog.wtf(TAG, "Package was null!", new Throwable()); 7643 return; 7644 } 7645 destroyAppDataLeafLIF(pkg, userId, flags); 7646 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7647 for (int i = 0; i < childCount; i++) { 7648 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7649 } 7650 } 7651 7652 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7653 final PackageSetting ps; 7654 synchronized (mPackages) { 7655 ps = mSettings.mPackages.get(pkg.packageName); 7656 } 7657 for (int realUserId : resolveUserIds(userId)) { 7658 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7659 try { 7660 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7661 ceDataInode); 7662 } catch (InstallerException e) { 7663 Slog.w(TAG, String.valueOf(e)); 7664 } 7665 } 7666 } 7667 7668 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7669 if (pkg == null) { 7670 Slog.wtf(TAG, "Package was null!", new Throwable()); 7671 return; 7672 } 7673 destroyAppProfilesLeafLIF(pkg); 7674 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7675 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7676 for (int i = 0; i < childCount; i++) { 7677 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7678 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7679 true /* removeBaseMarker */); 7680 } 7681 } 7682 7683 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7684 boolean removeBaseMarker) { 7685 if (pkg.isForwardLocked()) { 7686 return; 7687 } 7688 7689 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7690 try { 7691 path = PackageManagerServiceUtils.realpath(new File(path)); 7692 } catch (IOException e) { 7693 // TODO: Should we return early here ? 7694 Slog.w(TAG, "Failed to get canonical path", e); 7695 continue; 7696 } 7697 7698 final String useMarker = path.replace('/', '@'); 7699 for (int realUserId : resolveUserIds(userId)) { 7700 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7701 if (removeBaseMarker) { 7702 File foreignUseMark = new File(profileDir, useMarker); 7703 if (foreignUseMark.exists()) { 7704 if (!foreignUseMark.delete()) { 7705 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7706 + pkg.packageName); 7707 } 7708 } 7709 } 7710 7711 File[] markers = profileDir.listFiles(); 7712 if (markers != null) { 7713 final String searchString = "@" + pkg.packageName + "@"; 7714 // We also delete all markers that contain the package name we're 7715 // uninstalling. These are associated with secondary dex-files belonging 7716 // to the package. Reconstructing the path of these dex files is messy 7717 // in general. 7718 for (File marker : markers) { 7719 if (marker.getName().indexOf(searchString) > 0) { 7720 if (!marker.delete()) { 7721 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7722 + pkg.packageName); 7723 } 7724 } 7725 } 7726 } 7727 } 7728 } 7729 } 7730 7731 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7732 try { 7733 mInstaller.destroyAppProfiles(pkg.packageName); 7734 } catch (InstallerException e) { 7735 Slog.w(TAG, String.valueOf(e)); 7736 } 7737 } 7738 7739 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7740 if (pkg == null) { 7741 Slog.wtf(TAG, "Package was null!", new Throwable()); 7742 return; 7743 } 7744 clearAppProfilesLeafLIF(pkg); 7745 // We don't remove the base foreign use marker when clearing profiles because 7746 // we will rename it when the app is updated. Unlike the actual profile contents, 7747 // the foreign use marker is good across installs. 7748 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7749 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7750 for (int i = 0; i < childCount; i++) { 7751 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7752 } 7753 } 7754 7755 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7756 try { 7757 mInstaller.clearAppProfiles(pkg.packageName); 7758 } catch (InstallerException e) { 7759 Slog.w(TAG, String.valueOf(e)); 7760 } 7761 } 7762 7763 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7764 long lastUpdateTime) { 7765 // Set parent install/update time 7766 PackageSetting ps = (PackageSetting) pkg.mExtras; 7767 if (ps != null) { 7768 ps.firstInstallTime = firstInstallTime; 7769 ps.lastUpdateTime = lastUpdateTime; 7770 } 7771 // Set children install/update time 7772 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7773 for (int i = 0; i < childCount; i++) { 7774 PackageParser.Package childPkg = pkg.childPackages.get(i); 7775 ps = (PackageSetting) childPkg.mExtras; 7776 if (ps != null) { 7777 ps.firstInstallTime = firstInstallTime; 7778 ps.lastUpdateTime = lastUpdateTime; 7779 } 7780 } 7781 } 7782 7783 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7784 PackageParser.Package changingLib) { 7785 if (file.path != null) { 7786 usesLibraryFiles.add(file.path); 7787 return; 7788 } 7789 PackageParser.Package p = mPackages.get(file.apk); 7790 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7791 // If we are doing this while in the middle of updating a library apk, 7792 // then we need to make sure to use that new apk for determining the 7793 // dependencies here. (We haven't yet finished committing the new apk 7794 // to the package manager state.) 7795 if (p == null || p.packageName.equals(changingLib.packageName)) { 7796 p = changingLib; 7797 } 7798 } 7799 if (p != null) { 7800 usesLibraryFiles.addAll(p.getAllCodePaths()); 7801 } 7802 } 7803 7804 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7805 PackageParser.Package changingLib) throws PackageManagerException { 7806 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7807 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7808 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7809 for (int i=0; i<N; i++) { 7810 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7811 if (file == null) { 7812 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7813 "Package " + pkg.packageName + " requires unavailable shared library " 7814 + pkg.usesLibraries.get(i) + "; failing!"); 7815 } 7816 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7817 } 7818 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7819 for (int i=0; i<N; i++) { 7820 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7821 if (file == null) { 7822 Slog.w(TAG, "Package " + pkg.packageName 7823 + " desires unavailable shared library " 7824 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7825 } else { 7826 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7827 } 7828 } 7829 N = usesLibraryFiles.size(); 7830 if (N > 0) { 7831 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7832 } else { 7833 pkg.usesLibraryFiles = null; 7834 } 7835 } 7836 } 7837 7838 private static boolean hasString(List<String> list, List<String> which) { 7839 if (list == null) { 7840 return false; 7841 } 7842 for (int i=list.size()-1; i>=0; i--) { 7843 for (int j=which.size()-1; j>=0; j--) { 7844 if (which.get(j).equals(list.get(i))) { 7845 return true; 7846 } 7847 } 7848 } 7849 return false; 7850 } 7851 7852 private void updateAllSharedLibrariesLPw() { 7853 for (PackageParser.Package pkg : mPackages.values()) { 7854 try { 7855 updateSharedLibrariesLPw(pkg, null); 7856 } catch (PackageManagerException e) { 7857 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7858 } 7859 } 7860 } 7861 7862 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7863 PackageParser.Package changingPkg) { 7864 ArrayList<PackageParser.Package> res = null; 7865 for (PackageParser.Package pkg : mPackages.values()) { 7866 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7867 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7868 if (res == null) { 7869 res = new ArrayList<PackageParser.Package>(); 7870 } 7871 res.add(pkg); 7872 try { 7873 updateSharedLibrariesLPw(pkg, changingPkg); 7874 } catch (PackageManagerException e) { 7875 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7876 } 7877 } 7878 } 7879 return res; 7880 } 7881 7882 /** 7883 * Derive the value of the {@code cpuAbiOverride} based on the provided 7884 * value and an optional stored value from the package settings. 7885 */ 7886 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7887 String cpuAbiOverride = null; 7888 7889 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7890 cpuAbiOverride = null; 7891 } else if (abiOverride != null) { 7892 cpuAbiOverride = abiOverride; 7893 } else if (settings != null) { 7894 cpuAbiOverride = settings.cpuAbiOverrideString; 7895 } 7896 7897 return cpuAbiOverride; 7898 } 7899 7900 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7901 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7902 throws PackageManagerException { 7903 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7904 // If the package has children and this is the first dive in the function 7905 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7906 // whether all packages (parent and children) would be successfully scanned 7907 // before the actual scan since scanning mutates internal state and we want 7908 // to atomically install the package and its children. 7909 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7910 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7911 scanFlags |= SCAN_CHECK_ONLY; 7912 } 7913 } else { 7914 scanFlags &= ~SCAN_CHECK_ONLY; 7915 } 7916 7917 final PackageParser.Package scannedPkg; 7918 try { 7919 // Scan the parent 7920 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7921 // Scan the children 7922 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7923 for (int i = 0; i < childCount; i++) { 7924 PackageParser.Package childPkg = pkg.childPackages.get(i); 7925 scanPackageLI(childPkg, policyFlags, 7926 scanFlags, currentTime, user); 7927 } 7928 } finally { 7929 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7930 } 7931 7932 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7933 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7934 } 7935 7936 return scannedPkg; 7937 } 7938 7939 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7940 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7941 boolean success = false; 7942 try { 7943 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7944 currentTime, user); 7945 success = true; 7946 return res; 7947 } finally { 7948 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7949 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7950 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7951 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7952 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7953 } 7954 } 7955 } 7956 7957 /** 7958 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7959 */ 7960 private static boolean apkHasCode(String fileName) { 7961 StrictJarFile jarFile = null; 7962 try { 7963 jarFile = new StrictJarFile(fileName, 7964 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7965 return jarFile.findEntry("classes.dex") != null; 7966 } catch (IOException ignore) { 7967 } finally { 7968 try { 7969 jarFile.close(); 7970 } catch (IOException ignore) {} 7971 } 7972 return false; 7973 } 7974 7975 /** 7976 * Enforces code policy for the package. This ensures that if an APK has 7977 * declared hasCode="true" in its manifest that the APK actually contains 7978 * code. 7979 * 7980 * @throws PackageManagerException If bytecode could not be found when it should exist 7981 */ 7982 private static void enforceCodePolicy(PackageParser.Package pkg) 7983 throws PackageManagerException { 7984 final boolean shouldHaveCode = 7985 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7986 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7987 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7988 "Package " + pkg.baseCodePath + " code is missing"); 7989 } 7990 7991 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7992 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7993 final boolean splitShouldHaveCode = 7994 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7995 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7996 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7997 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7998 } 7999 } 8000 } 8001 } 8002 8003 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8004 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8005 throws PackageManagerException { 8006 final File scanFile = new File(pkg.codePath); 8007 if (pkg.applicationInfo.getCodePath() == null || 8008 pkg.applicationInfo.getResourcePath() == null) { 8009 // Bail out. The resource and code paths haven't been set. 8010 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8011 "Code and resource paths haven't been set correctly"); 8012 } 8013 8014 // Apply policy 8015 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8016 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8017 if (pkg.applicationInfo.isDirectBootAware()) { 8018 // we're direct boot aware; set for all components 8019 for (PackageParser.Service s : pkg.services) { 8020 s.info.encryptionAware = s.info.directBootAware = true; 8021 } 8022 for (PackageParser.Provider p : pkg.providers) { 8023 p.info.encryptionAware = p.info.directBootAware = true; 8024 } 8025 for (PackageParser.Activity a : pkg.activities) { 8026 a.info.encryptionAware = a.info.directBootAware = true; 8027 } 8028 for (PackageParser.Activity r : pkg.receivers) { 8029 r.info.encryptionAware = r.info.directBootAware = true; 8030 } 8031 } 8032 } else { 8033 // Only allow system apps to be flagged as core apps. 8034 pkg.coreApp = false; 8035 // clear flags not applicable to regular apps 8036 pkg.applicationInfo.privateFlags &= 8037 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8038 pkg.applicationInfo.privateFlags &= 8039 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8040 } 8041 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8042 8043 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8044 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8045 } 8046 8047 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8048 enforceCodePolicy(pkg); 8049 } 8050 8051 if (mCustomResolverComponentName != null && 8052 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8053 setUpCustomResolverActivity(pkg); 8054 } 8055 8056 if (pkg.packageName.equals("android")) { 8057 synchronized (mPackages) { 8058 if (mAndroidApplication != null) { 8059 Slog.w(TAG, "*************************************************"); 8060 Slog.w(TAG, "Core android package being redefined. Skipping."); 8061 Slog.w(TAG, " file=" + scanFile); 8062 Slog.w(TAG, "*************************************************"); 8063 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8064 "Core android package being redefined. Skipping."); 8065 } 8066 8067 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8068 // Set up information for our fall-back user intent resolution activity. 8069 mPlatformPackage = pkg; 8070 pkg.mVersionCode = mSdkVersion; 8071 mAndroidApplication = pkg.applicationInfo; 8072 8073 if (!mResolverReplaced) { 8074 mResolveActivity.applicationInfo = mAndroidApplication; 8075 mResolveActivity.name = ResolverActivity.class.getName(); 8076 mResolveActivity.packageName = mAndroidApplication.packageName; 8077 mResolveActivity.processName = "system:ui"; 8078 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8079 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8080 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8081 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8082 mResolveActivity.exported = true; 8083 mResolveActivity.enabled = true; 8084 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8085 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8086 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8087 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8088 | ActivityInfo.CONFIG_ORIENTATION 8089 | ActivityInfo.CONFIG_KEYBOARD 8090 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8091 mResolveInfo.activityInfo = mResolveActivity; 8092 mResolveInfo.priority = 0; 8093 mResolveInfo.preferredOrder = 0; 8094 mResolveInfo.match = 0; 8095 mResolveComponentName = new ComponentName( 8096 mAndroidApplication.packageName, mResolveActivity.name); 8097 } 8098 } 8099 } 8100 } 8101 8102 if (DEBUG_PACKAGE_SCANNING) { 8103 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8104 Log.d(TAG, "Scanning package " + pkg.packageName); 8105 } 8106 8107 synchronized (mPackages) { 8108 if (mPackages.containsKey(pkg.packageName) 8109 || mSharedLibraries.containsKey(pkg.packageName)) { 8110 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8111 "Application package " + pkg.packageName 8112 + " already installed. Skipping duplicate."); 8113 } 8114 8115 // If we're only installing presumed-existing packages, require that the 8116 // scanned APK is both already known and at the path previously established 8117 // for it. Previously unknown packages we pick up normally, but if we have an 8118 // a priori expectation about this package's install presence, enforce it. 8119 // With a singular exception for new system packages. When an OTA contains 8120 // a new system package, we allow the codepath to change from a system location 8121 // to the user-installed location. If we don't allow this change, any newer, 8122 // user-installed version of the application will be ignored. 8123 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8124 if (mExpectingBetter.containsKey(pkg.packageName)) { 8125 logCriticalInfo(Log.WARN, 8126 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8127 } else { 8128 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8129 if (known != null) { 8130 if (DEBUG_PACKAGE_SCANNING) { 8131 Log.d(TAG, "Examining " + pkg.codePath 8132 + " and requiring known paths " + known.codePathString 8133 + " & " + known.resourcePathString); 8134 } 8135 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8136 || !pkg.applicationInfo.getResourcePath().equals( 8137 known.resourcePathString)) { 8138 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8139 "Application package " + pkg.packageName 8140 + " found at " + pkg.applicationInfo.getCodePath() 8141 + " but expected at " + known.codePathString 8142 + "; ignoring."); 8143 } 8144 } 8145 } 8146 } 8147 } 8148 8149 // Initialize package source and resource directories 8150 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8151 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8152 8153 SharedUserSetting suid = null; 8154 PackageSetting pkgSetting = null; 8155 8156 if (!isSystemApp(pkg)) { 8157 // Only system apps can use these features. 8158 pkg.mOriginalPackages = null; 8159 pkg.mRealPackage = null; 8160 pkg.mAdoptPermissions = null; 8161 } 8162 8163 // Getting the package setting may have a side-effect, so if we 8164 // are only checking if scan would succeed, stash a copy of the 8165 // old setting to restore at the end. 8166 PackageSetting nonMutatedPs = null; 8167 8168 // writer 8169 synchronized (mPackages) { 8170 if (pkg.mSharedUserId != null) { 8171 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8172 if (suid == null) { 8173 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8174 "Creating application package " + pkg.packageName 8175 + " for shared user failed"); 8176 } 8177 if (DEBUG_PACKAGE_SCANNING) { 8178 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8179 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8180 + "): packages=" + suid.packages); 8181 } 8182 } 8183 8184 // Check if we are renaming from an original package name. 8185 PackageSetting origPackage = null; 8186 String realName = null; 8187 if (pkg.mOriginalPackages != null) { 8188 // This package may need to be renamed to a previously 8189 // installed name. Let's check on that... 8190 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8191 if (pkg.mOriginalPackages.contains(renamed)) { 8192 // This package had originally been installed as the 8193 // original name, and we have already taken care of 8194 // transitioning to the new one. Just update the new 8195 // one to continue using the old name. 8196 realName = pkg.mRealPackage; 8197 if (!pkg.packageName.equals(renamed)) { 8198 // Callers into this function may have already taken 8199 // care of renaming the package; only do it here if 8200 // it is not already done. 8201 pkg.setPackageName(renamed); 8202 } 8203 8204 } else { 8205 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8206 if ((origPackage = mSettings.peekPackageLPr( 8207 pkg.mOriginalPackages.get(i))) != null) { 8208 // We do have the package already installed under its 8209 // original name... should we use it? 8210 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8211 // New package is not compatible with original. 8212 origPackage = null; 8213 continue; 8214 } else if (origPackage.sharedUser != null) { 8215 // Make sure uid is compatible between packages. 8216 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8217 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8218 + " to " + pkg.packageName + ": old uid " 8219 + origPackage.sharedUser.name 8220 + " differs from " + pkg.mSharedUserId); 8221 origPackage = null; 8222 continue; 8223 } 8224 // TODO: Add case when shared user id is added [b/28144775] 8225 } else { 8226 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8227 + pkg.packageName + " to old name " + origPackage.name); 8228 } 8229 break; 8230 } 8231 } 8232 } 8233 } 8234 8235 if (mTransferedPackages.contains(pkg.packageName)) { 8236 Slog.w(TAG, "Package " + pkg.packageName 8237 + " was transferred to another, but its .apk remains"); 8238 } 8239 8240 // See comments in nonMutatedPs declaration 8241 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8242 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8243 if (foundPs != null) { 8244 nonMutatedPs = new PackageSetting(foundPs); 8245 } 8246 } 8247 8248 // Just create the setting, don't add it yet. For already existing packages 8249 // the PkgSetting exists already and doesn't have to be created. 8250 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8251 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8252 pkg.applicationInfo.primaryCpuAbi, 8253 pkg.applicationInfo.secondaryCpuAbi, 8254 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8255 user, false); 8256 if (pkgSetting == null) { 8257 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8258 "Creating application package " + pkg.packageName + " failed"); 8259 } 8260 8261 if (pkgSetting.origPackage != null) { 8262 // If we are first transitioning from an original package, 8263 // fix up the new package's name now. We need to do this after 8264 // looking up the package under its new name, so getPackageLP 8265 // can take care of fiddling things correctly. 8266 pkg.setPackageName(origPackage.name); 8267 8268 // File a report about this. 8269 String msg = "New package " + pkgSetting.realName 8270 + " renamed to replace old package " + pkgSetting.name; 8271 reportSettingsProblem(Log.WARN, msg); 8272 8273 // Make a note of it. 8274 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8275 mTransferedPackages.add(origPackage.name); 8276 } 8277 8278 // No longer need to retain this. 8279 pkgSetting.origPackage = null; 8280 } 8281 8282 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8283 // Make a note of it. 8284 mTransferedPackages.add(pkg.packageName); 8285 } 8286 8287 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8288 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8289 } 8290 8291 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8292 // Check all shared libraries and map to their actual file path. 8293 // We only do this here for apps not on a system dir, because those 8294 // are the only ones that can fail an install due to this. We 8295 // will take care of the system apps by updating all of their 8296 // library paths after the scan is done. 8297 updateSharedLibrariesLPw(pkg, null); 8298 } 8299 8300 if (mFoundPolicyFile) { 8301 SELinuxMMAC.assignSeinfoValue(pkg); 8302 } 8303 8304 pkg.applicationInfo.uid = pkgSetting.appId; 8305 pkg.mExtras = pkgSetting; 8306 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8307 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8308 // We just determined the app is signed correctly, so bring 8309 // over the latest parsed certs. 8310 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8311 } else { 8312 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8313 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8314 "Package " + pkg.packageName + " upgrade keys do not match the " 8315 + "previously installed version"); 8316 } else { 8317 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8318 String msg = "System package " + pkg.packageName 8319 + " signature changed; retaining data."; 8320 reportSettingsProblem(Log.WARN, msg); 8321 } 8322 } 8323 } else { 8324 try { 8325 verifySignaturesLP(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 } catch (PackageManagerException e) { 8330 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8331 throw e; 8332 } 8333 // The signature has changed, but this package is in the system 8334 // image... let's recover! 8335 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8336 // However... if this package is part of a shared user, but it 8337 // doesn't match the signature of the shared user, let's fail. 8338 // What this means is that you can't change the signatures 8339 // associated with an overall shared user, which doesn't seem all 8340 // that unreasonable. 8341 if (pkgSetting.sharedUser != null) { 8342 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8343 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8344 throw new PackageManagerException( 8345 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8346 "Signature mismatch for shared user: " 8347 + pkgSetting.sharedUser); 8348 } 8349 } 8350 // File a report about this. 8351 String msg = "System package " + pkg.packageName 8352 + " signature changed; retaining data."; 8353 reportSettingsProblem(Log.WARN, msg); 8354 } 8355 } 8356 // Verify that this new package doesn't have any content providers 8357 // that conflict with existing packages. Only do this if the 8358 // package isn't already installed, since we don't want to break 8359 // things that are installed. 8360 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8361 final int N = pkg.providers.size(); 8362 int i; 8363 for (i=0; i<N; i++) { 8364 PackageParser.Provider p = pkg.providers.get(i); 8365 if (p.info.authority != null) { 8366 String names[] = p.info.authority.split(";"); 8367 for (int j = 0; j < names.length; j++) { 8368 if (mProvidersByAuthority.containsKey(names[j])) { 8369 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8370 final String otherPackageName = 8371 ((other != null && other.getComponentName() != null) ? 8372 other.getComponentName().getPackageName() : "?"); 8373 throw new PackageManagerException( 8374 INSTALL_FAILED_CONFLICTING_PROVIDER, 8375 "Can't install because provider name " + names[j] 8376 + " (in package " + pkg.applicationInfo.packageName 8377 + ") is already used by " + otherPackageName); 8378 } 8379 } 8380 } 8381 } 8382 } 8383 8384 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8385 // This package wants to adopt ownership of permissions from 8386 // another package. 8387 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8388 final String origName = pkg.mAdoptPermissions.get(i); 8389 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8390 if (orig != null) { 8391 if (verifyPackageUpdateLPr(orig, pkg)) { 8392 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8393 + pkg.packageName); 8394 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8395 } 8396 } 8397 } 8398 } 8399 } 8400 8401 final String pkgName = pkg.packageName; 8402 8403 final long scanFileTime = scanFile.lastModified(); 8404 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8405 pkg.applicationInfo.processName = fixProcessName( 8406 pkg.applicationInfo.packageName, 8407 pkg.applicationInfo.processName, 8408 pkg.applicationInfo.uid); 8409 8410 if (pkg != mPlatformPackage) { 8411 // Get all of our default paths setup 8412 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8413 } 8414 8415 final String path = scanFile.getPath(); 8416 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8417 8418 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8419 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8420 8421 // Some system apps still use directory structure for native libraries 8422 // in which case we might end up not detecting abi solely based on apk 8423 // structure. Try to detect abi based on directory structure. 8424 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8425 pkg.applicationInfo.primaryCpuAbi == null) { 8426 setBundledAppAbisAndRoots(pkg, pkgSetting); 8427 setNativeLibraryPaths(pkg); 8428 } 8429 8430 } else { 8431 if ((scanFlags & SCAN_MOVE) != 0) { 8432 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8433 // but we already have this packages package info in the PackageSetting. We just 8434 // use that and derive the native library path based on the new codepath. 8435 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8436 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8437 } 8438 8439 // Set native library paths again. For moves, the path will be updated based on the 8440 // ABIs we've determined above. For non-moves, the path will be updated based on the 8441 // ABIs we determined during compilation, but the path will depend on the final 8442 // package path (after the rename away from the stage path). 8443 setNativeLibraryPaths(pkg); 8444 } 8445 8446 // This is a special case for the "system" package, where the ABI is 8447 // dictated by the zygote configuration (and init.rc). We should keep track 8448 // of this ABI so that we can deal with "normal" applications that run under 8449 // the same UID correctly. 8450 if (mPlatformPackage == pkg) { 8451 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8452 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8453 } 8454 8455 // If there's a mismatch between the abi-override in the package setting 8456 // and the abiOverride specified for the install. Warn about this because we 8457 // would've already compiled the app without taking the package setting into 8458 // account. 8459 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8460 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8461 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8462 " for package " + pkg.packageName); 8463 } 8464 } 8465 8466 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8467 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8468 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8469 8470 // Copy the derived override back to the parsed package, so that we can 8471 // update the package settings accordingly. 8472 pkg.cpuAbiOverride = cpuAbiOverride; 8473 8474 if (DEBUG_ABI_SELECTION) { 8475 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8476 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8477 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8478 } 8479 8480 // Push the derived path down into PackageSettings so we know what to 8481 // clean up at uninstall time. 8482 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8483 8484 if (DEBUG_ABI_SELECTION) { 8485 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8486 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8487 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8488 } 8489 8490 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8491 // We don't do this here during boot because we can do it all 8492 // at once after scanning all existing packages. 8493 // 8494 // We also do this *before* we perform dexopt on this package, so that 8495 // we can avoid redundant dexopts, and also to make sure we've got the 8496 // code and package path correct. 8497 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8498 pkg, true /* boot complete */); 8499 } 8500 8501 if (mFactoryTest && pkg.requestedPermissions.contains( 8502 android.Manifest.permission.FACTORY_TEST)) { 8503 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8504 } 8505 8506 ArrayList<PackageParser.Package> clientLibPkgs = null; 8507 8508 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8509 if (nonMutatedPs != null) { 8510 synchronized (mPackages) { 8511 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8512 } 8513 } 8514 return pkg; 8515 } 8516 8517 // Only privileged apps and updated privileged apps can add child packages. 8518 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8519 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8520 throw new PackageManagerException("Only privileged apps and updated " 8521 + "privileged apps can add child packages. Ignoring package " 8522 + pkg.packageName); 8523 } 8524 final int childCount = pkg.childPackages.size(); 8525 for (int i = 0; i < childCount; i++) { 8526 PackageParser.Package childPkg = pkg.childPackages.get(i); 8527 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8528 childPkg.packageName)) { 8529 throw new PackageManagerException("Cannot override a child package of " 8530 + "another disabled system app. Ignoring package " + pkg.packageName); 8531 } 8532 } 8533 } 8534 8535 // writer 8536 synchronized (mPackages) { 8537 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8538 // Only system apps can add new shared libraries. 8539 if (pkg.libraryNames != null) { 8540 for (int i=0; i<pkg.libraryNames.size(); i++) { 8541 String name = pkg.libraryNames.get(i); 8542 boolean allowed = false; 8543 if (pkg.isUpdatedSystemApp()) { 8544 // New library entries can only be added through the 8545 // system image. This is important to get rid of a lot 8546 // of nasty edge cases: for example if we allowed a non- 8547 // system update of the app to add a library, then uninstalling 8548 // the update would make the library go away, and assumptions 8549 // we made such as through app install filtering would now 8550 // have allowed apps on the device which aren't compatible 8551 // with it. Better to just have the restriction here, be 8552 // conservative, and create many fewer cases that can negatively 8553 // impact the user experience. 8554 final PackageSetting sysPs = mSettings 8555 .getDisabledSystemPkgLPr(pkg.packageName); 8556 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8557 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8558 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8559 allowed = true; 8560 break; 8561 } 8562 } 8563 } 8564 } else { 8565 allowed = true; 8566 } 8567 if (allowed) { 8568 if (!mSharedLibraries.containsKey(name)) { 8569 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8570 } else if (!name.equals(pkg.packageName)) { 8571 Slog.w(TAG, "Package " + pkg.packageName + " library " 8572 + name + " already exists; skipping"); 8573 } 8574 } else { 8575 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8576 + name + " that is not declared on system image; skipping"); 8577 } 8578 } 8579 if ((scanFlags & SCAN_BOOTING) == 0) { 8580 // If we are not booting, we need to update any applications 8581 // that are clients of our shared library. If we are booting, 8582 // this will all be done once the scan is complete. 8583 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8584 } 8585 } 8586 } 8587 } 8588 8589 if ((scanFlags & SCAN_BOOTING) != 0) { 8590 // No apps can run during boot scan, so they don't need to be frozen 8591 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8592 // Caller asked to not kill app, so it's probably not frozen 8593 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8594 // Caller asked us to ignore frozen check for some reason; they 8595 // probably didn't know the package name 8596 } else { 8597 // We're doing major surgery on this package, so it better be frozen 8598 // right now to keep it from launching 8599 checkPackageFrozen(pkgName); 8600 } 8601 8602 // Also need to kill any apps that are dependent on the library. 8603 if (clientLibPkgs != null) { 8604 for (int i=0; i<clientLibPkgs.size(); i++) { 8605 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8606 killApplication(clientPkg.applicationInfo.packageName, 8607 clientPkg.applicationInfo.uid, "update lib"); 8608 } 8609 } 8610 8611 // Make sure we're not adding any bogus keyset info 8612 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8613 ksms.assertScannedPackageValid(pkg); 8614 8615 // writer 8616 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8617 8618 boolean createIdmapFailed = false; 8619 synchronized (mPackages) { 8620 // We don't expect installation to fail beyond this point 8621 8622 if (pkgSetting.pkg != null) { 8623 // Note that |user| might be null during the initial boot scan. If a codePath 8624 // for an app has changed during a boot scan, it's due to an app update that's 8625 // part of the system partition and marker changes must be applied to all users. 8626 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8627 (user != null) ? user : UserHandle.ALL); 8628 } 8629 8630 // Add the new setting to mSettings 8631 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8632 // Add the new setting to mPackages 8633 mPackages.put(pkg.applicationInfo.packageName, pkg); 8634 // Make sure we don't accidentally delete its data. 8635 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8636 while (iter.hasNext()) { 8637 PackageCleanItem item = iter.next(); 8638 if (pkgName.equals(item.packageName)) { 8639 iter.remove(); 8640 } 8641 } 8642 8643 // Take care of first install / last update times. 8644 if (currentTime != 0) { 8645 if (pkgSetting.firstInstallTime == 0) { 8646 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8647 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8648 pkgSetting.lastUpdateTime = currentTime; 8649 } 8650 } else if (pkgSetting.firstInstallTime == 0) { 8651 // We need *something*. Take time time stamp of the file. 8652 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8653 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8654 if (scanFileTime != pkgSetting.timeStamp) { 8655 // A package on the system image has changed; consider this 8656 // to be an update. 8657 pkgSetting.lastUpdateTime = scanFileTime; 8658 } 8659 } 8660 8661 // Add the package's KeySets to the global KeySetManagerService 8662 ksms.addScannedPackageLPw(pkg); 8663 8664 int N = pkg.providers.size(); 8665 StringBuilder r = null; 8666 int i; 8667 for (i=0; i<N; i++) { 8668 PackageParser.Provider p = pkg.providers.get(i); 8669 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8670 p.info.processName, pkg.applicationInfo.uid); 8671 mProviders.addProvider(p); 8672 p.syncable = p.info.isSyncable; 8673 if (p.info.authority != null) { 8674 String names[] = p.info.authority.split(";"); 8675 p.info.authority = null; 8676 for (int j = 0; j < names.length; j++) { 8677 if (j == 1 && p.syncable) { 8678 // We only want the first authority for a provider to possibly be 8679 // syncable, so if we already added this provider using a different 8680 // authority clear the syncable flag. We copy the provider before 8681 // changing it because the mProviders object contains a reference 8682 // to a provider that we don't want to change. 8683 // Only do this for the second authority since the resulting provider 8684 // object can be the same for all future authorities for this provider. 8685 p = new PackageParser.Provider(p); 8686 p.syncable = false; 8687 } 8688 if (!mProvidersByAuthority.containsKey(names[j])) { 8689 mProvidersByAuthority.put(names[j], p); 8690 if (p.info.authority == null) { 8691 p.info.authority = names[j]; 8692 } else { 8693 p.info.authority = p.info.authority + ";" + names[j]; 8694 } 8695 if (DEBUG_PACKAGE_SCANNING) { 8696 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8697 Log.d(TAG, "Registered content provider: " + names[j] 8698 + ", className = " + p.info.name + ", isSyncable = " 8699 + p.info.isSyncable); 8700 } 8701 } else { 8702 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8703 Slog.w(TAG, "Skipping provider name " + names[j] + 8704 " (in package " + pkg.applicationInfo.packageName + 8705 "): name already used by " 8706 + ((other != null && other.getComponentName() != null) 8707 ? other.getComponentName().getPackageName() : "?")); 8708 } 8709 } 8710 } 8711 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8712 if (r == null) { 8713 r = new StringBuilder(256); 8714 } else { 8715 r.append(' '); 8716 } 8717 r.append(p.info.name); 8718 } 8719 } 8720 if (r != null) { 8721 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8722 } 8723 8724 N = pkg.services.size(); 8725 r = null; 8726 for (i=0; i<N; i++) { 8727 PackageParser.Service s = pkg.services.get(i); 8728 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8729 s.info.processName, pkg.applicationInfo.uid); 8730 mServices.addService(s); 8731 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8732 if (r == null) { 8733 r = new StringBuilder(256); 8734 } else { 8735 r.append(' '); 8736 } 8737 r.append(s.info.name); 8738 } 8739 } 8740 if (r != null) { 8741 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8742 } 8743 8744 N = pkg.receivers.size(); 8745 r = null; 8746 for (i=0; i<N; i++) { 8747 PackageParser.Activity a = pkg.receivers.get(i); 8748 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8749 a.info.processName, pkg.applicationInfo.uid); 8750 mReceivers.addActivity(a, "receiver"); 8751 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8752 if (r == null) { 8753 r = new StringBuilder(256); 8754 } else { 8755 r.append(' '); 8756 } 8757 r.append(a.info.name); 8758 } 8759 } 8760 if (r != null) { 8761 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8762 } 8763 8764 N = pkg.activities.size(); 8765 r = null; 8766 for (i=0; i<N; i++) { 8767 PackageParser.Activity a = pkg.activities.get(i); 8768 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8769 a.info.processName, pkg.applicationInfo.uid); 8770 mActivities.addActivity(a, "activity"); 8771 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8772 if (r == null) { 8773 r = new StringBuilder(256); 8774 } else { 8775 r.append(' '); 8776 } 8777 r.append(a.info.name); 8778 } 8779 } 8780 if (r != null) { 8781 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8782 } 8783 8784 N = pkg.permissionGroups.size(); 8785 r = null; 8786 for (i=0; i<N; i++) { 8787 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8788 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8789 if (cur == null) { 8790 mPermissionGroups.put(pg.info.name, pg); 8791 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8792 if (r == null) { 8793 r = new StringBuilder(256); 8794 } else { 8795 r.append(' '); 8796 } 8797 r.append(pg.info.name); 8798 } 8799 } else { 8800 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8801 + pg.info.packageName + " ignored: original from " 8802 + cur.info.packageName); 8803 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8804 if (r == null) { 8805 r = new StringBuilder(256); 8806 } else { 8807 r.append(' '); 8808 } 8809 r.append("DUP:"); 8810 r.append(pg.info.name); 8811 } 8812 } 8813 } 8814 if (r != null) { 8815 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8816 } 8817 8818 N = pkg.permissions.size(); 8819 r = null; 8820 for (i=0; i<N; i++) { 8821 PackageParser.Permission p = pkg.permissions.get(i); 8822 8823 // Assume by default that we did not install this permission into the system. 8824 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8825 8826 // Now that permission groups have a special meaning, we ignore permission 8827 // groups for legacy apps to prevent unexpected behavior. In particular, 8828 // permissions for one app being granted to someone just becase they happen 8829 // to be in a group defined by another app (before this had no implications). 8830 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8831 p.group = mPermissionGroups.get(p.info.group); 8832 // Warn for a permission in an unknown group. 8833 if (p.info.group != null && p.group == null) { 8834 Slog.w(TAG, "Permission " + p.info.name + " from package " 8835 + p.info.packageName + " in an unknown group " + p.info.group); 8836 } 8837 } 8838 8839 ArrayMap<String, BasePermission> permissionMap = 8840 p.tree ? mSettings.mPermissionTrees 8841 : mSettings.mPermissions; 8842 BasePermission bp = permissionMap.get(p.info.name); 8843 8844 // Allow system apps to redefine non-system permissions 8845 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8846 final boolean currentOwnerIsSystem = (bp.perm != null 8847 && isSystemApp(bp.perm.owner)); 8848 if (isSystemApp(p.owner)) { 8849 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8850 // It's a built-in permission and no owner, take ownership now 8851 bp.packageSetting = pkgSetting; 8852 bp.perm = p; 8853 bp.uid = pkg.applicationInfo.uid; 8854 bp.sourcePackage = p.info.packageName; 8855 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8856 } else if (!currentOwnerIsSystem) { 8857 String msg = "New decl " + p.owner + " of permission " 8858 + p.info.name + " is system; overriding " + bp.sourcePackage; 8859 reportSettingsProblem(Log.WARN, msg); 8860 bp = null; 8861 } 8862 } 8863 } 8864 8865 if (bp == null) { 8866 bp = new BasePermission(p.info.name, p.info.packageName, 8867 BasePermission.TYPE_NORMAL); 8868 permissionMap.put(p.info.name, bp); 8869 } 8870 8871 if (bp.perm == null) { 8872 if (bp.sourcePackage == null 8873 || bp.sourcePackage.equals(p.info.packageName)) { 8874 BasePermission tree = findPermissionTreeLP(p.info.name); 8875 if (tree == null 8876 || tree.sourcePackage.equals(p.info.packageName)) { 8877 bp.packageSetting = pkgSetting; 8878 bp.perm = p; 8879 bp.uid = pkg.applicationInfo.uid; 8880 bp.sourcePackage = p.info.packageName; 8881 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8882 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8883 if (r == null) { 8884 r = new StringBuilder(256); 8885 } else { 8886 r.append(' '); 8887 } 8888 r.append(p.info.name); 8889 } 8890 } else { 8891 Slog.w(TAG, "Permission " + p.info.name + " from package " 8892 + p.info.packageName + " ignored: base tree " 8893 + tree.name + " is from package " 8894 + tree.sourcePackage); 8895 } 8896 } else { 8897 Slog.w(TAG, "Permission " + p.info.name + " from package " 8898 + p.info.packageName + " ignored: original from " 8899 + bp.sourcePackage); 8900 } 8901 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8902 if (r == null) { 8903 r = new StringBuilder(256); 8904 } else { 8905 r.append(' '); 8906 } 8907 r.append("DUP:"); 8908 r.append(p.info.name); 8909 } 8910 if (bp.perm == p) { 8911 bp.protectionLevel = p.info.protectionLevel; 8912 } 8913 } 8914 8915 if (r != null) { 8916 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8917 } 8918 8919 N = pkg.instrumentation.size(); 8920 r = null; 8921 for (i=0; i<N; i++) { 8922 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8923 a.info.packageName = pkg.applicationInfo.packageName; 8924 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8925 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8926 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8927 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8928 a.info.dataDir = pkg.applicationInfo.dataDir; 8929 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8930 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8931 8932 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8933 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8934 mInstrumentation.put(a.getComponentName(), a); 8935 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8936 if (r == null) { 8937 r = new StringBuilder(256); 8938 } else { 8939 r.append(' '); 8940 } 8941 r.append(a.info.name); 8942 } 8943 } 8944 if (r != null) { 8945 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8946 } 8947 8948 if (pkg.protectedBroadcasts != null) { 8949 N = pkg.protectedBroadcasts.size(); 8950 for (i=0; i<N; i++) { 8951 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8952 } 8953 } 8954 8955 pkgSetting.setTimeStamp(scanFileTime); 8956 8957 // Create idmap files for pairs of (packages, overlay packages). 8958 // Note: "android", ie framework-res.apk, is handled by native layers. 8959 if (pkg.mOverlayTarget != null) { 8960 // This is an overlay package. 8961 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8962 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8963 mOverlays.put(pkg.mOverlayTarget, 8964 new ArrayMap<String, PackageParser.Package>()); 8965 } 8966 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8967 map.put(pkg.packageName, pkg); 8968 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8969 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8970 createIdmapFailed = true; 8971 } 8972 } 8973 } else if (mOverlays.containsKey(pkg.packageName) && 8974 !pkg.packageName.equals("android")) { 8975 // This is a regular package, with one or more known overlay packages. 8976 createIdmapsForPackageLI(pkg); 8977 } 8978 } 8979 8980 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8981 8982 if (createIdmapFailed) { 8983 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8984 "scanPackageLI failed to createIdmap"); 8985 } 8986 return pkg; 8987 } 8988 8989 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8990 PackageParser.Package update, UserHandle user) { 8991 if (existing.applicationInfo == null || update.applicationInfo == null) { 8992 // This isn't due to an app installation. 8993 return; 8994 } 8995 8996 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8997 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8998 8999 // The codePath hasn't changed, so there's nothing for us to do. 9000 if (Objects.equals(oldCodePath, newCodePath)) { 9001 return; 9002 } 9003 9004 File canonicalNewCodePath; 9005 try { 9006 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9007 } catch (IOException e) { 9008 Slog.w(TAG, "Failed to get canonical path.", e); 9009 return; 9010 } 9011 9012 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9013 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9014 // that the last component of the path (i.e, the name) doesn't need canonicalization 9015 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9016 // but may change in the future. Hopefully this function won't exist at that point. 9017 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9018 oldCodePath.getName()); 9019 9020 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9021 // with "@". 9022 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9023 if (!oldMarkerPrefix.endsWith("@")) { 9024 oldMarkerPrefix += "@"; 9025 } 9026 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9027 if (!newMarkerPrefix.endsWith("@")) { 9028 newMarkerPrefix += "@"; 9029 } 9030 9031 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9032 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9033 for (String updatedPath : updatedPaths) { 9034 String updatedPathName = new File(updatedPath).getName(); 9035 markerSuffixes.add(updatedPathName.replace('/', '@')); 9036 } 9037 9038 for (int userId : resolveUserIds(user.getIdentifier())) { 9039 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9040 9041 for (String markerSuffix : markerSuffixes) { 9042 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9043 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9044 if (oldForeignUseMark.exists()) { 9045 try { 9046 Os.rename(oldForeignUseMark.getAbsolutePath(), 9047 newForeignUseMark.getAbsolutePath()); 9048 } catch (ErrnoException e) { 9049 Slog.w(TAG, "Failed to rename foreign use marker", e); 9050 oldForeignUseMark.delete(); 9051 } 9052 } 9053 } 9054 } 9055 } 9056 9057 /** 9058 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9059 * is derived purely on the basis of the contents of {@code scanFile} and 9060 * {@code cpuAbiOverride}. 9061 * 9062 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9063 */ 9064 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9065 String cpuAbiOverride, boolean extractLibs) 9066 throws PackageManagerException { 9067 // TODO: We can probably be smarter about this stuff. For installed apps, 9068 // we can calculate this information at install time once and for all. For 9069 // system apps, we can probably assume that this information doesn't change 9070 // after the first boot scan. As things stand, we do lots of unnecessary work. 9071 9072 // Give ourselves some initial paths; we'll come back for another 9073 // pass once we've determined ABI below. 9074 setNativeLibraryPaths(pkg); 9075 9076 // We would never need to extract libs for forward-locked and external packages, 9077 // since the container service will do it for us. We shouldn't attempt to 9078 // extract libs from system app when it was not updated. 9079 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9080 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9081 extractLibs = false; 9082 } 9083 9084 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9085 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9086 9087 NativeLibraryHelper.Handle handle = null; 9088 try { 9089 handle = NativeLibraryHelper.Handle.create(pkg); 9090 // TODO(multiArch): This can be null for apps that didn't go through the 9091 // usual installation process. We can calculate it again, like we 9092 // do during install time. 9093 // 9094 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9095 // unnecessary. 9096 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9097 9098 // Null out the abis so that they can be recalculated. 9099 pkg.applicationInfo.primaryCpuAbi = null; 9100 pkg.applicationInfo.secondaryCpuAbi = null; 9101 if (isMultiArch(pkg.applicationInfo)) { 9102 // Warn if we've set an abiOverride for multi-lib packages.. 9103 // By definition, we need to copy both 32 and 64 bit libraries for 9104 // such packages. 9105 if (pkg.cpuAbiOverride != null 9106 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9107 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9108 } 9109 9110 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9111 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9112 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9113 if (extractLibs) { 9114 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9115 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9116 useIsaSpecificSubdirs); 9117 } else { 9118 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9119 } 9120 } 9121 9122 maybeThrowExceptionForMultiArchCopy( 9123 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9124 9125 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9126 if (extractLibs) { 9127 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9128 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9129 useIsaSpecificSubdirs); 9130 } else { 9131 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9132 } 9133 } 9134 9135 maybeThrowExceptionForMultiArchCopy( 9136 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9137 9138 if (abi64 >= 0) { 9139 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9140 } 9141 9142 if (abi32 >= 0) { 9143 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9144 if (abi64 >= 0) { 9145 if (pkg.use32bitAbi) { 9146 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9147 pkg.applicationInfo.primaryCpuAbi = abi; 9148 } else { 9149 pkg.applicationInfo.secondaryCpuAbi = abi; 9150 } 9151 } else { 9152 pkg.applicationInfo.primaryCpuAbi = abi; 9153 } 9154 } 9155 9156 } else { 9157 String[] abiList = (cpuAbiOverride != null) ? 9158 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9159 9160 // Enable gross and lame hacks for apps that are built with old 9161 // SDK tools. We must scan their APKs for renderscript bitcode and 9162 // not launch them if it's present. Don't bother checking on devices 9163 // that don't have 64 bit support. 9164 boolean needsRenderScriptOverride = false; 9165 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9166 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9167 abiList = Build.SUPPORTED_32_BIT_ABIS; 9168 needsRenderScriptOverride = true; 9169 } 9170 9171 final int copyRet; 9172 if (extractLibs) { 9173 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9174 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9175 } else { 9176 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9177 } 9178 9179 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9180 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9181 "Error unpackaging native libs for app, errorCode=" + copyRet); 9182 } 9183 9184 if (copyRet >= 0) { 9185 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9186 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9187 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9188 } else if (needsRenderScriptOverride) { 9189 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9190 } 9191 } 9192 } catch (IOException ioe) { 9193 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9194 } finally { 9195 IoUtils.closeQuietly(handle); 9196 } 9197 9198 // Now that we've calculated the ABIs and determined if it's an internal app, 9199 // we will go ahead and populate the nativeLibraryPath. 9200 setNativeLibraryPaths(pkg); 9201 } 9202 9203 /** 9204 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9205 * i.e, so that all packages can be run inside a single process if required. 9206 * 9207 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9208 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9209 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9210 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9211 * updating a package that belongs to a shared user. 9212 * 9213 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9214 * adds unnecessary complexity. 9215 */ 9216 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9217 PackageParser.Package scannedPackage, boolean bootComplete) { 9218 String requiredInstructionSet = null; 9219 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9220 requiredInstructionSet = VMRuntime.getInstructionSet( 9221 scannedPackage.applicationInfo.primaryCpuAbi); 9222 } 9223 9224 PackageSetting requirer = null; 9225 for (PackageSetting ps : packagesForUser) { 9226 // If packagesForUser contains scannedPackage, we skip it. This will happen 9227 // when scannedPackage is an update of an existing package. Without this check, 9228 // we will never be able to change the ABI of any package belonging to a shared 9229 // user, even if it's compatible with other packages. 9230 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9231 if (ps.primaryCpuAbiString == null) { 9232 continue; 9233 } 9234 9235 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9236 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9237 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9238 // this but there's not much we can do. 9239 String errorMessage = "Instruction set mismatch, " 9240 + ((requirer == null) ? "[caller]" : requirer) 9241 + " requires " + requiredInstructionSet + " whereas " + ps 9242 + " requires " + instructionSet; 9243 Slog.w(TAG, errorMessage); 9244 } 9245 9246 if (requiredInstructionSet == null) { 9247 requiredInstructionSet = instructionSet; 9248 requirer = ps; 9249 } 9250 } 9251 } 9252 9253 if (requiredInstructionSet != null) { 9254 String adjustedAbi; 9255 if (requirer != null) { 9256 // requirer != null implies that either scannedPackage was null or that scannedPackage 9257 // did not require an ABI, in which case we have to adjust scannedPackage to match 9258 // the ABI of the set (which is the same as requirer's ABI) 9259 adjustedAbi = requirer.primaryCpuAbiString; 9260 if (scannedPackage != null) { 9261 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9262 } 9263 } else { 9264 // requirer == null implies that we're updating all ABIs in the set to 9265 // match scannedPackage. 9266 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9267 } 9268 9269 for (PackageSetting ps : packagesForUser) { 9270 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9271 if (ps.primaryCpuAbiString != null) { 9272 continue; 9273 } 9274 9275 ps.primaryCpuAbiString = adjustedAbi; 9276 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9277 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9278 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9279 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9280 + " (requirer=" 9281 + (requirer == null ? "null" : requirer.pkg.packageName) 9282 + ", scannedPackage=" 9283 + (scannedPackage != null ? scannedPackage.packageName : "null") 9284 + ")"); 9285 try { 9286 mInstaller.rmdex(ps.codePathString, 9287 getDexCodeInstructionSet(getPreferredInstructionSet())); 9288 } catch (InstallerException ignored) { 9289 } 9290 } 9291 } 9292 } 9293 } 9294 } 9295 9296 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9297 synchronized (mPackages) { 9298 mResolverReplaced = true; 9299 // Set up information for custom user intent resolution activity. 9300 mResolveActivity.applicationInfo = pkg.applicationInfo; 9301 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9302 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9303 mResolveActivity.processName = pkg.applicationInfo.packageName; 9304 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9305 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9306 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9307 mResolveActivity.theme = 0; 9308 mResolveActivity.exported = true; 9309 mResolveActivity.enabled = true; 9310 mResolveInfo.activityInfo = mResolveActivity; 9311 mResolveInfo.priority = 0; 9312 mResolveInfo.preferredOrder = 0; 9313 mResolveInfo.match = 0; 9314 mResolveComponentName = mCustomResolverComponentName; 9315 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9316 mResolveComponentName); 9317 } 9318 } 9319 9320 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9321 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9322 9323 // Set up information for ephemeral installer activity 9324 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9325 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9326 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9327 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9328 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9329 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9330 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9331 mEphemeralInstallerActivity.theme = 0; 9332 mEphemeralInstallerActivity.exported = true; 9333 mEphemeralInstallerActivity.enabled = true; 9334 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9335 mEphemeralInstallerInfo.priority = 0; 9336 mEphemeralInstallerInfo.preferredOrder = 0; 9337 mEphemeralInstallerInfo.match = 0; 9338 9339 if (DEBUG_EPHEMERAL) { 9340 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9341 } 9342 } 9343 9344 private static String calculateBundledApkRoot(final String codePathString) { 9345 final File codePath = new File(codePathString); 9346 final File codeRoot; 9347 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9348 codeRoot = Environment.getRootDirectory(); 9349 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9350 codeRoot = Environment.getOemDirectory(); 9351 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9352 codeRoot = Environment.getVendorDirectory(); 9353 } else { 9354 // Unrecognized code path; take its top real segment as the apk root: 9355 // e.g. /something/app/blah.apk => /something 9356 try { 9357 File f = codePath.getCanonicalFile(); 9358 File parent = f.getParentFile(); // non-null because codePath is a file 9359 File tmp; 9360 while ((tmp = parent.getParentFile()) != null) { 9361 f = parent; 9362 parent = tmp; 9363 } 9364 codeRoot = f; 9365 Slog.w(TAG, "Unrecognized code path " 9366 + codePath + " - using " + codeRoot); 9367 } catch (IOException e) { 9368 // Can't canonicalize the code path -- shenanigans? 9369 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9370 return Environment.getRootDirectory().getPath(); 9371 } 9372 } 9373 return codeRoot.getPath(); 9374 } 9375 9376 /** 9377 * Derive and set the location of native libraries for the given package, 9378 * which varies depending on where and how the package was installed. 9379 */ 9380 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9381 final ApplicationInfo info = pkg.applicationInfo; 9382 final String codePath = pkg.codePath; 9383 final File codeFile = new File(codePath); 9384 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9385 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9386 9387 info.nativeLibraryRootDir = null; 9388 info.nativeLibraryRootRequiresIsa = false; 9389 info.nativeLibraryDir = null; 9390 info.secondaryNativeLibraryDir = null; 9391 9392 if (isApkFile(codeFile)) { 9393 // Monolithic install 9394 if (bundledApp) { 9395 // If "/system/lib64/apkname" exists, assume that is the per-package 9396 // native library directory to use; otherwise use "/system/lib/apkname". 9397 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9398 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9399 getPrimaryInstructionSet(info)); 9400 9401 // This is a bundled system app so choose the path based on the ABI. 9402 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9403 // is just the default path. 9404 final String apkName = deriveCodePathName(codePath); 9405 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9406 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9407 apkName).getAbsolutePath(); 9408 9409 if (info.secondaryCpuAbi != null) { 9410 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9411 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9412 secondaryLibDir, apkName).getAbsolutePath(); 9413 } 9414 } else if (asecApp) { 9415 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9416 .getAbsolutePath(); 9417 } else { 9418 final String apkName = deriveCodePathName(codePath); 9419 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9420 .getAbsolutePath(); 9421 } 9422 9423 info.nativeLibraryRootRequiresIsa = false; 9424 info.nativeLibraryDir = info.nativeLibraryRootDir; 9425 } else { 9426 // Cluster install 9427 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9428 info.nativeLibraryRootRequiresIsa = true; 9429 9430 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9431 getPrimaryInstructionSet(info)).getAbsolutePath(); 9432 9433 if (info.secondaryCpuAbi != null) { 9434 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9435 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9436 } 9437 } 9438 } 9439 9440 /** 9441 * Calculate the abis and roots for a bundled app. These can uniquely 9442 * be determined from the contents of the system partition, i.e whether 9443 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9444 * of this information, and instead assume that the system was built 9445 * sensibly. 9446 */ 9447 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9448 PackageSetting pkgSetting) { 9449 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9450 9451 // If "/system/lib64/apkname" exists, assume that is the per-package 9452 // native library directory to use; otherwise use "/system/lib/apkname". 9453 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9454 setBundledAppAbi(pkg, apkRoot, apkName); 9455 // pkgSetting might be null during rescan following uninstall of updates 9456 // to a bundled app, so accommodate that possibility. The settings in 9457 // that case will be established later from the parsed package. 9458 // 9459 // If the settings aren't null, sync them up with what we've just derived. 9460 // note that apkRoot isn't stored in the package settings. 9461 if (pkgSetting != null) { 9462 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9463 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9464 } 9465 } 9466 9467 /** 9468 * Deduces the ABI of a bundled app and sets the relevant fields on the 9469 * parsed pkg object. 9470 * 9471 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9472 * under which system libraries are installed. 9473 * @param apkName the name of the installed package. 9474 */ 9475 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9476 final File codeFile = new File(pkg.codePath); 9477 9478 final boolean has64BitLibs; 9479 final boolean has32BitLibs; 9480 if (isApkFile(codeFile)) { 9481 // Monolithic install 9482 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9483 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9484 } else { 9485 // Cluster install 9486 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9487 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9488 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9489 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9490 has64BitLibs = (new File(rootDir, isa)).exists(); 9491 } else { 9492 has64BitLibs = false; 9493 } 9494 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9495 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9496 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9497 has32BitLibs = (new File(rootDir, isa)).exists(); 9498 } else { 9499 has32BitLibs = false; 9500 } 9501 } 9502 9503 if (has64BitLibs && !has32BitLibs) { 9504 // The package has 64 bit libs, but not 32 bit libs. Its primary 9505 // ABI should be 64 bit. We can safely assume here that the bundled 9506 // native libraries correspond to the most preferred ABI in the list. 9507 9508 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9509 pkg.applicationInfo.secondaryCpuAbi = null; 9510 } else if (has32BitLibs && !has64BitLibs) { 9511 // The package has 32 bit libs but not 64 bit libs. Its primary 9512 // ABI should be 32 bit. 9513 9514 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9515 pkg.applicationInfo.secondaryCpuAbi = null; 9516 } else if (has32BitLibs && has64BitLibs) { 9517 // The application has both 64 and 32 bit bundled libraries. We check 9518 // here that the app declares multiArch support, and warn if it doesn't. 9519 // 9520 // We will be lenient here and record both ABIs. The primary will be the 9521 // ABI that's higher on the list, i.e, a device that's configured to prefer 9522 // 64 bit apps will see a 64 bit primary ABI, 9523 9524 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9525 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9526 } 9527 9528 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9529 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9530 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9531 } else { 9532 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9533 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9534 } 9535 } else { 9536 pkg.applicationInfo.primaryCpuAbi = null; 9537 pkg.applicationInfo.secondaryCpuAbi = null; 9538 } 9539 } 9540 9541 private void killApplication(String pkgName, int appId, String reason) { 9542 // Request the ActivityManager to kill the process(only for existing packages) 9543 // so that we do not end up in a confused state while the user is still using the older 9544 // version of the application while the new one gets installed. 9545 final long token = Binder.clearCallingIdentity(); 9546 try { 9547 IActivityManager am = ActivityManagerNative.getDefault(); 9548 if (am != null) { 9549 try { 9550 am.killApplicationWithAppId(pkgName, appId, reason); 9551 } catch (RemoteException e) { 9552 } 9553 } 9554 } finally { 9555 Binder.restoreCallingIdentity(token); 9556 } 9557 } 9558 9559 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9560 // Remove the parent package setting 9561 PackageSetting ps = (PackageSetting) pkg.mExtras; 9562 if (ps != null) { 9563 removePackageLI(ps, chatty); 9564 } 9565 // Remove the child package setting 9566 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9567 for (int i = 0; i < childCount; i++) { 9568 PackageParser.Package childPkg = pkg.childPackages.get(i); 9569 ps = (PackageSetting) childPkg.mExtras; 9570 if (ps != null) { 9571 removePackageLI(ps, chatty); 9572 } 9573 } 9574 } 9575 9576 void removePackageLI(PackageSetting ps, boolean chatty) { 9577 if (DEBUG_INSTALL) { 9578 if (chatty) 9579 Log.d(TAG, "Removing package " + ps.name); 9580 } 9581 9582 // writer 9583 synchronized (mPackages) { 9584 mPackages.remove(ps.name); 9585 final PackageParser.Package pkg = ps.pkg; 9586 if (pkg != null) { 9587 cleanPackageDataStructuresLILPw(pkg, chatty); 9588 } 9589 } 9590 } 9591 9592 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9593 if (DEBUG_INSTALL) { 9594 if (chatty) 9595 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9596 } 9597 9598 // writer 9599 synchronized (mPackages) { 9600 // Remove the parent package 9601 mPackages.remove(pkg.applicationInfo.packageName); 9602 cleanPackageDataStructuresLILPw(pkg, chatty); 9603 9604 // Remove the child packages 9605 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9606 for (int i = 0; i < childCount; i++) { 9607 PackageParser.Package childPkg = pkg.childPackages.get(i); 9608 mPackages.remove(childPkg.applicationInfo.packageName); 9609 cleanPackageDataStructuresLILPw(childPkg, chatty); 9610 } 9611 } 9612 } 9613 9614 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9615 int N = pkg.providers.size(); 9616 StringBuilder r = null; 9617 int i; 9618 for (i=0; i<N; i++) { 9619 PackageParser.Provider p = pkg.providers.get(i); 9620 mProviders.removeProvider(p); 9621 if (p.info.authority == null) { 9622 9623 /* There was another ContentProvider with this authority when 9624 * this app was installed so this authority is null, 9625 * Ignore it as we don't have to unregister the provider. 9626 */ 9627 continue; 9628 } 9629 String names[] = p.info.authority.split(";"); 9630 for (int j = 0; j < names.length; j++) { 9631 if (mProvidersByAuthority.get(names[j]) == p) { 9632 mProvidersByAuthority.remove(names[j]); 9633 if (DEBUG_REMOVE) { 9634 if (chatty) 9635 Log.d(TAG, "Unregistered content provider: " + names[j] 9636 + ", className = " + p.info.name + ", isSyncable = " 9637 + p.info.isSyncable); 9638 } 9639 } 9640 } 9641 if (DEBUG_REMOVE && chatty) { 9642 if (r == null) { 9643 r = new StringBuilder(256); 9644 } else { 9645 r.append(' '); 9646 } 9647 r.append(p.info.name); 9648 } 9649 } 9650 if (r != null) { 9651 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9652 } 9653 9654 N = pkg.services.size(); 9655 r = null; 9656 for (i=0; i<N; i++) { 9657 PackageParser.Service s = pkg.services.get(i); 9658 mServices.removeService(s); 9659 if (chatty) { 9660 if (r == null) { 9661 r = new StringBuilder(256); 9662 } else { 9663 r.append(' '); 9664 } 9665 r.append(s.info.name); 9666 } 9667 } 9668 if (r != null) { 9669 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9670 } 9671 9672 N = pkg.receivers.size(); 9673 r = null; 9674 for (i=0; i<N; i++) { 9675 PackageParser.Activity a = pkg.receivers.get(i); 9676 mReceivers.removeActivity(a, "receiver"); 9677 if (DEBUG_REMOVE && chatty) { 9678 if (r == null) { 9679 r = new StringBuilder(256); 9680 } else { 9681 r.append(' '); 9682 } 9683 r.append(a.info.name); 9684 } 9685 } 9686 if (r != null) { 9687 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9688 } 9689 9690 N = pkg.activities.size(); 9691 r = null; 9692 for (i=0; i<N; i++) { 9693 PackageParser.Activity a = pkg.activities.get(i); 9694 mActivities.removeActivity(a, "activity"); 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, " Activities: " + r); 9706 } 9707 9708 N = pkg.permissions.size(); 9709 r = null; 9710 for (i=0; i<N; i++) { 9711 PackageParser.Permission p = pkg.permissions.get(i); 9712 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9713 if (bp == null) { 9714 bp = mSettings.mPermissionTrees.get(p.info.name); 9715 } 9716 if (bp != null && bp.perm == p) { 9717 bp.perm = null; 9718 if (DEBUG_REMOVE && chatty) { 9719 if (r == null) { 9720 r = new StringBuilder(256); 9721 } else { 9722 r.append(' '); 9723 } 9724 r.append(p.info.name); 9725 } 9726 } 9727 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9728 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9729 if (appOpPkgs != null) { 9730 appOpPkgs.remove(pkg.packageName); 9731 } 9732 } 9733 } 9734 if (r != null) { 9735 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9736 } 9737 9738 N = pkg.requestedPermissions.size(); 9739 r = null; 9740 for (i=0; i<N; i++) { 9741 String perm = pkg.requestedPermissions.get(i); 9742 BasePermission bp = mSettings.mPermissions.get(perm); 9743 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9744 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9745 if (appOpPkgs != null) { 9746 appOpPkgs.remove(pkg.packageName); 9747 if (appOpPkgs.isEmpty()) { 9748 mAppOpPermissionPackages.remove(perm); 9749 } 9750 } 9751 } 9752 } 9753 if (r != null) { 9754 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9755 } 9756 9757 N = pkg.instrumentation.size(); 9758 r = null; 9759 for (i=0; i<N; i++) { 9760 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9761 mInstrumentation.remove(a.getComponentName()); 9762 if (DEBUG_REMOVE && chatty) { 9763 if (r == null) { 9764 r = new StringBuilder(256); 9765 } else { 9766 r.append(' '); 9767 } 9768 r.append(a.info.name); 9769 } 9770 } 9771 if (r != null) { 9772 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9773 } 9774 9775 r = null; 9776 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9777 // Only system apps can hold shared libraries. 9778 if (pkg.libraryNames != null) { 9779 for (i=0; i<pkg.libraryNames.size(); i++) { 9780 String name = pkg.libraryNames.get(i); 9781 SharedLibraryEntry cur = mSharedLibraries.get(name); 9782 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9783 mSharedLibraries.remove(name); 9784 if (DEBUG_REMOVE && chatty) { 9785 if (r == null) { 9786 r = new StringBuilder(256); 9787 } else { 9788 r.append(' '); 9789 } 9790 r.append(name); 9791 } 9792 } 9793 } 9794 } 9795 } 9796 if (r != null) { 9797 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9798 } 9799 } 9800 9801 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9802 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9803 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9804 return true; 9805 } 9806 } 9807 return false; 9808 } 9809 9810 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9811 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9812 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9813 9814 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9815 // Update the parent permissions 9816 updatePermissionsLPw(pkg.packageName, pkg, flags); 9817 // Update the child permissions 9818 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9819 for (int i = 0; i < childCount; i++) { 9820 PackageParser.Package childPkg = pkg.childPackages.get(i); 9821 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9822 } 9823 } 9824 9825 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9826 int flags) { 9827 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9828 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9829 } 9830 9831 private void updatePermissionsLPw(String changingPkg, 9832 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9833 // Make sure there are no dangling permission trees. 9834 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9835 while (it.hasNext()) { 9836 final BasePermission bp = it.next(); 9837 if (bp.packageSetting == null) { 9838 // We may not yet have parsed the package, so just see if 9839 // we still know about its settings. 9840 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9841 } 9842 if (bp.packageSetting == null) { 9843 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9844 + " from package " + bp.sourcePackage); 9845 it.remove(); 9846 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9847 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9848 Slog.i(TAG, "Removing old permission tree: " + bp.name 9849 + " from package " + bp.sourcePackage); 9850 flags |= UPDATE_PERMISSIONS_ALL; 9851 it.remove(); 9852 } 9853 } 9854 } 9855 9856 // Make sure all dynamic permissions have been assigned to a package, 9857 // and make sure there are no dangling permissions. 9858 it = mSettings.mPermissions.values().iterator(); 9859 while (it.hasNext()) { 9860 final BasePermission bp = it.next(); 9861 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9862 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9863 + bp.name + " pkg=" + bp.sourcePackage 9864 + " info=" + bp.pendingInfo); 9865 if (bp.packageSetting == null && bp.pendingInfo != null) { 9866 final BasePermission tree = findPermissionTreeLP(bp.name); 9867 if (tree != null && tree.perm != null) { 9868 bp.packageSetting = tree.packageSetting; 9869 bp.perm = new PackageParser.Permission(tree.perm.owner, 9870 new PermissionInfo(bp.pendingInfo)); 9871 bp.perm.info.packageName = tree.perm.info.packageName; 9872 bp.perm.info.name = bp.name; 9873 bp.uid = tree.uid; 9874 } 9875 } 9876 } 9877 if (bp.packageSetting == null) { 9878 // We may not yet have parsed the package, so just see if 9879 // we still know about its settings. 9880 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9881 } 9882 if (bp.packageSetting == null) { 9883 Slog.w(TAG, "Removing dangling permission: " + bp.name 9884 + " from package " + bp.sourcePackage); 9885 it.remove(); 9886 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9887 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9888 Slog.i(TAG, "Removing old permission: " + bp.name 9889 + " from package " + bp.sourcePackage); 9890 flags |= UPDATE_PERMISSIONS_ALL; 9891 it.remove(); 9892 } 9893 } 9894 } 9895 9896 // Now update the permissions for all packages, in particular 9897 // replace the granted permissions of the system packages. 9898 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9899 for (PackageParser.Package pkg : mPackages.values()) { 9900 if (pkg != pkgInfo) { 9901 // Only replace for packages on requested volume 9902 final String volumeUuid = getVolumeUuidForPackage(pkg); 9903 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9904 && Objects.equals(replaceVolumeUuid, volumeUuid); 9905 grantPermissionsLPw(pkg, replace, changingPkg); 9906 } 9907 } 9908 } 9909 9910 if (pkgInfo != null) { 9911 // Only replace for packages on requested volume 9912 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9913 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9914 && Objects.equals(replaceVolumeUuid, volumeUuid); 9915 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9916 } 9917 } 9918 9919 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9920 String packageOfInterest) { 9921 // IMPORTANT: There are two types of permissions: install and runtime. 9922 // Install time permissions are granted when the app is installed to 9923 // all device users and users added in the future. Runtime permissions 9924 // are granted at runtime explicitly to specific users. Normal and signature 9925 // protected permissions are install time permissions. Dangerous permissions 9926 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9927 // otherwise they are runtime permissions. This function does not manage 9928 // runtime permissions except for the case an app targeting Lollipop MR1 9929 // being upgraded to target a newer SDK, in which case dangerous permissions 9930 // are transformed from install time to runtime ones. 9931 9932 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9933 if (ps == null) { 9934 return; 9935 } 9936 9937 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9938 9939 PermissionsState permissionsState = ps.getPermissionsState(); 9940 PermissionsState origPermissions = permissionsState; 9941 9942 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9943 9944 boolean runtimePermissionsRevoked = false; 9945 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9946 9947 boolean changedInstallPermission = false; 9948 9949 if (replace) { 9950 ps.installPermissionsFixed = false; 9951 if (!ps.isSharedUser()) { 9952 origPermissions = new PermissionsState(permissionsState); 9953 permissionsState.reset(); 9954 } else { 9955 // We need to know only about runtime permission changes since the 9956 // calling code always writes the install permissions state but 9957 // the runtime ones are written only if changed. The only cases of 9958 // changed runtime permissions here are promotion of an install to 9959 // runtime and revocation of a runtime from a shared user. 9960 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9961 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9962 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9963 runtimePermissionsRevoked = true; 9964 } 9965 } 9966 } 9967 9968 permissionsState.setGlobalGids(mGlobalGids); 9969 9970 final int N = pkg.requestedPermissions.size(); 9971 for (int i=0; i<N; i++) { 9972 final String name = pkg.requestedPermissions.get(i); 9973 final BasePermission bp = mSettings.mPermissions.get(name); 9974 9975 if (DEBUG_INSTALL) { 9976 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9977 } 9978 9979 if (bp == null || bp.packageSetting == null) { 9980 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9981 Slog.w(TAG, "Unknown permission " + name 9982 + " in package " + pkg.packageName); 9983 } 9984 continue; 9985 } 9986 9987 final String perm = bp.name; 9988 boolean allowedSig = false; 9989 int grant = GRANT_DENIED; 9990 9991 // Keep track of app op permissions. 9992 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9993 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9994 if (pkgs == null) { 9995 pkgs = new ArraySet<>(); 9996 mAppOpPermissionPackages.put(bp.name, pkgs); 9997 } 9998 pkgs.add(pkg.packageName); 9999 } 10000 10001 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10002 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10003 >= Build.VERSION_CODES.M; 10004 switch (level) { 10005 case PermissionInfo.PROTECTION_NORMAL: { 10006 // For all apps normal permissions are install time ones. 10007 grant = GRANT_INSTALL; 10008 } break; 10009 10010 case PermissionInfo.PROTECTION_DANGEROUS: { 10011 // If a permission review is required for legacy apps we represent 10012 // their permissions as always granted runtime ones since we need 10013 // to keep the review required permission flag per user while an 10014 // install permission's state is shared across all users. 10015 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10016 // For legacy apps dangerous permissions are install time ones. 10017 grant = GRANT_INSTALL; 10018 } else if (origPermissions.hasInstallPermission(bp.name)) { 10019 // For legacy apps that became modern, install becomes runtime. 10020 grant = GRANT_UPGRADE; 10021 } else if (mPromoteSystemApps 10022 && isSystemApp(ps) 10023 && mExistingSystemPackages.contains(ps.name)) { 10024 // For legacy system apps, install becomes runtime. 10025 // We cannot check hasInstallPermission() for system apps since those 10026 // permissions were granted implicitly and not persisted pre-M. 10027 grant = GRANT_UPGRADE; 10028 } else { 10029 // For modern apps keep runtime permissions unchanged. 10030 grant = GRANT_RUNTIME; 10031 } 10032 } break; 10033 10034 case PermissionInfo.PROTECTION_SIGNATURE: { 10035 // For all apps signature permissions are install time ones. 10036 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10037 if (allowedSig) { 10038 grant = GRANT_INSTALL; 10039 } 10040 } break; 10041 } 10042 10043 if (DEBUG_INSTALL) { 10044 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10045 } 10046 10047 if (grant != GRANT_DENIED) { 10048 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10049 // If this is an existing, non-system package, then 10050 // we can't add any new permissions to it. 10051 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10052 // Except... if this is a permission that was added 10053 // to the platform (note: need to only do this when 10054 // updating the platform). 10055 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10056 grant = GRANT_DENIED; 10057 } 10058 } 10059 } 10060 10061 switch (grant) { 10062 case GRANT_INSTALL: { 10063 // Revoke this as runtime permission to handle the case of 10064 // a runtime permission being downgraded to an install one. 10065 // Also in permission review mode we keep dangerous permissions 10066 // for legacy apps 10067 for (int userId : UserManagerService.getInstance().getUserIds()) { 10068 if (origPermissions.getRuntimePermissionState( 10069 bp.name, userId) != null) { 10070 // Revoke the runtime permission and clear the flags. 10071 origPermissions.revokeRuntimePermission(bp, userId); 10072 origPermissions.updatePermissionFlags(bp, userId, 10073 PackageManager.MASK_PERMISSION_FLAGS, 0); 10074 // If we revoked a permission permission, we have to write. 10075 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10076 changedRuntimePermissionUserIds, userId); 10077 } 10078 } 10079 // Grant an install permission. 10080 if (permissionsState.grantInstallPermission(bp) != 10081 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10082 changedInstallPermission = true; 10083 } 10084 } break; 10085 10086 case GRANT_RUNTIME: { 10087 // Grant previously granted runtime permissions. 10088 for (int userId : UserManagerService.getInstance().getUserIds()) { 10089 PermissionState permissionState = origPermissions 10090 .getRuntimePermissionState(bp.name, userId); 10091 int flags = permissionState != null 10092 ? permissionState.getFlags() : 0; 10093 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10094 if (permissionsState.grantRuntimePermission(bp, userId) == 10095 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10096 // If we cannot put the permission as it was, we have to write. 10097 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10098 changedRuntimePermissionUserIds, userId); 10099 } 10100 // If the app supports runtime permissions no need for a review. 10101 if (Build.PERMISSIONS_REVIEW_REQUIRED 10102 && appSupportsRuntimePermissions 10103 && (flags & PackageManager 10104 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10105 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10106 // Since we changed the flags, we have to write. 10107 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10108 changedRuntimePermissionUserIds, userId); 10109 } 10110 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10111 && !appSupportsRuntimePermissions) { 10112 // For legacy apps that need a permission review, every new 10113 // runtime permission is granted but it is pending a review. 10114 // We also need to review only platform defined runtime 10115 // permissions as these are the only ones the platform knows 10116 // how to disable the API to simulate revocation as legacy 10117 // apps don't expect to run with revoked permissions. 10118 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10119 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10120 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10121 // We changed the flags, hence have to write. 10122 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10123 changedRuntimePermissionUserIds, userId); 10124 } 10125 } 10126 if (permissionsState.grantRuntimePermission(bp, userId) 10127 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10128 // We changed the permission, hence have to write. 10129 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10130 changedRuntimePermissionUserIds, userId); 10131 } 10132 } 10133 // Propagate the permission flags. 10134 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10135 } 10136 } break; 10137 10138 case GRANT_UPGRADE: { 10139 // Grant runtime permissions for a previously held install permission. 10140 PermissionState permissionState = origPermissions 10141 .getInstallPermissionState(bp.name); 10142 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10143 10144 if (origPermissions.revokeInstallPermission(bp) 10145 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10146 // We will be transferring the permission flags, so clear them. 10147 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10148 PackageManager.MASK_PERMISSION_FLAGS, 0); 10149 changedInstallPermission = true; 10150 } 10151 10152 // If the permission is not to be promoted to runtime we ignore it and 10153 // also its other flags as they are not applicable to install permissions. 10154 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10155 for (int userId : currentUserIds) { 10156 if (permissionsState.grantRuntimePermission(bp, userId) != 10157 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10158 // Transfer the permission flags. 10159 permissionsState.updatePermissionFlags(bp, userId, 10160 flags, flags); 10161 // If we granted the permission, we have to write. 10162 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10163 changedRuntimePermissionUserIds, userId); 10164 } 10165 } 10166 } 10167 } break; 10168 10169 default: { 10170 if (packageOfInterest == null 10171 || packageOfInterest.equals(pkg.packageName)) { 10172 Slog.w(TAG, "Not granting permission " + perm 10173 + " to package " + pkg.packageName 10174 + " because it was previously installed without"); 10175 } 10176 } break; 10177 } 10178 } else { 10179 if (permissionsState.revokeInstallPermission(bp) != 10180 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10181 // Also drop the permission flags. 10182 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10183 PackageManager.MASK_PERMISSION_FLAGS, 0); 10184 changedInstallPermission = true; 10185 Slog.i(TAG, "Un-granting permission " + perm 10186 + " from package " + pkg.packageName 10187 + " (protectionLevel=" + bp.protectionLevel 10188 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10189 + ")"); 10190 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10191 // Don't print warning for app op permissions, since it is fine for them 10192 // not to be granted, there is a UI for the user to decide. 10193 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10194 Slog.w(TAG, "Not granting permission " + perm 10195 + " to package " + pkg.packageName 10196 + " (protectionLevel=" + bp.protectionLevel 10197 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10198 + ")"); 10199 } 10200 } 10201 } 10202 } 10203 10204 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10205 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10206 // This is the first that we have heard about this package, so the 10207 // permissions we have now selected are fixed until explicitly 10208 // changed. 10209 ps.installPermissionsFixed = true; 10210 } 10211 10212 // Persist the runtime permissions state for users with changes. If permissions 10213 // were revoked because no app in the shared user declares them we have to 10214 // write synchronously to avoid losing runtime permissions state. 10215 for (int userId : changedRuntimePermissionUserIds) { 10216 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10217 } 10218 10219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10220 } 10221 10222 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10223 boolean allowed = false; 10224 final int NP = PackageParser.NEW_PERMISSIONS.length; 10225 for (int ip=0; ip<NP; ip++) { 10226 final PackageParser.NewPermissionInfo npi 10227 = PackageParser.NEW_PERMISSIONS[ip]; 10228 if (npi.name.equals(perm) 10229 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10230 allowed = true; 10231 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10232 + pkg.packageName); 10233 break; 10234 } 10235 } 10236 return allowed; 10237 } 10238 10239 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10240 BasePermission bp, PermissionsState origPermissions) { 10241 boolean allowed; 10242 allowed = (compareSignatures( 10243 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10244 == PackageManager.SIGNATURE_MATCH) 10245 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10246 == PackageManager.SIGNATURE_MATCH); 10247 if (!allowed && (bp.protectionLevel 10248 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10249 if (isSystemApp(pkg)) { 10250 // For updated system applications, a system permission 10251 // is granted only if it had been defined by the original application. 10252 if (pkg.isUpdatedSystemApp()) { 10253 final PackageSetting sysPs = mSettings 10254 .getDisabledSystemPkgLPr(pkg.packageName); 10255 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10256 // If the original was granted this permission, we take 10257 // that grant decision as read and propagate it to the 10258 // update. 10259 if (sysPs.isPrivileged()) { 10260 allowed = true; 10261 } 10262 } else { 10263 // The system apk may have been updated with an older 10264 // version of the one on the data partition, but which 10265 // granted a new system permission that it didn't have 10266 // before. In this case we do want to allow the app to 10267 // now get the new permission if the ancestral apk is 10268 // privileged to get it. 10269 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10270 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10271 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10272 allowed = true; 10273 break; 10274 } 10275 } 10276 } 10277 // Also if a privileged parent package on the system image or any of 10278 // its children requested a privileged permission, the updated child 10279 // packages can also get the permission. 10280 if (pkg.parentPackage != null) { 10281 final PackageSetting disabledSysParentPs = mSettings 10282 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10283 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10284 && disabledSysParentPs.isPrivileged()) { 10285 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10286 allowed = true; 10287 } else if (disabledSysParentPs.pkg.childPackages != null) { 10288 final int count = disabledSysParentPs.pkg.childPackages.size(); 10289 for (int i = 0; i < count; i++) { 10290 PackageParser.Package disabledSysChildPkg = 10291 disabledSysParentPs.pkg.childPackages.get(i); 10292 if (isPackageRequestingPermission(disabledSysChildPkg, 10293 perm)) { 10294 allowed = true; 10295 break; 10296 } 10297 } 10298 } 10299 } 10300 } 10301 } 10302 } else { 10303 allowed = isPrivilegedApp(pkg); 10304 } 10305 } 10306 } 10307 if (!allowed) { 10308 if (!allowed && (bp.protectionLevel 10309 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10310 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10311 // If this was a previously normal/dangerous permission that got moved 10312 // to a system permission as part of the runtime permission redesign, then 10313 // we still want to blindly grant it to old apps. 10314 allowed = true; 10315 } 10316 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10317 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10318 // If this permission is to be granted to the system installer and 10319 // this app is an installer, then it gets the permission. 10320 allowed = true; 10321 } 10322 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10323 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10324 // If this permission is to be granted to the system verifier and 10325 // this app is a verifier, then it gets the permission. 10326 allowed = true; 10327 } 10328 if (!allowed && (bp.protectionLevel 10329 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10330 && isSystemApp(pkg)) { 10331 // Any pre-installed system app is allowed to get this permission. 10332 allowed = true; 10333 } 10334 if (!allowed && (bp.protectionLevel 10335 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10336 // For development permissions, a development permission 10337 // is granted only if it was already granted. 10338 allowed = origPermissions.hasInstallPermission(perm); 10339 } 10340 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10341 && pkg.packageName.equals(mSetupWizardPackage)) { 10342 // If this permission is to be granted to the system setup wizard and 10343 // this app is a setup wizard, then it gets the permission. 10344 allowed = true; 10345 } 10346 } 10347 return allowed; 10348 } 10349 10350 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10351 final int permCount = pkg.requestedPermissions.size(); 10352 for (int j = 0; j < permCount; j++) { 10353 String requestedPermission = pkg.requestedPermissions.get(j); 10354 if (permission.equals(requestedPermission)) { 10355 return true; 10356 } 10357 } 10358 return false; 10359 } 10360 10361 final class ActivityIntentResolver 10362 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10363 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10364 boolean defaultOnly, int userId) { 10365 if (!sUserManager.exists(userId)) return null; 10366 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10367 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10368 } 10369 10370 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10371 int userId) { 10372 if (!sUserManager.exists(userId)) return null; 10373 mFlags = flags; 10374 return super.queryIntent(intent, resolvedType, 10375 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10376 } 10377 10378 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10379 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10380 if (!sUserManager.exists(userId)) return null; 10381 if (packageActivities == null) { 10382 return null; 10383 } 10384 mFlags = flags; 10385 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10386 final int N = packageActivities.size(); 10387 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10388 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10389 10390 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10391 for (int i = 0; i < N; ++i) { 10392 intentFilters = packageActivities.get(i).intents; 10393 if (intentFilters != null && intentFilters.size() > 0) { 10394 PackageParser.ActivityIntentInfo[] array = 10395 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10396 intentFilters.toArray(array); 10397 listCut.add(array); 10398 } 10399 } 10400 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10401 } 10402 10403 /** 10404 * Finds a privileged activity that matches the specified activity names. 10405 */ 10406 private PackageParser.Activity findMatchingActivity( 10407 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10408 for (PackageParser.Activity sysActivity : activityList) { 10409 if (sysActivity.info.name.equals(activityInfo.name)) { 10410 return sysActivity; 10411 } 10412 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10413 return sysActivity; 10414 } 10415 if (sysActivity.info.targetActivity != null) { 10416 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10417 return sysActivity; 10418 } 10419 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10420 return sysActivity; 10421 } 10422 } 10423 } 10424 return null; 10425 } 10426 10427 public class IterGenerator<E> { 10428 public Iterator<E> generate(ActivityIntentInfo info) { 10429 return null; 10430 } 10431 } 10432 10433 public class ActionIterGenerator extends IterGenerator<String> { 10434 @Override 10435 public Iterator<String> generate(ActivityIntentInfo info) { 10436 return info.actionsIterator(); 10437 } 10438 } 10439 10440 public class CategoriesIterGenerator extends IterGenerator<String> { 10441 @Override 10442 public Iterator<String> generate(ActivityIntentInfo info) { 10443 return info.categoriesIterator(); 10444 } 10445 } 10446 10447 public class SchemesIterGenerator extends IterGenerator<String> { 10448 @Override 10449 public Iterator<String> generate(ActivityIntentInfo info) { 10450 return info.schemesIterator(); 10451 } 10452 } 10453 10454 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10455 @Override 10456 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10457 return info.authoritiesIterator(); 10458 } 10459 } 10460 10461 /** 10462 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10463 * MODIFIED. Do not pass in a list that should not be changed. 10464 */ 10465 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10466 IterGenerator<T> generator, Iterator<T> searchIterator) { 10467 // loop through the set of actions; every one must be found in the intent filter 10468 while (searchIterator.hasNext()) { 10469 // we must have at least one filter in the list to consider a match 10470 if (intentList.size() == 0) { 10471 break; 10472 } 10473 10474 final T searchAction = searchIterator.next(); 10475 10476 // loop through the set of intent filters 10477 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10478 while (intentIter.hasNext()) { 10479 final ActivityIntentInfo intentInfo = intentIter.next(); 10480 boolean selectionFound = false; 10481 10482 // loop through the intent filter's selection criteria; at least one 10483 // of them must match the searched criteria 10484 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10485 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10486 final T intentSelection = intentSelectionIter.next(); 10487 if (intentSelection != null && intentSelection.equals(searchAction)) { 10488 selectionFound = true; 10489 break; 10490 } 10491 } 10492 10493 // the selection criteria wasn't found in this filter's set; this filter 10494 // is not a potential match 10495 if (!selectionFound) { 10496 intentIter.remove(); 10497 } 10498 } 10499 } 10500 } 10501 10502 private boolean isProtectedAction(ActivityIntentInfo filter) { 10503 final Iterator<String> actionsIter = filter.actionsIterator(); 10504 while (actionsIter != null && actionsIter.hasNext()) { 10505 final String filterAction = actionsIter.next(); 10506 if (PROTECTED_ACTIONS.contains(filterAction)) { 10507 return true; 10508 } 10509 } 10510 return false; 10511 } 10512 10513 /** 10514 * Adjusts the priority of the given intent filter according to policy. 10515 * <p> 10516 * <ul> 10517 * <li>The priority for non privileged applications is capped to '0'</li> 10518 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10519 * <li>The priority for unbundled updates to privileged applications is capped to the 10520 * priority defined on the system partition</li> 10521 * </ul> 10522 * <p> 10523 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10524 * allowed to obtain any priority on any action. 10525 */ 10526 private void adjustPriority( 10527 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10528 // nothing to do; priority is fine as-is 10529 if (intent.getPriority() <= 0) { 10530 return; 10531 } 10532 10533 final ActivityInfo activityInfo = intent.activity.info; 10534 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10535 10536 final boolean privilegedApp = 10537 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10538 if (!privilegedApp) { 10539 // non-privileged applications can never define a priority >0 10540 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10541 + " package: " + applicationInfo.packageName 10542 + " activity: " + intent.activity.className 10543 + " origPrio: " + intent.getPriority()); 10544 intent.setPriority(0); 10545 return; 10546 } 10547 10548 if (systemActivities == null) { 10549 // the system package is not disabled; we're parsing the system partition 10550 if (isProtectedAction(intent)) { 10551 if (mDeferProtectedFilters) { 10552 // We can't deal with these just yet. No component should ever obtain a 10553 // >0 priority for a protected actions, with ONE exception -- the setup 10554 // wizard. The setup wizard, however, cannot be known until we're able to 10555 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10556 // until all intent filters have been processed. Chicken, meet egg. 10557 // Let the filter temporarily have a high priority and rectify the 10558 // priorities after all system packages have been scanned. 10559 mProtectedFilters.add(intent); 10560 if (DEBUG_FILTERS) { 10561 Slog.i(TAG, "Protected action; save for later;" 10562 + " package: " + applicationInfo.packageName 10563 + " activity: " + intent.activity.className 10564 + " origPrio: " + intent.getPriority()); 10565 } 10566 return; 10567 } else { 10568 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10569 Slog.i(TAG, "No setup wizard;" 10570 + " All protected intents capped to priority 0"); 10571 } 10572 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10573 if (DEBUG_FILTERS) { 10574 Slog.i(TAG, "Found setup wizard;" 10575 + " allow priority " + intent.getPriority() + ";" 10576 + " package: " + intent.activity.info.packageName 10577 + " activity: " + intent.activity.className 10578 + " priority: " + intent.getPriority()); 10579 } 10580 // setup wizard gets whatever it wants 10581 return; 10582 } 10583 Slog.w(TAG, "Protected action; cap priority to 0;" 10584 + " package: " + intent.activity.info.packageName 10585 + " activity: " + intent.activity.className 10586 + " origPrio: " + intent.getPriority()); 10587 intent.setPriority(0); 10588 return; 10589 } 10590 } 10591 // privileged apps on the system image get whatever priority they request 10592 return; 10593 } 10594 10595 // privileged app unbundled update ... try to find the same activity 10596 final PackageParser.Activity foundActivity = 10597 findMatchingActivity(systemActivities, activityInfo); 10598 if (foundActivity == null) { 10599 // this is a new activity; it cannot obtain >0 priority 10600 if (DEBUG_FILTERS) { 10601 Slog.i(TAG, "New activity; cap priority to 0;" 10602 + " package: " + applicationInfo.packageName 10603 + " activity: " + intent.activity.className 10604 + " origPrio: " + intent.getPriority()); 10605 } 10606 intent.setPriority(0); 10607 return; 10608 } 10609 10610 // found activity, now check for filter equivalence 10611 10612 // a shallow copy is enough; we modify the list, not its contents 10613 final List<ActivityIntentInfo> intentListCopy = 10614 new ArrayList<>(foundActivity.intents); 10615 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10616 10617 // find matching action subsets 10618 final Iterator<String> actionsIterator = intent.actionsIterator(); 10619 if (actionsIterator != null) { 10620 getIntentListSubset( 10621 intentListCopy, new ActionIterGenerator(), actionsIterator); 10622 if (intentListCopy.size() == 0) { 10623 // no more intents to match; we're not equivalent 10624 if (DEBUG_FILTERS) { 10625 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10626 + " package: " + applicationInfo.packageName 10627 + " activity: " + intent.activity.className 10628 + " origPrio: " + intent.getPriority()); 10629 } 10630 intent.setPriority(0); 10631 return; 10632 } 10633 } 10634 10635 // find matching category subsets 10636 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10637 if (categoriesIterator != null) { 10638 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10639 categoriesIterator); 10640 if (intentListCopy.size() == 0) { 10641 // no more intents to match; we're not equivalent 10642 if (DEBUG_FILTERS) { 10643 Slog.i(TAG, "Mismatched category; 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 schemes subsets 10654 final Iterator<String> schemesIterator = intent.schemesIterator(); 10655 if (schemesIterator != null) { 10656 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10657 schemesIterator); 10658 if (intentListCopy.size() == 0) { 10659 // no more intents to match; we're not equivalent 10660 if (DEBUG_FILTERS) { 10661 Slog.i(TAG, "Mismatched scheme; 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 authorities subsets 10672 final Iterator<IntentFilter.AuthorityEntry> 10673 authoritiesIterator = intent.authoritiesIterator(); 10674 if (authoritiesIterator != null) { 10675 getIntentListSubset(intentListCopy, 10676 new AuthoritiesIterGenerator(), 10677 authoritiesIterator); 10678 if (intentListCopy.size() == 0) { 10679 // no more intents to match; we're not equivalent 10680 if (DEBUG_FILTERS) { 10681 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10682 + " package: " + applicationInfo.packageName 10683 + " activity: " + intent.activity.className 10684 + " origPrio: " + intent.getPriority()); 10685 } 10686 intent.setPriority(0); 10687 return; 10688 } 10689 } 10690 10691 // we found matching filter(s); app gets the max priority of all intents 10692 int cappedPriority = 0; 10693 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10694 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10695 } 10696 if (intent.getPriority() > cappedPriority) { 10697 if (DEBUG_FILTERS) { 10698 Slog.i(TAG, "Found matching filter(s);" 10699 + " cap priority to " + cappedPriority + ";" 10700 + " package: " + applicationInfo.packageName 10701 + " activity: " + intent.activity.className 10702 + " origPrio: " + intent.getPriority()); 10703 } 10704 intent.setPriority(cappedPriority); 10705 return; 10706 } 10707 // all this for nothing; the requested priority was <= what was on the system 10708 } 10709 10710 public final void addActivity(PackageParser.Activity a, String type) { 10711 mActivities.put(a.getComponentName(), a); 10712 if (DEBUG_SHOW_INFO) 10713 Log.v( 10714 TAG, " " + type + " " + 10715 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10716 if (DEBUG_SHOW_INFO) 10717 Log.v(TAG, " Class=" + a.info.name); 10718 final int NI = a.intents.size(); 10719 for (int j=0; j<NI; j++) { 10720 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10721 if ("activity".equals(type)) { 10722 final PackageSetting ps = 10723 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10724 final List<PackageParser.Activity> systemActivities = 10725 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10726 adjustPriority(systemActivities, intent); 10727 } 10728 if (DEBUG_SHOW_INFO) { 10729 Log.v(TAG, " IntentFilter:"); 10730 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10731 } 10732 if (!intent.debugCheck()) { 10733 Log.w(TAG, "==> For Activity " + a.info.name); 10734 } 10735 addFilter(intent); 10736 } 10737 } 10738 10739 public final void removeActivity(PackageParser.Activity a, String type) { 10740 mActivities.remove(a.getComponentName()); 10741 if (DEBUG_SHOW_INFO) { 10742 Log.v(TAG, " " + type + " " 10743 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10744 : a.info.name) + ":"); 10745 Log.v(TAG, " Class=" + a.info.name); 10746 } 10747 final int NI = a.intents.size(); 10748 for (int j=0; j<NI; j++) { 10749 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10750 if (DEBUG_SHOW_INFO) { 10751 Log.v(TAG, " IntentFilter:"); 10752 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10753 } 10754 removeFilter(intent); 10755 } 10756 } 10757 10758 @Override 10759 protected boolean allowFilterResult( 10760 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10761 ActivityInfo filterAi = filter.activity.info; 10762 for (int i=dest.size()-1; i>=0; i--) { 10763 ActivityInfo destAi = dest.get(i).activityInfo; 10764 if (destAi.name == filterAi.name 10765 && destAi.packageName == filterAi.packageName) { 10766 return false; 10767 } 10768 } 10769 return true; 10770 } 10771 10772 @Override 10773 protected ActivityIntentInfo[] newArray(int size) { 10774 return new ActivityIntentInfo[size]; 10775 } 10776 10777 @Override 10778 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10779 if (!sUserManager.exists(userId)) return true; 10780 PackageParser.Package p = filter.activity.owner; 10781 if (p != null) { 10782 PackageSetting ps = (PackageSetting)p.mExtras; 10783 if (ps != null) { 10784 // System apps are never considered stopped for purposes of 10785 // filtering, because there may be no way for the user to 10786 // actually re-launch them. 10787 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10788 && ps.getStopped(userId); 10789 } 10790 } 10791 return false; 10792 } 10793 10794 @Override 10795 protected boolean isPackageForFilter(String packageName, 10796 PackageParser.ActivityIntentInfo info) { 10797 return packageName.equals(info.activity.owner.packageName); 10798 } 10799 10800 @Override 10801 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10802 int match, int userId) { 10803 if (!sUserManager.exists(userId)) return null; 10804 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10805 return null; 10806 } 10807 final PackageParser.Activity activity = info.activity; 10808 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10809 if (ps == null) { 10810 return null; 10811 } 10812 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10813 ps.readUserState(userId), userId); 10814 if (ai == null) { 10815 return null; 10816 } 10817 final ResolveInfo res = new ResolveInfo(); 10818 res.activityInfo = ai; 10819 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10820 res.filter = info; 10821 } 10822 if (info != null) { 10823 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10824 } 10825 res.priority = info.getPriority(); 10826 res.preferredOrder = activity.owner.mPreferredOrder; 10827 //System.out.println("Result: " + res.activityInfo.className + 10828 // " = " + res.priority); 10829 res.match = match; 10830 res.isDefault = info.hasDefault; 10831 res.labelRes = info.labelRes; 10832 res.nonLocalizedLabel = info.nonLocalizedLabel; 10833 if (userNeedsBadging(userId)) { 10834 res.noResourceId = true; 10835 } else { 10836 res.icon = info.icon; 10837 } 10838 res.iconResourceId = info.icon; 10839 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10840 return res; 10841 } 10842 10843 @Override 10844 protected void sortResults(List<ResolveInfo> results) { 10845 Collections.sort(results, mResolvePrioritySorter); 10846 } 10847 10848 @Override 10849 protected void dumpFilter(PrintWriter out, String prefix, 10850 PackageParser.ActivityIntentInfo filter) { 10851 out.print(prefix); out.print( 10852 Integer.toHexString(System.identityHashCode(filter.activity))); 10853 out.print(' '); 10854 filter.activity.printComponentShortName(out); 10855 out.print(" filter "); 10856 out.println(Integer.toHexString(System.identityHashCode(filter))); 10857 } 10858 10859 @Override 10860 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10861 return filter.activity; 10862 } 10863 10864 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10865 PackageParser.Activity activity = (PackageParser.Activity)label; 10866 out.print(prefix); out.print( 10867 Integer.toHexString(System.identityHashCode(activity))); 10868 out.print(' '); 10869 activity.printComponentShortName(out); 10870 if (count > 1) { 10871 out.print(" ("); out.print(count); out.print(" filters)"); 10872 } 10873 out.println(); 10874 } 10875 10876 // Keys are String (activity class name), values are Activity. 10877 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10878 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10879 private int mFlags; 10880 } 10881 10882 private final class ServiceIntentResolver 10883 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10884 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10885 boolean defaultOnly, int userId) { 10886 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10887 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10888 } 10889 10890 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10891 int userId) { 10892 if (!sUserManager.exists(userId)) return null; 10893 mFlags = flags; 10894 return super.queryIntent(intent, resolvedType, 10895 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10896 } 10897 10898 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10899 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10900 if (!sUserManager.exists(userId)) return null; 10901 if (packageServices == null) { 10902 return null; 10903 } 10904 mFlags = flags; 10905 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10906 final int N = packageServices.size(); 10907 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10908 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10909 10910 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10911 for (int i = 0; i < N; ++i) { 10912 intentFilters = packageServices.get(i).intents; 10913 if (intentFilters != null && intentFilters.size() > 0) { 10914 PackageParser.ServiceIntentInfo[] array = 10915 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10916 intentFilters.toArray(array); 10917 listCut.add(array); 10918 } 10919 } 10920 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10921 } 10922 10923 public final void addService(PackageParser.Service s) { 10924 mServices.put(s.getComponentName(), s); 10925 if (DEBUG_SHOW_INFO) { 10926 Log.v(TAG, " " 10927 + (s.info.nonLocalizedLabel != null 10928 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10929 Log.v(TAG, " Class=" + s.info.name); 10930 } 10931 final int NI = s.intents.size(); 10932 int j; 10933 for (j=0; j<NI; j++) { 10934 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10935 if (DEBUG_SHOW_INFO) { 10936 Log.v(TAG, " IntentFilter:"); 10937 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10938 } 10939 if (!intent.debugCheck()) { 10940 Log.w(TAG, "==> For Service " + s.info.name); 10941 } 10942 addFilter(intent); 10943 } 10944 } 10945 10946 public final void removeService(PackageParser.Service s) { 10947 mServices.remove(s.getComponentName()); 10948 if (DEBUG_SHOW_INFO) { 10949 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10950 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10951 Log.v(TAG, " Class=" + s.info.name); 10952 } 10953 final int NI = s.intents.size(); 10954 int j; 10955 for (j=0; j<NI; j++) { 10956 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10957 if (DEBUG_SHOW_INFO) { 10958 Log.v(TAG, " IntentFilter:"); 10959 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10960 } 10961 removeFilter(intent); 10962 } 10963 } 10964 10965 @Override 10966 protected boolean allowFilterResult( 10967 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10968 ServiceInfo filterSi = filter.service.info; 10969 for (int i=dest.size()-1; i>=0; i--) { 10970 ServiceInfo destAi = dest.get(i).serviceInfo; 10971 if (destAi.name == filterSi.name 10972 && destAi.packageName == filterSi.packageName) { 10973 return false; 10974 } 10975 } 10976 return true; 10977 } 10978 10979 @Override 10980 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10981 return new PackageParser.ServiceIntentInfo[size]; 10982 } 10983 10984 @Override 10985 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10986 if (!sUserManager.exists(userId)) return true; 10987 PackageParser.Package p = filter.service.owner; 10988 if (p != null) { 10989 PackageSetting ps = (PackageSetting)p.mExtras; 10990 if (ps != null) { 10991 // System apps are never considered stopped for purposes of 10992 // filtering, because there may be no way for the user to 10993 // actually re-launch them. 10994 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10995 && ps.getStopped(userId); 10996 } 10997 } 10998 return false; 10999 } 11000 11001 @Override 11002 protected boolean isPackageForFilter(String packageName, 11003 PackageParser.ServiceIntentInfo info) { 11004 return packageName.equals(info.service.owner.packageName); 11005 } 11006 11007 @Override 11008 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11009 int match, int userId) { 11010 if (!sUserManager.exists(userId)) return null; 11011 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11012 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11013 return null; 11014 } 11015 final PackageParser.Service service = info.service; 11016 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11017 if (ps == null) { 11018 return null; 11019 } 11020 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11021 ps.readUserState(userId), userId); 11022 if (si == null) { 11023 return null; 11024 } 11025 final ResolveInfo res = new ResolveInfo(); 11026 res.serviceInfo = si; 11027 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11028 res.filter = filter; 11029 } 11030 res.priority = info.getPriority(); 11031 res.preferredOrder = service.owner.mPreferredOrder; 11032 res.match = match; 11033 res.isDefault = info.hasDefault; 11034 res.labelRes = info.labelRes; 11035 res.nonLocalizedLabel = info.nonLocalizedLabel; 11036 res.icon = info.icon; 11037 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11038 return res; 11039 } 11040 11041 @Override 11042 protected void sortResults(List<ResolveInfo> results) { 11043 Collections.sort(results, mResolvePrioritySorter); 11044 } 11045 11046 @Override 11047 protected void dumpFilter(PrintWriter out, String prefix, 11048 PackageParser.ServiceIntentInfo filter) { 11049 out.print(prefix); out.print( 11050 Integer.toHexString(System.identityHashCode(filter.service))); 11051 out.print(' '); 11052 filter.service.printComponentShortName(out); 11053 out.print(" filter "); 11054 out.println(Integer.toHexString(System.identityHashCode(filter))); 11055 } 11056 11057 @Override 11058 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11059 return filter.service; 11060 } 11061 11062 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11063 PackageParser.Service service = (PackageParser.Service)label; 11064 out.print(prefix); out.print( 11065 Integer.toHexString(System.identityHashCode(service))); 11066 out.print(' '); 11067 service.printComponentShortName(out); 11068 if (count > 1) { 11069 out.print(" ("); out.print(count); out.print(" filters)"); 11070 } 11071 out.println(); 11072 } 11073 11074// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11075// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11076// final List<ResolveInfo> retList = Lists.newArrayList(); 11077// while (i.hasNext()) { 11078// final ResolveInfo resolveInfo = (ResolveInfo) i; 11079// if (isEnabledLP(resolveInfo.serviceInfo)) { 11080// retList.add(resolveInfo); 11081// } 11082// } 11083// return retList; 11084// } 11085 11086 // Keys are String (activity class name), values are Activity. 11087 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11088 = new ArrayMap<ComponentName, PackageParser.Service>(); 11089 private int mFlags; 11090 }; 11091 11092 private final class ProviderIntentResolver 11093 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11095 boolean defaultOnly, int userId) { 11096 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11097 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11098 } 11099 11100 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11101 int userId) { 11102 if (!sUserManager.exists(userId)) 11103 return null; 11104 mFlags = flags; 11105 return super.queryIntent(intent, resolvedType, 11106 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11107 } 11108 11109 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11110 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11111 if (!sUserManager.exists(userId)) 11112 return null; 11113 if (packageProviders == null) { 11114 return null; 11115 } 11116 mFlags = flags; 11117 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11118 final int N = packageProviders.size(); 11119 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11120 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11121 11122 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11123 for (int i = 0; i < N; ++i) { 11124 intentFilters = packageProviders.get(i).intents; 11125 if (intentFilters != null && intentFilters.size() > 0) { 11126 PackageParser.ProviderIntentInfo[] array = 11127 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11128 intentFilters.toArray(array); 11129 listCut.add(array); 11130 } 11131 } 11132 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11133 } 11134 11135 public final void addProvider(PackageParser.Provider p) { 11136 if (mProviders.containsKey(p.getComponentName())) { 11137 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11138 return; 11139 } 11140 11141 mProviders.put(p.getComponentName(), p); 11142 if (DEBUG_SHOW_INFO) { 11143 Log.v(TAG, " " 11144 + (p.info.nonLocalizedLabel != null 11145 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11146 Log.v(TAG, " Class=" + p.info.name); 11147 } 11148 final int NI = p.intents.size(); 11149 int j; 11150 for (j = 0; j < NI; j++) { 11151 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11152 if (DEBUG_SHOW_INFO) { 11153 Log.v(TAG, " IntentFilter:"); 11154 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11155 } 11156 if (!intent.debugCheck()) { 11157 Log.w(TAG, "==> For Provider " + p.info.name); 11158 } 11159 addFilter(intent); 11160 } 11161 } 11162 11163 public final void removeProvider(PackageParser.Provider p) { 11164 mProviders.remove(p.getComponentName()); 11165 if (DEBUG_SHOW_INFO) { 11166 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11167 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11168 Log.v(TAG, " Class=" + p.info.name); 11169 } 11170 final int NI = p.intents.size(); 11171 int j; 11172 for (j = 0; j < NI; j++) { 11173 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11174 if (DEBUG_SHOW_INFO) { 11175 Log.v(TAG, " IntentFilter:"); 11176 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11177 } 11178 removeFilter(intent); 11179 } 11180 } 11181 11182 @Override 11183 protected boolean allowFilterResult( 11184 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11185 ProviderInfo filterPi = filter.provider.info; 11186 for (int i = dest.size() - 1; i >= 0; i--) { 11187 ProviderInfo destPi = dest.get(i).providerInfo; 11188 if (destPi.name == filterPi.name 11189 && destPi.packageName == filterPi.packageName) { 11190 return false; 11191 } 11192 } 11193 return true; 11194 } 11195 11196 @Override 11197 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11198 return new PackageParser.ProviderIntentInfo[size]; 11199 } 11200 11201 @Override 11202 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11203 if (!sUserManager.exists(userId)) 11204 return true; 11205 PackageParser.Package p = filter.provider.owner; 11206 if (p != null) { 11207 PackageSetting ps = (PackageSetting) p.mExtras; 11208 if (ps != null) { 11209 // System apps are never considered stopped for purposes of 11210 // filtering, because there may be no way for the user to 11211 // actually re-launch them. 11212 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11213 && ps.getStopped(userId); 11214 } 11215 } 11216 return false; 11217 } 11218 11219 @Override 11220 protected boolean isPackageForFilter(String packageName, 11221 PackageParser.ProviderIntentInfo info) { 11222 return packageName.equals(info.provider.owner.packageName); 11223 } 11224 11225 @Override 11226 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11227 int match, int userId) { 11228 if (!sUserManager.exists(userId)) 11229 return null; 11230 final PackageParser.ProviderIntentInfo info = filter; 11231 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11232 return null; 11233 } 11234 final PackageParser.Provider provider = info.provider; 11235 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11236 if (ps == null) { 11237 return null; 11238 } 11239 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11240 ps.readUserState(userId), userId); 11241 if (pi == null) { 11242 return null; 11243 } 11244 final ResolveInfo res = new ResolveInfo(); 11245 res.providerInfo = pi; 11246 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11247 res.filter = filter; 11248 } 11249 res.priority = info.getPriority(); 11250 res.preferredOrder = provider.owner.mPreferredOrder; 11251 res.match = match; 11252 res.isDefault = info.hasDefault; 11253 res.labelRes = info.labelRes; 11254 res.nonLocalizedLabel = info.nonLocalizedLabel; 11255 res.icon = info.icon; 11256 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11257 return res; 11258 } 11259 11260 @Override 11261 protected void sortResults(List<ResolveInfo> results) { 11262 Collections.sort(results, mResolvePrioritySorter); 11263 } 11264 11265 @Override 11266 protected void dumpFilter(PrintWriter out, String prefix, 11267 PackageParser.ProviderIntentInfo filter) { 11268 out.print(prefix); 11269 out.print( 11270 Integer.toHexString(System.identityHashCode(filter.provider))); 11271 out.print(' '); 11272 filter.provider.printComponentShortName(out); 11273 out.print(" filter "); 11274 out.println(Integer.toHexString(System.identityHashCode(filter))); 11275 } 11276 11277 @Override 11278 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11279 return filter.provider; 11280 } 11281 11282 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11283 PackageParser.Provider provider = (PackageParser.Provider)label; 11284 out.print(prefix); out.print( 11285 Integer.toHexString(System.identityHashCode(provider))); 11286 out.print(' '); 11287 provider.printComponentShortName(out); 11288 if (count > 1) { 11289 out.print(" ("); out.print(count); out.print(" filters)"); 11290 } 11291 out.println(); 11292 } 11293 11294 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11295 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11296 private int mFlags; 11297 } 11298 11299 private static final class EphemeralIntentResolver 11300 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11301 @Override 11302 protected EphemeralResolveIntentInfo[] newArray(int size) { 11303 return new EphemeralResolveIntentInfo[size]; 11304 } 11305 11306 @Override 11307 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11308 return true; 11309 } 11310 11311 @Override 11312 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11313 int userId) { 11314 if (!sUserManager.exists(userId)) { 11315 return null; 11316 } 11317 return info.getEphemeralResolveInfo(); 11318 } 11319 } 11320 11321 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11322 new Comparator<ResolveInfo>() { 11323 public int compare(ResolveInfo r1, ResolveInfo r2) { 11324 int v1 = r1.priority; 11325 int v2 = r2.priority; 11326 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11327 if (v1 != v2) { 11328 return (v1 > v2) ? -1 : 1; 11329 } 11330 v1 = r1.preferredOrder; 11331 v2 = r2.preferredOrder; 11332 if (v1 != v2) { 11333 return (v1 > v2) ? -1 : 1; 11334 } 11335 if (r1.isDefault != r2.isDefault) { 11336 return r1.isDefault ? -1 : 1; 11337 } 11338 v1 = r1.match; 11339 v2 = r2.match; 11340 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11341 if (v1 != v2) { 11342 return (v1 > v2) ? -1 : 1; 11343 } 11344 if (r1.system != r2.system) { 11345 return r1.system ? -1 : 1; 11346 } 11347 if (r1.activityInfo != null) { 11348 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11349 } 11350 if (r1.serviceInfo != null) { 11351 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11352 } 11353 if (r1.providerInfo != null) { 11354 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11355 } 11356 return 0; 11357 } 11358 }; 11359 11360 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11361 new Comparator<ProviderInfo>() { 11362 public int compare(ProviderInfo p1, ProviderInfo p2) { 11363 final int v1 = p1.initOrder; 11364 final int v2 = p2.initOrder; 11365 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11366 } 11367 }; 11368 11369 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11370 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11371 final int[] userIds) { 11372 mHandler.post(new Runnable() { 11373 @Override 11374 public void run() { 11375 try { 11376 final IActivityManager am = ActivityManagerNative.getDefault(); 11377 if (am == null) return; 11378 final int[] resolvedUserIds; 11379 if (userIds == null) { 11380 resolvedUserIds = am.getRunningUserIds(); 11381 } else { 11382 resolvedUserIds = userIds; 11383 } 11384 for (int id : resolvedUserIds) { 11385 final Intent intent = new Intent(action, 11386 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11387 if (extras != null) { 11388 intent.putExtras(extras); 11389 } 11390 if (targetPkg != null) { 11391 intent.setPackage(targetPkg); 11392 } 11393 // Modify the UID when posting to other users 11394 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11395 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11396 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11397 intent.putExtra(Intent.EXTRA_UID, uid); 11398 } 11399 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11400 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11401 if (DEBUG_BROADCASTS) { 11402 RuntimeException here = new RuntimeException("here"); 11403 here.fillInStackTrace(); 11404 Slog.d(TAG, "Sending to user " + id + ": " 11405 + intent.toShortString(false, true, false, false) 11406 + " " + intent.getExtras(), here); 11407 } 11408 am.broadcastIntent(null, intent, null, finishedReceiver, 11409 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11410 null, finishedReceiver != null, false, id); 11411 } 11412 } catch (RemoteException ex) { 11413 } 11414 } 11415 }); 11416 } 11417 11418 /** 11419 * Check if the external storage media is available. This is true if there 11420 * is a mounted external storage medium or if the external storage is 11421 * emulated. 11422 */ 11423 private boolean isExternalMediaAvailable() { 11424 return mMediaMounted || Environment.isExternalStorageEmulated(); 11425 } 11426 11427 @Override 11428 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11429 // writer 11430 synchronized (mPackages) { 11431 if (!isExternalMediaAvailable()) { 11432 // If the external storage is no longer mounted at this point, 11433 // the caller may not have been able to delete all of this 11434 // packages files and can not delete any more. Bail. 11435 return null; 11436 } 11437 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11438 if (lastPackage != null) { 11439 pkgs.remove(lastPackage); 11440 } 11441 if (pkgs.size() > 0) { 11442 return pkgs.get(0); 11443 } 11444 } 11445 return null; 11446 } 11447 11448 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11449 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11450 userId, andCode ? 1 : 0, packageName); 11451 if (mSystemReady) { 11452 msg.sendToTarget(); 11453 } else { 11454 if (mPostSystemReadyMessages == null) { 11455 mPostSystemReadyMessages = new ArrayList<>(); 11456 } 11457 mPostSystemReadyMessages.add(msg); 11458 } 11459 } 11460 11461 void startCleaningPackages() { 11462 // reader 11463 if (!isExternalMediaAvailable()) { 11464 return; 11465 } 11466 synchronized (mPackages) { 11467 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11468 return; 11469 } 11470 } 11471 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11472 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11473 IActivityManager am = ActivityManagerNative.getDefault(); 11474 if (am != null) { 11475 try { 11476 am.startService(null, intent, null, mContext.getOpPackageName(), 11477 UserHandle.USER_SYSTEM); 11478 } catch (RemoteException e) { 11479 } 11480 } 11481 } 11482 11483 @Override 11484 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11485 int installFlags, String installerPackageName, int userId) { 11486 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11487 11488 final int callingUid = Binder.getCallingUid(); 11489 enforceCrossUserPermission(callingUid, userId, 11490 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11491 11492 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11493 try { 11494 if (observer != null) { 11495 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11496 } 11497 } catch (RemoteException re) { 11498 } 11499 return; 11500 } 11501 11502 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11503 installFlags |= PackageManager.INSTALL_FROM_ADB; 11504 11505 } else { 11506 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11507 // about installerPackageName. 11508 11509 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11510 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11511 } 11512 11513 UserHandle user; 11514 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11515 user = UserHandle.ALL; 11516 } else { 11517 user = new UserHandle(userId); 11518 } 11519 11520 // Only system components can circumvent runtime permissions when installing. 11521 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11522 && mContext.checkCallingOrSelfPermission(Manifest.permission 11523 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11524 throw new SecurityException("You need the " 11525 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11526 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11527 } 11528 11529 final File originFile = new File(originPath); 11530 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11531 11532 final Message msg = mHandler.obtainMessage(INIT_COPY); 11533 final VerificationInfo verificationInfo = new VerificationInfo( 11534 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11535 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11536 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11537 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11538 null /*certificates*/); 11539 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11540 msg.obj = params; 11541 11542 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11543 System.identityHashCode(msg.obj)); 11544 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11545 System.identityHashCode(msg.obj)); 11546 11547 mHandler.sendMessage(msg); 11548 } 11549 11550 void installStage(String packageName, File stagedDir, String stagedCid, 11551 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11552 String installerPackageName, int installerUid, UserHandle user, 11553 Certificate[][] certificates) { 11554 if (DEBUG_EPHEMERAL) { 11555 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11556 Slog.d(TAG, "Ephemeral install of " + packageName); 11557 } 11558 } 11559 final VerificationInfo verificationInfo = new VerificationInfo( 11560 sessionParams.originatingUri, sessionParams.referrerUri, 11561 sessionParams.originatingUid, installerUid); 11562 11563 final OriginInfo origin; 11564 if (stagedDir != null) { 11565 origin = OriginInfo.fromStagedFile(stagedDir); 11566 } else { 11567 origin = OriginInfo.fromStagedContainer(stagedCid); 11568 } 11569 11570 final Message msg = mHandler.obtainMessage(INIT_COPY); 11571 final InstallParams params = new InstallParams(origin, null, observer, 11572 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11573 verificationInfo, user, sessionParams.abiOverride, 11574 sessionParams.grantedRuntimePermissions, certificates); 11575 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11576 msg.obj = params; 11577 11578 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11579 System.identityHashCode(msg.obj)); 11580 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11581 System.identityHashCode(msg.obj)); 11582 11583 mHandler.sendMessage(msg); 11584 } 11585 11586 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11587 int userId) { 11588 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11589 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11590 } 11591 11592 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11593 int appId, int userId) { 11594 Bundle extras = new Bundle(1); 11595 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11596 11597 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11598 packageName, extras, 0, null, null, new int[] {userId}); 11599 try { 11600 IActivityManager am = ActivityManagerNative.getDefault(); 11601 if (isSystem && am.isUserRunning(userId, 0)) { 11602 // The just-installed/enabled app is bundled on the system, so presumed 11603 // to be able to run automatically without needing an explicit launch. 11604 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11605 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11606 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11607 .setPackage(packageName); 11608 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11609 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11610 } 11611 } catch (RemoteException e) { 11612 // shouldn't happen 11613 Slog.w(TAG, "Unable to bootstrap installed package", e); 11614 } 11615 } 11616 11617 @Override 11618 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11619 int userId) { 11620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11621 PackageSetting pkgSetting; 11622 final int uid = Binder.getCallingUid(); 11623 enforceCrossUserPermission(uid, userId, 11624 true /* requireFullPermission */, true /* checkShell */, 11625 "setApplicationHiddenSetting for user " + userId); 11626 11627 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11628 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11629 return false; 11630 } 11631 11632 long callingId = Binder.clearCallingIdentity(); 11633 try { 11634 boolean sendAdded = false; 11635 boolean sendRemoved = false; 11636 // writer 11637 synchronized (mPackages) { 11638 pkgSetting = mSettings.mPackages.get(packageName); 11639 if (pkgSetting == null) { 11640 return false; 11641 } 11642 if (pkgSetting.getHidden(userId) != hidden) { 11643 pkgSetting.setHidden(hidden, userId); 11644 mSettings.writePackageRestrictionsLPr(userId); 11645 if (hidden) { 11646 sendRemoved = true; 11647 } else { 11648 sendAdded = true; 11649 } 11650 } 11651 } 11652 if (sendAdded) { 11653 sendPackageAddedForUser(packageName, pkgSetting, userId); 11654 return true; 11655 } 11656 if (sendRemoved) { 11657 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11658 "hiding pkg"); 11659 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11660 return true; 11661 } 11662 } finally { 11663 Binder.restoreCallingIdentity(callingId); 11664 } 11665 return false; 11666 } 11667 11668 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11669 int userId) { 11670 final PackageRemovedInfo info = new PackageRemovedInfo(); 11671 info.removedPackage = packageName; 11672 info.removedUsers = new int[] {userId}; 11673 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11674 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11675 } 11676 11677 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11678 if (pkgList.length > 0) { 11679 Bundle extras = new Bundle(1); 11680 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11681 11682 sendPackageBroadcast( 11683 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11684 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11685 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11686 new int[] {userId}); 11687 } 11688 } 11689 11690 /** 11691 * Returns true if application is not found or there was an error. Otherwise it returns 11692 * the hidden state of the package for the given user. 11693 */ 11694 @Override 11695 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11696 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11697 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11698 true /* requireFullPermission */, false /* checkShell */, 11699 "getApplicationHidden for user " + userId); 11700 PackageSetting pkgSetting; 11701 long callingId = Binder.clearCallingIdentity(); 11702 try { 11703 // writer 11704 synchronized (mPackages) { 11705 pkgSetting = mSettings.mPackages.get(packageName); 11706 if (pkgSetting == null) { 11707 return true; 11708 } 11709 return pkgSetting.getHidden(userId); 11710 } 11711 } finally { 11712 Binder.restoreCallingIdentity(callingId); 11713 } 11714 } 11715 11716 /** 11717 * @hide 11718 */ 11719 @Override 11720 public int installExistingPackageAsUser(String packageName, int userId) { 11721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11722 null); 11723 PackageSetting pkgSetting; 11724 final int uid = Binder.getCallingUid(); 11725 enforceCrossUserPermission(uid, userId, 11726 true /* requireFullPermission */, true /* checkShell */, 11727 "installExistingPackage for user " + userId); 11728 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11729 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11730 } 11731 11732 long callingId = Binder.clearCallingIdentity(); 11733 try { 11734 boolean installed = false; 11735 11736 // writer 11737 synchronized (mPackages) { 11738 pkgSetting = mSettings.mPackages.get(packageName); 11739 if (pkgSetting == null) { 11740 return PackageManager.INSTALL_FAILED_INVALID_URI; 11741 } 11742 if (!pkgSetting.getInstalled(userId)) { 11743 pkgSetting.setInstalled(true, userId); 11744 pkgSetting.setHidden(false, userId); 11745 mSettings.writePackageRestrictionsLPr(userId); 11746 installed = true; 11747 } 11748 } 11749 11750 if (installed) { 11751 if (pkgSetting.pkg != null) { 11752 synchronized (mInstallLock) { 11753 // We don't need to freeze for a brand new install 11754 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11755 } 11756 } 11757 sendPackageAddedForUser(packageName, pkgSetting, userId); 11758 } 11759 } finally { 11760 Binder.restoreCallingIdentity(callingId); 11761 } 11762 11763 return PackageManager.INSTALL_SUCCEEDED; 11764 } 11765 11766 boolean isUserRestricted(int userId, String restrictionKey) { 11767 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11768 if (restrictions.getBoolean(restrictionKey, false)) { 11769 Log.w(TAG, "User is restricted: " + restrictionKey); 11770 return true; 11771 } 11772 return false; 11773 } 11774 11775 @Override 11776 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11777 int userId) { 11778 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11779 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11780 true /* requireFullPermission */, true /* checkShell */, 11781 "setPackagesSuspended for user " + userId); 11782 11783 if (ArrayUtils.isEmpty(packageNames)) { 11784 return packageNames; 11785 } 11786 11787 // List of package names for whom the suspended state has changed. 11788 List<String> changedPackages = new ArrayList<>(packageNames.length); 11789 // List of package names for whom the suspended state is not set as requested in this 11790 // method. 11791 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11792 long callingId = Binder.clearCallingIdentity(); 11793 try { 11794 for (int i = 0; i < packageNames.length; i++) { 11795 String packageName = packageNames[i]; 11796 boolean changed = false; 11797 final int appId; 11798 synchronized (mPackages) { 11799 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11800 if (pkgSetting == null) { 11801 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11802 + "\". Skipping suspending/un-suspending."); 11803 unactionedPackages.add(packageName); 11804 continue; 11805 } 11806 appId = pkgSetting.appId; 11807 if (pkgSetting.getSuspended(userId) != suspended) { 11808 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11809 unactionedPackages.add(packageName); 11810 continue; 11811 } 11812 pkgSetting.setSuspended(suspended, userId); 11813 mSettings.writePackageRestrictionsLPr(userId); 11814 changed = true; 11815 changedPackages.add(packageName); 11816 } 11817 } 11818 11819 if (changed && suspended) { 11820 killApplication(packageName, UserHandle.getUid(userId, appId), 11821 "suspending package"); 11822 } 11823 } 11824 } finally { 11825 Binder.restoreCallingIdentity(callingId); 11826 } 11827 11828 if (!changedPackages.isEmpty()) { 11829 sendPackagesSuspendedForUser(changedPackages.toArray( 11830 new String[changedPackages.size()]), userId, suspended); 11831 } 11832 11833 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11834 } 11835 11836 @Override 11837 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11838 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11839 true /* requireFullPermission */, false /* checkShell */, 11840 "isPackageSuspendedForUser for user " + userId); 11841 synchronized (mPackages) { 11842 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11843 if (pkgSetting == null) { 11844 throw new IllegalArgumentException("Unknown target package: " + packageName); 11845 } 11846 return pkgSetting.getSuspended(userId); 11847 } 11848 } 11849 11850 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11851 if (isPackageDeviceAdmin(packageName, userId)) { 11852 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11853 + "\": has an active device admin"); 11854 return false; 11855 } 11856 11857 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11858 if (packageName.equals(activeLauncherPackageName)) { 11859 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11860 + "\": contains the active launcher"); 11861 return false; 11862 } 11863 11864 if (packageName.equals(mRequiredInstallerPackage)) { 11865 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11866 + "\": required for package installation"); 11867 return false; 11868 } 11869 11870 if (packageName.equals(mRequiredVerifierPackage)) { 11871 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11872 + "\": required for package verification"); 11873 return false; 11874 } 11875 11876 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11877 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11878 + "\": is the default dialer"); 11879 return false; 11880 } 11881 11882 return true; 11883 } 11884 11885 private String getActiveLauncherPackageName(int userId) { 11886 Intent intent = new Intent(Intent.ACTION_MAIN); 11887 intent.addCategory(Intent.CATEGORY_HOME); 11888 ResolveInfo resolveInfo = resolveIntent( 11889 intent, 11890 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11891 PackageManager.MATCH_DEFAULT_ONLY, 11892 userId); 11893 11894 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11895 } 11896 11897 private String getDefaultDialerPackageName(int userId) { 11898 synchronized (mPackages) { 11899 return mSettings.getDefaultDialerPackageNameLPw(userId); 11900 } 11901 } 11902 11903 @Override 11904 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11905 mContext.enforceCallingOrSelfPermission( 11906 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11907 "Only package verification agents can verify applications"); 11908 11909 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11910 final PackageVerificationResponse response = new PackageVerificationResponse( 11911 verificationCode, Binder.getCallingUid()); 11912 msg.arg1 = id; 11913 msg.obj = response; 11914 mHandler.sendMessage(msg); 11915 } 11916 11917 @Override 11918 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11919 long millisecondsToDelay) { 11920 mContext.enforceCallingOrSelfPermission( 11921 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11922 "Only package verification agents can extend verification timeouts"); 11923 11924 final PackageVerificationState state = mPendingVerification.get(id); 11925 final PackageVerificationResponse response = new PackageVerificationResponse( 11926 verificationCodeAtTimeout, Binder.getCallingUid()); 11927 11928 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11929 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11930 } 11931 if (millisecondsToDelay < 0) { 11932 millisecondsToDelay = 0; 11933 } 11934 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11935 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11936 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11937 } 11938 11939 if ((state != null) && !state.timeoutExtended()) { 11940 state.extendTimeout(); 11941 11942 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11943 msg.arg1 = id; 11944 msg.obj = response; 11945 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11946 } 11947 } 11948 11949 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11950 int verificationCode, UserHandle user) { 11951 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11952 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11953 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11954 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11955 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11956 11957 mContext.sendBroadcastAsUser(intent, user, 11958 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11959 } 11960 11961 private ComponentName matchComponentForVerifier(String packageName, 11962 List<ResolveInfo> receivers) { 11963 ActivityInfo targetReceiver = null; 11964 11965 final int NR = receivers.size(); 11966 for (int i = 0; i < NR; i++) { 11967 final ResolveInfo info = receivers.get(i); 11968 if (info.activityInfo == null) { 11969 continue; 11970 } 11971 11972 if (packageName.equals(info.activityInfo.packageName)) { 11973 targetReceiver = info.activityInfo; 11974 break; 11975 } 11976 } 11977 11978 if (targetReceiver == null) { 11979 return null; 11980 } 11981 11982 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11983 } 11984 11985 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11986 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11987 if (pkgInfo.verifiers.length == 0) { 11988 return null; 11989 } 11990 11991 final int N = pkgInfo.verifiers.length; 11992 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11993 for (int i = 0; i < N; i++) { 11994 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11995 11996 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11997 receivers); 11998 if (comp == null) { 11999 continue; 12000 } 12001 12002 final int verifierUid = getUidForVerifier(verifierInfo); 12003 if (verifierUid == -1) { 12004 continue; 12005 } 12006 12007 if (DEBUG_VERIFY) { 12008 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12009 + " with the correct signature"); 12010 } 12011 sufficientVerifiers.add(comp); 12012 verificationState.addSufficientVerifier(verifierUid); 12013 } 12014 12015 return sufficientVerifiers; 12016 } 12017 12018 private int getUidForVerifier(VerifierInfo verifierInfo) { 12019 synchronized (mPackages) { 12020 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12021 if (pkg == null) { 12022 return -1; 12023 } else if (pkg.mSignatures.length != 1) { 12024 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12025 + " has more than one signature; ignoring"); 12026 return -1; 12027 } 12028 12029 /* 12030 * If the public key of the package's signature does not match 12031 * our expected public key, then this is a different package and 12032 * we should skip. 12033 */ 12034 12035 final byte[] expectedPublicKey; 12036 try { 12037 final Signature verifierSig = pkg.mSignatures[0]; 12038 final PublicKey publicKey = verifierSig.getPublicKey(); 12039 expectedPublicKey = publicKey.getEncoded(); 12040 } catch (CertificateException e) { 12041 return -1; 12042 } 12043 12044 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12045 12046 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12047 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12048 + " does not have the expected public key; ignoring"); 12049 return -1; 12050 } 12051 12052 return pkg.applicationInfo.uid; 12053 } 12054 } 12055 12056 @Override 12057 public void finishPackageInstall(int token, boolean didLaunch) { 12058 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12059 12060 if (DEBUG_INSTALL) { 12061 Slog.v(TAG, "BM finishing package install for " + token); 12062 } 12063 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12064 12065 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12066 mHandler.sendMessage(msg); 12067 } 12068 12069 /** 12070 * Get the verification agent timeout. 12071 * 12072 * @return verification timeout in milliseconds 12073 */ 12074 private long getVerificationTimeout() { 12075 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12076 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12077 DEFAULT_VERIFICATION_TIMEOUT); 12078 } 12079 12080 /** 12081 * Get the default verification agent response code. 12082 * 12083 * @return default verification response code 12084 */ 12085 private int getDefaultVerificationResponse() { 12086 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12087 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12088 DEFAULT_VERIFICATION_RESPONSE); 12089 } 12090 12091 /** 12092 * Check whether or not package verification has been enabled. 12093 * 12094 * @return true if verification should be performed 12095 */ 12096 private boolean isVerificationEnabled(int userId, int installFlags) { 12097 if (!DEFAULT_VERIFY_ENABLE) { 12098 return false; 12099 } 12100 // Ephemeral apps don't get the full verification treatment 12101 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12102 if (DEBUG_EPHEMERAL) { 12103 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12104 } 12105 return false; 12106 } 12107 12108 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12109 12110 // Check if installing from ADB 12111 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12112 // Do not run verification in a test harness environment 12113 if (ActivityManager.isRunningInTestHarness()) { 12114 return false; 12115 } 12116 if (ensureVerifyAppsEnabled) { 12117 return true; 12118 } 12119 // Check if the developer does not want package verification for ADB installs 12120 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12121 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12122 return false; 12123 } 12124 } 12125 12126 if (ensureVerifyAppsEnabled) { 12127 return true; 12128 } 12129 12130 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12131 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12132 } 12133 12134 @Override 12135 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12136 throws RemoteException { 12137 mContext.enforceCallingOrSelfPermission( 12138 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12139 "Only intentfilter verification agents can verify applications"); 12140 12141 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12142 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12143 Binder.getCallingUid(), verificationCode, failedDomains); 12144 msg.arg1 = id; 12145 msg.obj = response; 12146 mHandler.sendMessage(msg); 12147 } 12148 12149 @Override 12150 public int getIntentVerificationStatus(String packageName, int userId) { 12151 synchronized (mPackages) { 12152 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12153 } 12154 } 12155 12156 @Override 12157 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12158 mContext.enforceCallingOrSelfPermission( 12159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12160 12161 boolean result = false; 12162 synchronized (mPackages) { 12163 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12164 } 12165 if (result) { 12166 scheduleWritePackageRestrictionsLocked(userId); 12167 } 12168 return result; 12169 } 12170 12171 @Override 12172 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12173 String packageName) { 12174 synchronized (mPackages) { 12175 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12176 } 12177 } 12178 12179 @Override 12180 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12181 if (TextUtils.isEmpty(packageName)) { 12182 return ParceledListSlice.emptyList(); 12183 } 12184 synchronized (mPackages) { 12185 PackageParser.Package pkg = mPackages.get(packageName); 12186 if (pkg == null || pkg.activities == null) { 12187 return ParceledListSlice.emptyList(); 12188 } 12189 final int count = pkg.activities.size(); 12190 ArrayList<IntentFilter> result = new ArrayList<>(); 12191 for (int n=0; n<count; n++) { 12192 PackageParser.Activity activity = pkg.activities.get(n); 12193 if (activity.intents != null && activity.intents.size() > 0) { 12194 result.addAll(activity.intents); 12195 } 12196 } 12197 return new ParceledListSlice<>(result); 12198 } 12199 } 12200 12201 @Override 12202 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12203 mContext.enforceCallingOrSelfPermission( 12204 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12205 12206 synchronized (mPackages) { 12207 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12208 if (packageName != null) { 12209 result |= updateIntentVerificationStatus(packageName, 12210 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12211 userId); 12212 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12213 packageName, userId); 12214 } 12215 return result; 12216 } 12217 } 12218 12219 @Override 12220 public String getDefaultBrowserPackageName(int userId) { 12221 synchronized (mPackages) { 12222 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12223 } 12224 } 12225 12226 /** 12227 * Get the "allow unknown sources" setting. 12228 * 12229 * @return the current "allow unknown sources" setting 12230 */ 12231 private int getUnknownSourcesSettings() { 12232 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12233 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12234 -1); 12235 } 12236 12237 @Override 12238 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12239 final int uid = Binder.getCallingUid(); 12240 // writer 12241 synchronized (mPackages) { 12242 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12243 if (targetPackageSetting == null) { 12244 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12245 } 12246 12247 PackageSetting installerPackageSetting; 12248 if (installerPackageName != null) { 12249 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12250 if (installerPackageSetting == null) { 12251 throw new IllegalArgumentException("Unknown installer package: " 12252 + installerPackageName); 12253 } 12254 } else { 12255 installerPackageSetting = null; 12256 } 12257 12258 Signature[] callerSignature; 12259 Object obj = mSettings.getUserIdLPr(uid); 12260 if (obj != null) { 12261 if (obj instanceof SharedUserSetting) { 12262 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12263 } else if (obj instanceof PackageSetting) { 12264 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12265 } else { 12266 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12267 } 12268 } else { 12269 throw new SecurityException("Unknown calling UID: " + uid); 12270 } 12271 12272 // Verify: can't set installerPackageName to a package that is 12273 // not signed with the same cert as the caller. 12274 if (installerPackageSetting != null) { 12275 if (compareSignatures(callerSignature, 12276 installerPackageSetting.signatures.mSignatures) 12277 != PackageManager.SIGNATURE_MATCH) { 12278 throw new SecurityException( 12279 "Caller does not have same cert as new installer package " 12280 + installerPackageName); 12281 } 12282 } 12283 12284 // Verify: if target already has an installer package, it must 12285 // be signed with the same cert as the caller. 12286 if (targetPackageSetting.installerPackageName != null) { 12287 PackageSetting setting = mSettings.mPackages.get( 12288 targetPackageSetting.installerPackageName); 12289 // If the currently set package isn't valid, then it's always 12290 // okay to change it. 12291 if (setting != null) { 12292 if (compareSignatures(callerSignature, 12293 setting.signatures.mSignatures) 12294 != PackageManager.SIGNATURE_MATCH) { 12295 throw new SecurityException( 12296 "Caller does not have same cert as old installer package " 12297 + targetPackageSetting.installerPackageName); 12298 } 12299 } 12300 } 12301 12302 // Okay! 12303 targetPackageSetting.installerPackageName = installerPackageName; 12304 if (installerPackageName != null) { 12305 mSettings.mInstallerPackages.add(installerPackageName); 12306 } 12307 scheduleWriteSettingsLocked(); 12308 } 12309 } 12310 12311 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12312 // Queue up an async operation since the package installation may take a little while. 12313 mHandler.post(new Runnable() { 12314 public void run() { 12315 mHandler.removeCallbacks(this); 12316 // Result object to be returned 12317 PackageInstalledInfo res = new PackageInstalledInfo(); 12318 res.setReturnCode(currentStatus); 12319 res.uid = -1; 12320 res.pkg = null; 12321 res.removedInfo = null; 12322 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12323 args.doPreInstall(res.returnCode); 12324 synchronized (mInstallLock) { 12325 installPackageTracedLI(args, res); 12326 } 12327 args.doPostInstall(res.returnCode, res.uid); 12328 } 12329 12330 // A restore should be performed at this point if (a) the install 12331 // succeeded, (b) the operation is not an update, and (c) the new 12332 // package has not opted out of backup participation. 12333 final boolean update = res.removedInfo != null 12334 && res.removedInfo.removedPackage != null; 12335 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12336 boolean doRestore = !update 12337 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12338 12339 // Set up the post-install work request bookkeeping. This will be used 12340 // and cleaned up by the post-install event handling regardless of whether 12341 // there's a restore pass performed. Token values are >= 1. 12342 int token; 12343 if (mNextInstallToken < 0) mNextInstallToken = 1; 12344 token = mNextInstallToken++; 12345 12346 PostInstallData data = new PostInstallData(args, res); 12347 mRunningInstalls.put(token, data); 12348 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12349 12350 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12351 // Pass responsibility to the Backup Manager. It will perform a 12352 // restore if appropriate, then pass responsibility back to the 12353 // Package Manager to run the post-install observer callbacks 12354 // and broadcasts. 12355 IBackupManager bm = IBackupManager.Stub.asInterface( 12356 ServiceManager.getService(Context.BACKUP_SERVICE)); 12357 if (bm != null) { 12358 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12359 + " to BM for possible restore"); 12360 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12361 try { 12362 // TODO: http://b/22388012 12363 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12364 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12365 } else { 12366 doRestore = false; 12367 } 12368 } catch (RemoteException e) { 12369 // can't happen; the backup manager is local 12370 } catch (Exception e) { 12371 Slog.e(TAG, "Exception trying to enqueue restore", e); 12372 doRestore = false; 12373 } 12374 } else { 12375 Slog.e(TAG, "Backup Manager not found!"); 12376 doRestore = false; 12377 } 12378 } 12379 12380 if (!doRestore) { 12381 // No restore possible, or the Backup Manager was mysteriously not 12382 // available -- just fire the post-install work request directly. 12383 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12384 12385 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12386 12387 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12388 mHandler.sendMessage(msg); 12389 } 12390 } 12391 }); 12392 } 12393 12394 /** 12395 * Callback from PackageSettings whenever an app is first transitioned out of the 12396 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12397 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12398 * here whether the app is the target of an ongoing install, and only send the 12399 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12400 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12401 * handling. 12402 */ 12403 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12404 // Serialize this with the rest of the install-process message chain. In the 12405 // restore-at-install case, this Runnable will necessarily run before the 12406 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12407 // are coherent. In the non-restore case, the app has already completed install 12408 // and been launched through some other means, so it is not in a problematic 12409 // state for observers to see the FIRST_LAUNCH signal. 12410 mHandler.post(new Runnable() { 12411 @Override 12412 public void run() { 12413 for (int i = 0; i < mRunningInstalls.size(); i++) { 12414 final PostInstallData data = mRunningInstalls.valueAt(i); 12415 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12416 // right package; but is it for the right user? 12417 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12418 if (userId == data.res.newUsers[uIndex]) { 12419 if (DEBUG_BACKUP) { 12420 Slog.i(TAG, "Package " + pkgName 12421 + " being restored so deferring FIRST_LAUNCH"); 12422 } 12423 return; 12424 } 12425 } 12426 } 12427 } 12428 // didn't find it, so not being restored 12429 if (DEBUG_BACKUP) { 12430 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12431 } 12432 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12433 } 12434 }); 12435 } 12436 12437 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12438 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12439 installerPkg, null, userIds); 12440 } 12441 12442 private abstract class HandlerParams { 12443 private static final int MAX_RETRIES = 4; 12444 12445 /** 12446 * Number of times startCopy() has been attempted and had a non-fatal 12447 * error. 12448 */ 12449 private int mRetries = 0; 12450 12451 /** User handle for the user requesting the information or installation. */ 12452 private final UserHandle mUser; 12453 String traceMethod; 12454 int traceCookie; 12455 12456 HandlerParams(UserHandle user) { 12457 mUser = user; 12458 } 12459 12460 UserHandle getUser() { 12461 return mUser; 12462 } 12463 12464 HandlerParams setTraceMethod(String traceMethod) { 12465 this.traceMethod = traceMethod; 12466 return this; 12467 } 12468 12469 HandlerParams setTraceCookie(int traceCookie) { 12470 this.traceCookie = traceCookie; 12471 return this; 12472 } 12473 12474 final boolean startCopy() { 12475 boolean res; 12476 try { 12477 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12478 12479 if (++mRetries > MAX_RETRIES) { 12480 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12481 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12482 handleServiceError(); 12483 return false; 12484 } else { 12485 handleStartCopy(); 12486 res = true; 12487 } 12488 } catch (RemoteException e) { 12489 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12490 mHandler.sendEmptyMessage(MCS_RECONNECT); 12491 res = false; 12492 } 12493 handleReturnCode(); 12494 return res; 12495 } 12496 12497 final void serviceError() { 12498 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12499 handleServiceError(); 12500 handleReturnCode(); 12501 } 12502 12503 abstract void handleStartCopy() throws RemoteException; 12504 abstract void handleServiceError(); 12505 abstract void handleReturnCode(); 12506 } 12507 12508 class MeasureParams extends HandlerParams { 12509 private final PackageStats mStats; 12510 private boolean mSuccess; 12511 12512 private final IPackageStatsObserver mObserver; 12513 12514 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12515 super(new UserHandle(stats.userHandle)); 12516 mObserver = observer; 12517 mStats = stats; 12518 } 12519 12520 @Override 12521 public String toString() { 12522 return "MeasureParams{" 12523 + Integer.toHexString(System.identityHashCode(this)) 12524 + " " + mStats.packageName + "}"; 12525 } 12526 12527 @Override 12528 void handleStartCopy() throws RemoteException { 12529 synchronized (mInstallLock) { 12530 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12531 } 12532 12533 if (mSuccess) { 12534 final boolean mounted; 12535 if (Environment.isExternalStorageEmulated()) { 12536 mounted = true; 12537 } else { 12538 final String status = Environment.getExternalStorageState(); 12539 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12540 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12541 } 12542 12543 if (mounted) { 12544 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12545 12546 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12547 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12548 12549 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12550 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12551 12552 // Always subtract cache size, since it's a subdirectory 12553 mStats.externalDataSize -= mStats.externalCacheSize; 12554 12555 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12556 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12557 12558 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12559 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12560 } 12561 } 12562 } 12563 12564 @Override 12565 void handleReturnCode() { 12566 if (mObserver != null) { 12567 try { 12568 mObserver.onGetStatsCompleted(mStats, mSuccess); 12569 } catch (RemoteException e) { 12570 Slog.i(TAG, "Observer no longer exists."); 12571 } 12572 } 12573 } 12574 12575 @Override 12576 void handleServiceError() { 12577 Slog.e(TAG, "Could not measure application " + mStats.packageName 12578 + " external storage"); 12579 } 12580 } 12581 12582 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12583 throws RemoteException { 12584 long result = 0; 12585 for (File path : paths) { 12586 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12587 } 12588 return result; 12589 } 12590 12591 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12592 for (File path : paths) { 12593 try { 12594 mcs.clearDirectory(path.getAbsolutePath()); 12595 } catch (RemoteException e) { 12596 } 12597 } 12598 } 12599 12600 static class OriginInfo { 12601 /** 12602 * Location where install is coming from, before it has been 12603 * copied/renamed into place. This could be a single monolithic APK 12604 * file, or a cluster directory. This location may be untrusted. 12605 */ 12606 final File file; 12607 final String cid; 12608 12609 /** 12610 * Flag indicating that {@link #file} or {@link #cid} has already been 12611 * staged, meaning downstream users don't need to defensively copy the 12612 * contents. 12613 */ 12614 final boolean staged; 12615 12616 /** 12617 * Flag indicating that {@link #file} or {@link #cid} is an already 12618 * installed app that is being moved. 12619 */ 12620 final boolean existing; 12621 12622 final String resolvedPath; 12623 final File resolvedFile; 12624 12625 static OriginInfo fromNothing() { 12626 return new OriginInfo(null, null, false, false); 12627 } 12628 12629 static OriginInfo fromUntrustedFile(File file) { 12630 return new OriginInfo(file, null, false, false); 12631 } 12632 12633 static OriginInfo fromExistingFile(File file) { 12634 return new OriginInfo(file, null, false, true); 12635 } 12636 12637 static OriginInfo fromStagedFile(File file) { 12638 return new OriginInfo(file, null, true, false); 12639 } 12640 12641 static OriginInfo fromStagedContainer(String cid) { 12642 return new OriginInfo(null, cid, true, false); 12643 } 12644 12645 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12646 this.file = file; 12647 this.cid = cid; 12648 this.staged = staged; 12649 this.existing = existing; 12650 12651 if (cid != null) { 12652 resolvedPath = PackageHelper.getSdDir(cid); 12653 resolvedFile = new File(resolvedPath); 12654 } else if (file != null) { 12655 resolvedPath = file.getAbsolutePath(); 12656 resolvedFile = file; 12657 } else { 12658 resolvedPath = null; 12659 resolvedFile = null; 12660 } 12661 } 12662 } 12663 12664 static class MoveInfo { 12665 final int moveId; 12666 final String fromUuid; 12667 final String toUuid; 12668 final String packageName; 12669 final String dataAppName; 12670 final int appId; 12671 final String seinfo; 12672 final int targetSdkVersion; 12673 12674 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12675 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12676 this.moveId = moveId; 12677 this.fromUuid = fromUuid; 12678 this.toUuid = toUuid; 12679 this.packageName = packageName; 12680 this.dataAppName = dataAppName; 12681 this.appId = appId; 12682 this.seinfo = seinfo; 12683 this.targetSdkVersion = targetSdkVersion; 12684 } 12685 } 12686 12687 static class VerificationInfo { 12688 /** A constant used to indicate that a uid value is not present. */ 12689 public static final int NO_UID = -1; 12690 12691 /** URI referencing where the package was downloaded from. */ 12692 final Uri originatingUri; 12693 12694 /** HTTP referrer URI associated with the originatingURI. */ 12695 final Uri referrer; 12696 12697 /** UID of the application that the install request originated from. */ 12698 final int originatingUid; 12699 12700 /** UID of application requesting the install */ 12701 final int installerUid; 12702 12703 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12704 this.originatingUri = originatingUri; 12705 this.referrer = referrer; 12706 this.originatingUid = originatingUid; 12707 this.installerUid = installerUid; 12708 } 12709 } 12710 12711 class InstallParams extends HandlerParams { 12712 final OriginInfo origin; 12713 final MoveInfo move; 12714 final IPackageInstallObserver2 observer; 12715 int installFlags; 12716 final String installerPackageName; 12717 final String volumeUuid; 12718 private InstallArgs mArgs; 12719 private int mRet; 12720 final String packageAbiOverride; 12721 final String[] grantedRuntimePermissions; 12722 final VerificationInfo verificationInfo; 12723 final Certificate[][] certificates; 12724 12725 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12726 int installFlags, String installerPackageName, String volumeUuid, 12727 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12728 String[] grantedPermissions, Certificate[][] certificates) { 12729 super(user); 12730 this.origin = origin; 12731 this.move = move; 12732 this.observer = observer; 12733 this.installFlags = installFlags; 12734 this.installerPackageName = installerPackageName; 12735 this.volumeUuid = volumeUuid; 12736 this.verificationInfo = verificationInfo; 12737 this.packageAbiOverride = packageAbiOverride; 12738 this.grantedRuntimePermissions = grantedPermissions; 12739 this.certificates = certificates; 12740 } 12741 12742 @Override 12743 public String toString() { 12744 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12745 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12746 } 12747 12748 private int installLocationPolicy(PackageInfoLite pkgLite) { 12749 String packageName = pkgLite.packageName; 12750 int installLocation = pkgLite.installLocation; 12751 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12752 // reader 12753 synchronized (mPackages) { 12754 // Currently installed package which the new package is attempting to replace or 12755 // null if no such package is installed. 12756 PackageParser.Package installedPkg = mPackages.get(packageName); 12757 // Package which currently owns the data which the new package will own if installed. 12758 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12759 // will be null whereas dataOwnerPkg will contain information about the package 12760 // which was uninstalled while keeping its data. 12761 PackageParser.Package dataOwnerPkg = installedPkg; 12762 if (dataOwnerPkg == null) { 12763 PackageSetting ps = mSettings.mPackages.get(packageName); 12764 if (ps != null) { 12765 dataOwnerPkg = ps.pkg; 12766 } 12767 } 12768 12769 if (dataOwnerPkg != null) { 12770 // If installed, the package will get access to data left on the device by its 12771 // predecessor. As a security measure, this is permited only if this is not a 12772 // version downgrade or if the predecessor package is marked as debuggable and 12773 // a downgrade is explicitly requested. 12774 // 12775 // On debuggable platform builds, downgrades are permitted even for 12776 // non-debuggable packages to make testing easier. Debuggable platform builds do 12777 // not offer security guarantees and thus it's OK to disable some security 12778 // mechanisms to make debugging/testing easier on those builds. However, even on 12779 // debuggable builds downgrades of packages are permitted only if requested via 12780 // installFlags. This is because we aim to keep the behavior of debuggable 12781 // platform builds as close as possible to the behavior of non-debuggable 12782 // platform builds. 12783 final boolean downgradeRequested = 12784 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12785 final boolean packageDebuggable = 12786 (dataOwnerPkg.applicationInfo.flags 12787 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12788 final boolean downgradePermitted = 12789 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12790 if (!downgradePermitted) { 12791 try { 12792 checkDowngrade(dataOwnerPkg, pkgLite); 12793 } catch (PackageManagerException e) { 12794 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12795 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12796 } 12797 } 12798 } 12799 12800 if (installedPkg != null) { 12801 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12802 // Check for updated system application. 12803 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12804 if (onSd) { 12805 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12806 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12807 } 12808 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12809 } else { 12810 if (onSd) { 12811 // Install flag overrides everything. 12812 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12813 } 12814 // If current upgrade specifies particular preference 12815 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12816 // Application explicitly specified internal. 12817 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12818 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12819 // App explictly prefers external. Let policy decide 12820 } else { 12821 // Prefer previous location 12822 if (isExternal(installedPkg)) { 12823 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12824 } 12825 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12826 } 12827 } 12828 } else { 12829 // Invalid install. Return error code 12830 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12831 } 12832 } 12833 } 12834 // All the special cases have been taken care of. 12835 // Return result based on recommended install location. 12836 if (onSd) { 12837 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12838 } 12839 return pkgLite.recommendedInstallLocation; 12840 } 12841 12842 /* 12843 * Invoke remote method to get package information and install 12844 * location values. Override install location based on default 12845 * policy if needed and then create install arguments based 12846 * on the install location. 12847 */ 12848 public void handleStartCopy() throws RemoteException { 12849 int ret = PackageManager.INSTALL_SUCCEEDED; 12850 12851 // If we're already staged, we've firmly committed to an install location 12852 if (origin.staged) { 12853 if (origin.file != null) { 12854 installFlags |= PackageManager.INSTALL_INTERNAL; 12855 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12856 } else if (origin.cid != null) { 12857 installFlags |= PackageManager.INSTALL_EXTERNAL; 12858 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12859 } else { 12860 throw new IllegalStateException("Invalid stage location"); 12861 } 12862 } 12863 12864 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12865 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12866 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12867 PackageInfoLite pkgLite = null; 12868 12869 if (onInt && onSd) { 12870 // Check if both bits are set. 12871 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12872 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12873 } else if (onSd && ephemeral) { 12874 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12875 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12876 } else { 12877 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12878 packageAbiOverride); 12879 12880 if (DEBUG_EPHEMERAL && ephemeral) { 12881 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12882 } 12883 12884 /* 12885 * If we have too little free space, try to free cache 12886 * before giving up. 12887 */ 12888 if (!origin.staged && pkgLite.recommendedInstallLocation 12889 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12890 // TODO: focus freeing disk space on the target device 12891 final StorageManager storage = StorageManager.from(mContext); 12892 final long lowThreshold = storage.getStorageLowBytes( 12893 Environment.getDataDirectory()); 12894 12895 final long sizeBytes = mContainerService.calculateInstalledSize( 12896 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12897 12898 try { 12899 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12900 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12901 installFlags, packageAbiOverride); 12902 } catch (InstallerException e) { 12903 Slog.w(TAG, "Failed to free cache", e); 12904 } 12905 12906 /* 12907 * The cache free must have deleted the file we 12908 * downloaded to install. 12909 * 12910 * TODO: fix the "freeCache" call to not delete 12911 * the file we care about. 12912 */ 12913 if (pkgLite.recommendedInstallLocation 12914 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12915 pkgLite.recommendedInstallLocation 12916 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12917 } 12918 } 12919 } 12920 12921 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12922 int loc = pkgLite.recommendedInstallLocation; 12923 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12924 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12925 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12926 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12927 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12928 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12929 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12930 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12931 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12932 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12933 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12934 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12935 } else { 12936 // Override with defaults if needed. 12937 loc = installLocationPolicy(pkgLite); 12938 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12939 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12940 } else if (!onSd && !onInt) { 12941 // Override install location with flags 12942 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12943 // Set the flag to install on external media. 12944 installFlags |= PackageManager.INSTALL_EXTERNAL; 12945 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12946 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12947 if (DEBUG_EPHEMERAL) { 12948 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12949 } 12950 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12951 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12952 |PackageManager.INSTALL_INTERNAL); 12953 } else { 12954 // Make sure the flag for installing on external 12955 // media is unset 12956 installFlags |= PackageManager.INSTALL_INTERNAL; 12957 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12958 } 12959 } 12960 } 12961 } 12962 12963 final InstallArgs args = createInstallArgs(this); 12964 mArgs = args; 12965 12966 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12967 // TODO: http://b/22976637 12968 // Apps installed for "all" users use the device owner to verify the app 12969 UserHandle verifierUser = getUser(); 12970 if (verifierUser == UserHandle.ALL) { 12971 verifierUser = UserHandle.SYSTEM; 12972 } 12973 12974 /* 12975 * Determine if we have any installed package verifiers. If we 12976 * do, then we'll defer to them to verify the packages. 12977 */ 12978 final int requiredUid = mRequiredVerifierPackage == null ? -1 12979 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12980 verifierUser.getIdentifier()); 12981 if (!origin.existing && requiredUid != -1 12982 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12983 final Intent verification = new Intent( 12984 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12985 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12986 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12987 PACKAGE_MIME_TYPE); 12988 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12989 12990 // Query all live verifiers based on current user state 12991 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12992 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12993 12994 if (DEBUG_VERIFY) { 12995 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12996 + verification.toString() + " with " + pkgLite.verifiers.length 12997 + " optional verifiers"); 12998 } 12999 13000 final int verificationId = mPendingVerificationToken++; 13001 13002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13003 13004 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13005 installerPackageName); 13006 13007 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13008 installFlags); 13009 13010 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13011 pkgLite.packageName); 13012 13013 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13014 pkgLite.versionCode); 13015 13016 if (verificationInfo != null) { 13017 if (verificationInfo.originatingUri != null) { 13018 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13019 verificationInfo.originatingUri); 13020 } 13021 if (verificationInfo.referrer != null) { 13022 verification.putExtra(Intent.EXTRA_REFERRER, 13023 verificationInfo.referrer); 13024 } 13025 if (verificationInfo.originatingUid >= 0) { 13026 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13027 verificationInfo.originatingUid); 13028 } 13029 if (verificationInfo.installerUid >= 0) { 13030 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13031 verificationInfo.installerUid); 13032 } 13033 } 13034 13035 final PackageVerificationState verificationState = new PackageVerificationState( 13036 requiredUid, args); 13037 13038 mPendingVerification.append(verificationId, verificationState); 13039 13040 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13041 receivers, verificationState); 13042 13043 /* 13044 * If any sufficient verifiers were listed in the package 13045 * manifest, attempt to ask them. 13046 */ 13047 if (sufficientVerifiers != null) { 13048 final int N = sufficientVerifiers.size(); 13049 if (N == 0) { 13050 Slog.i(TAG, "Additional verifiers required, but none installed."); 13051 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13052 } else { 13053 for (int i = 0; i < N; i++) { 13054 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13055 13056 final Intent sufficientIntent = new Intent(verification); 13057 sufficientIntent.setComponent(verifierComponent); 13058 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13059 } 13060 } 13061 } 13062 13063 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13064 mRequiredVerifierPackage, receivers); 13065 if (ret == PackageManager.INSTALL_SUCCEEDED 13066 && mRequiredVerifierPackage != null) { 13067 Trace.asyncTraceBegin( 13068 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13069 /* 13070 * Send the intent to the required verification agent, 13071 * but only start the verification timeout after the 13072 * target BroadcastReceivers have run. 13073 */ 13074 verification.setComponent(requiredVerifierComponent); 13075 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13076 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13077 new BroadcastReceiver() { 13078 @Override 13079 public void onReceive(Context context, Intent intent) { 13080 final Message msg = mHandler 13081 .obtainMessage(CHECK_PENDING_VERIFICATION); 13082 msg.arg1 = verificationId; 13083 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13084 } 13085 }, null, 0, null, null); 13086 13087 /* 13088 * We don't want the copy to proceed until verification 13089 * succeeds, so null out this field. 13090 */ 13091 mArgs = null; 13092 } 13093 } else { 13094 /* 13095 * No package verification is enabled, so immediately start 13096 * the remote call to initiate copy using temporary file. 13097 */ 13098 ret = args.copyApk(mContainerService, true); 13099 } 13100 } 13101 13102 mRet = ret; 13103 } 13104 13105 @Override 13106 void handleReturnCode() { 13107 // If mArgs is null, then MCS couldn't be reached. When it 13108 // reconnects, it will try again to install. At that point, this 13109 // will succeed. 13110 if (mArgs != null) { 13111 processPendingInstall(mArgs, mRet); 13112 } 13113 } 13114 13115 @Override 13116 void handleServiceError() { 13117 mArgs = createInstallArgs(this); 13118 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13119 } 13120 13121 public boolean isForwardLocked() { 13122 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13123 } 13124 } 13125 13126 /** 13127 * Used during creation of InstallArgs 13128 * 13129 * @param installFlags package installation flags 13130 * @return true if should be installed on external storage 13131 */ 13132 private static boolean installOnExternalAsec(int installFlags) { 13133 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13134 return false; 13135 } 13136 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13137 return true; 13138 } 13139 return false; 13140 } 13141 13142 /** 13143 * Used during creation of InstallArgs 13144 * 13145 * @param installFlags package installation flags 13146 * @return true if should be installed as forward locked 13147 */ 13148 private static boolean installForwardLocked(int installFlags) { 13149 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13150 } 13151 13152 private InstallArgs createInstallArgs(InstallParams params) { 13153 if (params.move != null) { 13154 return new MoveInstallArgs(params); 13155 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13156 return new AsecInstallArgs(params); 13157 } else { 13158 return new FileInstallArgs(params); 13159 } 13160 } 13161 13162 /** 13163 * Create args that describe an existing installed package. Typically used 13164 * when cleaning up old installs, or used as a move source. 13165 */ 13166 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13167 String resourcePath, String[] instructionSets) { 13168 final boolean isInAsec; 13169 if (installOnExternalAsec(installFlags)) { 13170 /* Apps on SD card are always in ASEC containers. */ 13171 isInAsec = true; 13172 } else if (installForwardLocked(installFlags) 13173 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13174 /* 13175 * Forward-locked apps are only in ASEC containers if they're the 13176 * new style 13177 */ 13178 isInAsec = true; 13179 } else { 13180 isInAsec = false; 13181 } 13182 13183 if (isInAsec) { 13184 return new AsecInstallArgs(codePath, instructionSets, 13185 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13186 } else { 13187 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13188 } 13189 } 13190 13191 static abstract class InstallArgs { 13192 /** @see InstallParams#origin */ 13193 final OriginInfo origin; 13194 /** @see InstallParams#move */ 13195 final MoveInfo move; 13196 13197 final IPackageInstallObserver2 observer; 13198 // Always refers to PackageManager flags only 13199 final int installFlags; 13200 final String installerPackageName; 13201 final String volumeUuid; 13202 final UserHandle user; 13203 final String abiOverride; 13204 final String[] installGrantPermissions; 13205 /** If non-null, drop an async trace when the install completes */ 13206 final String traceMethod; 13207 final int traceCookie; 13208 final Certificate[][] certificates; 13209 13210 // The list of instruction sets supported by this app. This is currently 13211 // only used during the rmdex() phase to clean up resources. We can get rid of this 13212 // if we move dex files under the common app path. 13213 /* nullable */ String[] instructionSets; 13214 13215 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13216 int installFlags, String installerPackageName, String volumeUuid, 13217 UserHandle user, String[] instructionSets, 13218 String abiOverride, String[] installGrantPermissions, 13219 String traceMethod, int traceCookie, Certificate[][] certificates) { 13220 this.origin = origin; 13221 this.move = move; 13222 this.installFlags = installFlags; 13223 this.observer = observer; 13224 this.installerPackageName = installerPackageName; 13225 this.volumeUuid = volumeUuid; 13226 this.user = user; 13227 this.instructionSets = instructionSets; 13228 this.abiOverride = abiOverride; 13229 this.installGrantPermissions = installGrantPermissions; 13230 this.traceMethod = traceMethod; 13231 this.traceCookie = traceCookie; 13232 this.certificates = certificates; 13233 } 13234 13235 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13236 abstract int doPreInstall(int status); 13237 13238 /** 13239 * Rename package into final resting place. All paths on the given 13240 * scanned package should be updated to reflect the rename. 13241 */ 13242 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13243 abstract int doPostInstall(int status, int uid); 13244 13245 /** @see PackageSettingBase#codePathString */ 13246 abstract String getCodePath(); 13247 /** @see PackageSettingBase#resourcePathString */ 13248 abstract String getResourcePath(); 13249 13250 // Need installer lock especially for dex file removal. 13251 abstract void cleanUpResourcesLI(); 13252 abstract boolean doPostDeleteLI(boolean delete); 13253 13254 /** 13255 * Called before the source arguments are copied. This is used mostly 13256 * for MoveParams when it needs to read the source file to put it in the 13257 * destination. 13258 */ 13259 int doPreCopy() { 13260 return PackageManager.INSTALL_SUCCEEDED; 13261 } 13262 13263 /** 13264 * Called after the source arguments are copied. This is used mostly for 13265 * MoveParams when it needs to read the source file to put it in the 13266 * destination. 13267 */ 13268 int doPostCopy(int uid) { 13269 return PackageManager.INSTALL_SUCCEEDED; 13270 } 13271 13272 protected boolean isFwdLocked() { 13273 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13274 } 13275 13276 protected boolean isExternalAsec() { 13277 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13278 } 13279 13280 protected boolean isEphemeral() { 13281 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13282 } 13283 13284 UserHandle getUser() { 13285 return user; 13286 } 13287 } 13288 13289 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13290 if (!allCodePaths.isEmpty()) { 13291 if (instructionSets == null) { 13292 throw new IllegalStateException("instructionSet == null"); 13293 } 13294 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13295 for (String codePath : allCodePaths) { 13296 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13297 try { 13298 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13299 } catch (InstallerException ignored) { 13300 } 13301 } 13302 } 13303 } 13304 } 13305 13306 /** 13307 * Logic to handle installation of non-ASEC applications, including copying 13308 * and renaming logic. 13309 */ 13310 class FileInstallArgs extends InstallArgs { 13311 private File codeFile; 13312 private File resourceFile; 13313 13314 // Example topology: 13315 // /data/app/com.example/base.apk 13316 // /data/app/com.example/split_foo.apk 13317 // /data/app/com.example/lib/arm/libfoo.so 13318 // /data/app/com.example/lib/arm64/libfoo.so 13319 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13320 13321 /** New install */ 13322 FileInstallArgs(InstallParams params) { 13323 super(params.origin, params.move, params.observer, params.installFlags, 13324 params.installerPackageName, params.volumeUuid, 13325 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13326 params.grantedRuntimePermissions, 13327 params.traceMethod, params.traceCookie, params.certificates); 13328 if (isFwdLocked()) { 13329 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13330 } 13331 } 13332 13333 /** Existing install */ 13334 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13335 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13336 null, null, null, 0, null /*certificates*/); 13337 this.codeFile = (codePath != null) ? new File(codePath) : null; 13338 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13339 } 13340 13341 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13343 try { 13344 return doCopyApk(imcs, temp); 13345 } finally { 13346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13347 } 13348 } 13349 13350 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13351 if (origin.staged) { 13352 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13353 codeFile = origin.file; 13354 resourceFile = origin.file; 13355 return PackageManager.INSTALL_SUCCEEDED; 13356 } 13357 13358 try { 13359 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13360 final File tempDir = 13361 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13362 codeFile = tempDir; 13363 resourceFile = tempDir; 13364 } catch (IOException e) { 13365 Slog.w(TAG, "Failed to create copy file: " + e); 13366 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13367 } 13368 13369 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13370 @Override 13371 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13372 if (!FileUtils.isValidExtFilename(name)) { 13373 throw new IllegalArgumentException("Invalid filename: " + name); 13374 } 13375 try { 13376 final File file = new File(codeFile, name); 13377 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13378 O_RDWR | O_CREAT, 0644); 13379 Os.chmod(file.getAbsolutePath(), 0644); 13380 return new ParcelFileDescriptor(fd); 13381 } catch (ErrnoException e) { 13382 throw new RemoteException("Failed to open: " + e.getMessage()); 13383 } 13384 } 13385 }; 13386 13387 int ret = PackageManager.INSTALL_SUCCEEDED; 13388 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13389 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13390 Slog.e(TAG, "Failed to copy package"); 13391 return ret; 13392 } 13393 13394 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13395 NativeLibraryHelper.Handle handle = null; 13396 try { 13397 handle = NativeLibraryHelper.Handle.create(codeFile); 13398 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13399 abiOverride); 13400 } catch (IOException e) { 13401 Slog.e(TAG, "Copying native libraries failed", e); 13402 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13403 } finally { 13404 IoUtils.closeQuietly(handle); 13405 } 13406 13407 return ret; 13408 } 13409 13410 int doPreInstall(int status) { 13411 if (status != PackageManager.INSTALL_SUCCEEDED) { 13412 cleanUp(); 13413 } 13414 return status; 13415 } 13416 13417 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13418 if (status != PackageManager.INSTALL_SUCCEEDED) { 13419 cleanUp(); 13420 return false; 13421 } 13422 13423 final File targetDir = codeFile.getParentFile(); 13424 final File beforeCodeFile = codeFile; 13425 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13426 13427 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13428 try { 13429 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13430 } catch (ErrnoException e) { 13431 Slog.w(TAG, "Failed to rename", e); 13432 return false; 13433 } 13434 13435 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13436 Slog.w(TAG, "Failed to restorecon"); 13437 return false; 13438 } 13439 13440 // Reflect the rename internally 13441 codeFile = afterCodeFile; 13442 resourceFile = afterCodeFile; 13443 13444 // Reflect the rename in scanned details 13445 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13446 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13447 afterCodeFile, pkg.baseCodePath)); 13448 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13449 afterCodeFile, pkg.splitCodePaths)); 13450 13451 // Reflect the rename in app info 13452 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13453 pkg.setApplicationInfoCodePath(pkg.codePath); 13454 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13455 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13456 pkg.setApplicationInfoResourcePath(pkg.codePath); 13457 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13458 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13459 13460 return true; 13461 } 13462 13463 int doPostInstall(int status, int uid) { 13464 if (status != PackageManager.INSTALL_SUCCEEDED) { 13465 cleanUp(); 13466 } 13467 return status; 13468 } 13469 13470 @Override 13471 String getCodePath() { 13472 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13473 } 13474 13475 @Override 13476 String getResourcePath() { 13477 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13478 } 13479 13480 private boolean cleanUp() { 13481 if (codeFile == null || !codeFile.exists()) { 13482 return false; 13483 } 13484 13485 removeCodePathLI(codeFile); 13486 13487 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13488 resourceFile.delete(); 13489 } 13490 13491 return true; 13492 } 13493 13494 void cleanUpResourcesLI() { 13495 // Try enumerating all code paths before deleting 13496 List<String> allCodePaths = Collections.EMPTY_LIST; 13497 if (codeFile != null && codeFile.exists()) { 13498 try { 13499 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13500 allCodePaths = pkg.getAllCodePaths(); 13501 } catch (PackageParserException e) { 13502 // Ignored; we tried our best 13503 } 13504 } 13505 13506 cleanUp(); 13507 removeDexFiles(allCodePaths, instructionSets); 13508 } 13509 13510 boolean doPostDeleteLI(boolean delete) { 13511 // XXX err, shouldn't we respect the delete flag? 13512 cleanUpResourcesLI(); 13513 return true; 13514 } 13515 } 13516 13517 private boolean isAsecExternal(String cid) { 13518 final String asecPath = PackageHelper.getSdFilesystem(cid); 13519 return !asecPath.startsWith(mAsecInternalPath); 13520 } 13521 13522 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13523 PackageManagerException { 13524 if (copyRet < 0) { 13525 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13526 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13527 throw new PackageManagerException(copyRet, message); 13528 } 13529 } 13530 } 13531 13532 /** 13533 * Extract the MountService "container ID" from the full code path of an 13534 * .apk. 13535 */ 13536 static String cidFromCodePath(String fullCodePath) { 13537 int eidx = fullCodePath.lastIndexOf("/"); 13538 String subStr1 = fullCodePath.substring(0, eidx); 13539 int sidx = subStr1.lastIndexOf("/"); 13540 return subStr1.substring(sidx+1, eidx); 13541 } 13542 13543 /** 13544 * Logic to handle installation of ASEC applications, including copying and 13545 * renaming logic. 13546 */ 13547 class AsecInstallArgs extends InstallArgs { 13548 static final String RES_FILE_NAME = "pkg.apk"; 13549 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13550 13551 String cid; 13552 String packagePath; 13553 String resourcePath; 13554 13555 /** New install */ 13556 AsecInstallArgs(InstallParams params) { 13557 super(params.origin, params.move, params.observer, params.installFlags, 13558 params.installerPackageName, params.volumeUuid, 13559 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13560 params.grantedRuntimePermissions, 13561 params.traceMethod, params.traceCookie, params.certificates); 13562 } 13563 13564 /** Existing install */ 13565 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13566 boolean isExternal, boolean isForwardLocked) { 13567 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13568 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13569 instructionSets, null, null, null, 0, null /*certificates*/); 13570 // Hackily pretend we're still looking at a full code path 13571 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13572 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13573 } 13574 13575 // Extract cid from fullCodePath 13576 int eidx = fullCodePath.lastIndexOf("/"); 13577 String subStr1 = fullCodePath.substring(0, eidx); 13578 int sidx = subStr1.lastIndexOf("/"); 13579 cid = subStr1.substring(sidx+1, eidx); 13580 setMountPath(subStr1); 13581 } 13582 13583 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13584 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13585 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13586 instructionSets, null, null, null, 0, null /*certificates*/); 13587 this.cid = cid; 13588 setMountPath(PackageHelper.getSdDir(cid)); 13589 } 13590 13591 void createCopyFile() { 13592 cid = mInstallerService.allocateExternalStageCidLegacy(); 13593 } 13594 13595 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13596 if (origin.staged && origin.cid != null) { 13597 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13598 cid = origin.cid; 13599 setMountPath(PackageHelper.getSdDir(cid)); 13600 return PackageManager.INSTALL_SUCCEEDED; 13601 } 13602 13603 if (temp) { 13604 createCopyFile(); 13605 } else { 13606 /* 13607 * Pre-emptively destroy the container since it's destroyed if 13608 * copying fails due to it existing anyway. 13609 */ 13610 PackageHelper.destroySdDir(cid); 13611 } 13612 13613 final String newMountPath = imcs.copyPackageToContainer( 13614 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13615 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13616 13617 if (newMountPath != null) { 13618 setMountPath(newMountPath); 13619 return PackageManager.INSTALL_SUCCEEDED; 13620 } else { 13621 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13622 } 13623 } 13624 13625 @Override 13626 String getCodePath() { 13627 return packagePath; 13628 } 13629 13630 @Override 13631 String getResourcePath() { 13632 return resourcePath; 13633 } 13634 13635 int doPreInstall(int status) { 13636 if (status != PackageManager.INSTALL_SUCCEEDED) { 13637 // Destroy container 13638 PackageHelper.destroySdDir(cid); 13639 } else { 13640 boolean mounted = PackageHelper.isContainerMounted(cid); 13641 if (!mounted) { 13642 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13643 Process.SYSTEM_UID); 13644 if (newMountPath != null) { 13645 setMountPath(newMountPath); 13646 } else { 13647 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13648 } 13649 } 13650 } 13651 return status; 13652 } 13653 13654 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13655 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13656 String newMountPath = null; 13657 if (PackageHelper.isContainerMounted(cid)) { 13658 // Unmount the container 13659 if (!PackageHelper.unMountSdDir(cid)) { 13660 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13661 return false; 13662 } 13663 } 13664 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13665 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13666 " which might be stale. Will try to clean up."); 13667 // Clean up the stale container and proceed to recreate. 13668 if (!PackageHelper.destroySdDir(newCacheId)) { 13669 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13670 return false; 13671 } 13672 // Successfully cleaned up stale container. Try to rename again. 13673 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13674 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13675 + " inspite of cleaning it up."); 13676 return false; 13677 } 13678 } 13679 if (!PackageHelper.isContainerMounted(newCacheId)) { 13680 Slog.w(TAG, "Mounting container " + newCacheId); 13681 newMountPath = PackageHelper.mountSdDir(newCacheId, 13682 getEncryptKey(), Process.SYSTEM_UID); 13683 } else { 13684 newMountPath = PackageHelper.getSdDir(newCacheId); 13685 } 13686 if (newMountPath == null) { 13687 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13688 return false; 13689 } 13690 Log.i(TAG, "Succesfully renamed " + cid + 13691 " to " + newCacheId + 13692 " at new path: " + newMountPath); 13693 cid = newCacheId; 13694 13695 final File beforeCodeFile = new File(packagePath); 13696 setMountPath(newMountPath); 13697 final File afterCodeFile = new File(packagePath); 13698 13699 // Reflect the rename in scanned details 13700 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13701 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13702 afterCodeFile, pkg.baseCodePath)); 13703 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13704 afterCodeFile, pkg.splitCodePaths)); 13705 13706 // Reflect the rename in app info 13707 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13708 pkg.setApplicationInfoCodePath(pkg.codePath); 13709 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13710 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13711 pkg.setApplicationInfoResourcePath(pkg.codePath); 13712 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13713 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13714 13715 return true; 13716 } 13717 13718 private void setMountPath(String mountPath) { 13719 final File mountFile = new File(mountPath); 13720 13721 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13722 if (monolithicFile.exists()) { 13723 packagePath = monolithicFile.getAbsolutePath(); 13724 if (isFwdLocked()) { 13725 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13726 } else { 13727 resourcePath = packagePath; 13728 } 13729 } else { 13730 packagePath = mountFile.getAbsolutePath(); 13731 resourcePath = packagePath; 13732 } 13733 } 13734 13735 int doPostInstall(int status, int uid) { 13736 if (status != PackageManager.INSTALL_SUCCEEDED) { 13737 cleanUp(); 13738 } else { 13739 final int groupOwner; 13740 final String protectedFile; 13741 if (isFwdLocked()) { 13742 groupOwner = UserHandle.getSharedAppGid(uid); 13743 protectedFile = RES_FILE_NAME; 13744 } else { 13745 groupOwner = -1; 13746 protectedFile = null; 13747 } 13748 13749 if (uid < Process.FIRST_APPLICATION_UID 13750 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13751 Slog.e(TAG, "Failed to finalize " + cid); 13752 PackageHelper.destroySdDir(cid); 13753 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13754 } 13755 13756 boolean mounted = PackageHelper.isContainerMounted(cid); 13757 if (!mounted) { 13758 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13759 } 13760 } 13761 return status; 13762 } 13763 13764 private void cleanUp() { 13765 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13766 13767 // Destroy secure container 13768 PackageHelper.destroySdDir(cid); 13769 } 13770 13771 private List<String> getAllCodePaths() { 13772 final File codeFile = new File(getCodePath()); 13773 if (codeFile != null && codeFile.exists()) { 13774 try { 13775 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13776 return pkg.getAllCodePaths(); 13777 } catch (PackageParserException e) { 13778 // Ignored; we tried our best 13779 } 13780 } 13781 return Collections.EMPTY_LIST; 13782 } 13783 13784 void cleanUpResourcesLI() { 13785 // Enumerate all code paths before deleting 13786 cleanUpResourcesLI(getAllCodePaths()); 13787 } 13788 13789 private void cleanUpResourcesLI(List<String> allCodePaths) { 13790 cleanUp(); 13791 removeDexFiles(allCodePaths, instructionSets); 13792 } 13793 13794 String getPackageName() { 13795 return getAsecPackageName(cid); 13796 } 13797 13798 boolean doPostDeleteLI(boolean delete) { 13799 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13800 final List<String> allCodePaths = getAllCodePaths(); 13801 boolean mounted = PackageHelper.isContainerMounted(cid); 13802 if (mounted) { 13803 // Unmount first 13804 if (PackageHelper.unMountSdDir(cid)) { 13805 mounted = false; 13806 } 13807 } 13808 if (!mounted && delete) { 13809 cleanUpResourcesLI(allCodePaths); 13810 } 13811 return !mounted; 13812 } 13813 13814 @Override 13815 int doPreCopy() { 13816 if (isFwdLocked()) { 13817 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13818 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13819 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13820 } 13821 } 13822 13823 return PackageManager.INSTALL_SUCCEEDED; 13824 } 13825 13826 @Override 13827 int doPostCopy(int uid) { 13828 if (isFwdLocked()) { 13829 if (uid < Process.FIRST_APPLICATION_UID 13830 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13831 RES_FILE_NAME)) { 13832 Slog.e(TAG, "Failed to finalize " + cid); 13833 PackageHelper.destroySdDir(cid); 13834 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13835 } 13836 } 13837 13838 return PackageManager.INSTALL_SUCCEEDED; 13839 } 13840 } 13841 13842 /** 13843 * Logic to handle movement of existing installed applications. 13844 */ 13845 class MoveInstallArgs extends InstallArgs { 13846 private File codeFile; 13847 private File resourceFile; 13848 13849 /** New install */ 13850 MoveInstallArgs(InstallParams params) { 13851 super(params.origin, params.move, params.observer, params.installFlags, 13852 params.installerPackageName, params.volumeUuid, 13853 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13854 params.grantedRuntimePermissions, 13855 params.traceMethod, params.traceCookie, params.certificates); 13856 } 13857 13858 int copyApk(IMediaContainerService imcs, boolean temp) { 13859 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13860 + move.fromUuid + " to " + move.toUuid); 13861 synchronized (mInstaller) { 13862 try { 13863 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13864 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13865 } catch (InstallerException e) { 13866 Slog.w(TAG, "Failed to move app", e); 13867 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13868 } 13869 } 13870 13871 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13872 resourceFile = codeFile; 13873 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13874 13875 return PackageManager.INSTALL_SUCCEEDED; 13876 } 13877 13878 int doPreInstall(int status) { 13879 if (status != PackageManager.INSTALL_SUCCEEDED) { 13880 cleanUp(move.toUuid); 13881 } 13882 return status; 13883 } 13884 13885 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13886 if (status != PackageManager.INSTALL_SUCCEEDED) { 13887 cleanUp(move.toUuid); 13888 return false; 13889 } 13890 13891 // Reflect the move in app info 13892 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13893 pkg.setApplicationInfoCodePath(pkg.codePath); 13894 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13895 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13896 pkg.setApplicationInfoResourcePath(pkg.codePath); 13897 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13898 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13899 13900 return true; 13901 } 13902 13903 int doPostInstall(int status, int uid) { 13904 if (status == PackageManager.INSTALL_SUCCEEDED) { 13905 cleanUp(move.fromUuid); 13906 } else { 13907 cleanUp(move.toUuid); 13908 } 13909 return status; 13910 } 13911 13912 @Override 13913 String getCodePath() { 13914 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13915 } 13916 13917 @Override 13918 String getResourcePath() { 13919 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13920 } 13921 13922 private boolean cleanUp(String volumeUuid) { 13923 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13924 move.dataAppName); 13925 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13926 final int[] userIds = sUserManager.getUserIds(); 13927 synchronized (mInstallLock) { 13928 // Clean up both app data and code 13929 // All package moves are frozen until finished 13930 for (int userId : userIds) { 13931 try { 13932 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13933 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13934 } catch (InstallerException e) { 13935 Slog.w(TAG, String.valueOf(e)); 13936 } 13937 } 13938 removeCodePathLI(codeFile); 13939 } 13940 return true; 13941 } 13942 13943 void cleanUpResourcesLI() { 13944 throw new UnsupportedOperationException(); 13945 } 13946 13947 boolean doPostDeleteLI(boolean delete) { 13948 throw new UnsupportedOperationException(); 13949 } 13950 } 13951 13952 static String getAsecPackageName(String packageCid) { 13953 int idx = packageCid.lastIndexOf("-"); 13954 if (idx == -1) { 13955 return packageCid; 13956 } 13957 return packageCid.substring(0, idx); 13958 } 13959 13960 // Utility method used to create code paths based on package name and available index. 13961 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13962 String idxStr = ""; 13963 int idx = 1; 13964 // Fall back to default value of idx=1 if prefix is not 13965 // part of oldCodePath 13966 if (oldCodePath != null) { 13967 String subStr = oldCodePath; 13968 // Drop the suffix right away 13969 if (suffix != null && subStr.endsWith(suffix)) { 13970 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13971 } 13972 // If oldCodePath already contains prefix find out the 13973 // ending index to either increment or decrement. 13974 int sidx = subStr.lastIndexOf(prefix); 13975 if (sidx != -1) { 13976 subStr = subStr.substring(sidx + prefix.length()); 13977 if (subStr != null) { 13978 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13979 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13980 } 13981 try { 13982 idx = Integer.parseInt(subStr); 13983 if (idx <= 1) { 13984 idx++; 13985 } else { 13986 idx--; 13987 } 13988 } catch(NumberFormatException e) { 13989 } 13990 } 13991 } 13992 } 13993 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13994 return prefix + idxStr; 13995 } 13996 13997 private File getNextCodePath(File targetDir, String packageName) { 13998 int suffix = 1; 13999 File result; 14000 do { 14001 result = new File(targetDir, packageName + "-" + suffix); 14002 suffix++; 14003 } while (result.exists()); 14004 return result; 14005 } 14006 14007 // Utility method that returns the relative package path with respect 14008 // to the installation directory. Like say for /data/data/com.test-1.apk 14009 // string com.test-1 is returned. 14010 static String deriveCodePathName(String codePath) { 14011 if (codePath == null) { 14012 return null; 14013 } 14014 final File codeFile = new File(codePath); 14015 final String name = codeFile.getName(); 14016 if (codeFile.isDirectory()) { 14017 return name; 14018 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14019 final int lastDot = name.lastIndexOf('.'); 14020 return name.substring(0, lastDot); 14021 } else { 14022 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14023 return null; 14024 } 14025 } 14026 14027 static class PackageInstalledInfo { 14028 String name; 14029 int uid; 14030 // The set of users that originally had this package installed. 14031 int[] origUsers; 14032 // The set of users that now have this package installed. 14033 int[] newUsers; 14034 PackageParser.Package pkg; 14035 int returnCode; 14036 String returnMsg; 14037 PackageRemovedInfo removedInfo; 14038 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14039 14040 public void setError(int code, String msg) { 14041 setReturnCode(code); 14042 setReturnMessage(msg); 14043 Slog.w(TAG, msg); 14044 } 14045 14046 public void setError(String msg, PackageParserException e) { 14047 setReturnCode(e.error); 14048 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14049 Slog.w(TAG, msg, e); 14050 } 14051 14052 public void setError(String msg, PackageManagerException e) { 14053 returnCode = e.error; 14054 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14055 Slog.w(TAG, msg, e); 14056 } 14057 14058 public void setReturnCode(int returnCode) { 14059 this.returnCode = returnCode; 14060 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14061 for (int i = 0; i < childCount; i++) { 14062 addedChildPackages.valueAt(i).returnCode = returnCode; 14063 } 14064 } 14065 14066 private void setReturnMessage(String returnMsg) { 14067 this.returnMsg = returnMsg; 14068 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14069 for (int i = 0; i < childCount; i++) { 14070 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14071 } 14072 } 14073 14074 // In some error cases we want to convey more info back to the observer 14075 String origPackage; 14076 String origPermission; 14077 } 14078 14079 /* 14080 * Install a non-existing package. 14081 */ 14082 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14083 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14084 PackageInstalledInfo res) { 14085 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14086 14087 // Remember this for later, in case we need to rollback this install 14088 String pkgName = pkg.packageName; 14089 14090 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14091 14092 synchronized(mPackages) { 14093 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14094 // A package with the same name is already installed, though 14095 // it has been renamed to an older name. The package we 14096 // are trying to install should be installed as an update to 14097 // the existing one, but that has not been requested, so bail. 14098 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14099 + " without first uninstalling package running as " 14100 + mSettings.mRenamedPackages.get(pkgName)); 14101 return; 14102 } 14103 if (mPackages.containsKey(pkgName)) { 14104 // Don't allow installation over an existing package with the same name. 14105 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14106 + " without first uninstalling."); 14107 return; 14108 } 14109 } 14110 14111 try { 14112 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14113 System.currentTimeMillis(), user); 14114 14115 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14116 14117 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14118 prepareAppDataAfterInstallLIF(newPackage); 14119 14120 } else { 14121 // Remove package from internal structures, but keep around any 14122 // data that might have already existed 14123 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14124 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14125 } 14126 } catch (PackageManagerException e) { 14127 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14128 } 14129 14130 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14131 } 14132 14133 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14134 // Can't rotate keys during boot or if sharedUser. 14135 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14136 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14137 return false; 14138 } 14139 // app is using upgradeKeySets; make sure all are valid 14140 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14141 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14142 for (int i = 0; i < upgradeKeySets.length; i++) { 14143 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14144 Slog.wtf(TAG, "Package " 14145 + (oldPs.name != null ? oldPs.name : "<null>") 14146 + " contains upgrade-key-set reference to unknown key-set: " 14147 + upgradeKeySets[i] 14148 + " reverting to signatures check."); 14149 return false; 14150 } 14151 } 14152 return true; 14153 } 14154 14155 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14156 // Upgrade keysets are being used. Determine if new package has a superset of the 14157 // required keys. 14158 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14159 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14160 for (int i = 0; i < upgradeKeySets.length; i++) { 14161 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14162 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14163 return true; 14164 } 14165 } 14166 return false; 14167 } 14168 14169 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14170 try (DigestInputStream digestStream = 14171 new DigestInputStream(new FileInputStream(file), digest)) { 14172 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14173 } 14174 } 14175 14176 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14177 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14178 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14179 14180 final PackageParser.Package oldPackage; 14181 final String pkgName = pkg.packageName; 14182 final int[] allUsers; 14183 final int[] installedUsers; 14184 14185 synchronized(mPackages) { 14186 oldPackage = mPackages.get(pkgName); 14187 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14188 14189 // don't allow upgrade to target a release SDK from a pre-release SDK 14190 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14191 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14192 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14193 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14194 if (oldTargetsPreRelease 14195 && !newTargetsPreRelease 14196 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14197 Slog.w(TAG, "Can't install package targeting released sdk"); 14198 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14199 return; 14200 } 14201 14202 // don't allow an upgrade from full to ephemeral 14203 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14204 if (isEphemeral && !oldIsEphemeral) { 14205 // can't downgrade from full to ephemeral 14206 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14207 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14208 return; 14209 } 14210 14211 // verify signatures are valid 14212 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14213 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14214 if (!checkUpgradeKeySetLP(ps, pkg)) { 14215 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14216 "New package not signed by keys specified by upgrade-keysets: " 14217 + pkgName); 14218 return; 14219 } 14220 } else { 14221 // default to original signature matching 14222 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14223 != PackageManager.SIGNATURE_MATCH) { 14224 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14225 "New package has a different signature: " + pkgName); 14226 return; 14227 } 14228 } 14229 14230 // don't allow a system upgrade unless the upgrade hash matches 14231 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14232 byte[] digestBytes = null; 14233 try { 14234 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14235 updateDigest(digest, new File(pkg.baseCodePath)); 14236 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14237 for (String path : pkg.splitCodePaths) { 14238 updateDigest(digest, new File(path)); 14239 } 14240 } 14241 digestBytes = digest.digest(); 14242 } catch (NoSuchAlgorithmException | IOException e) { 14243 res.setError(INSTALL_FAILED_INVALID_APK, 14244 "Could not compute hash: " + pkgName); 14245 return; 14246 } 14247 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14248 res.setError(INSTALL_FAILED_INVALID_APK, 14249 "New package fails restrict-update check: " + pkgName); 14250 return; 14251 } 14252 // retain upgrade restriction 14253 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14254 } 14255 14256 // Check for shared user id changes 14257 String invalidPackageName = 14258 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14259 if (invalidPackageName != null) { 14260 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14261 "Package " + invalidPackageName + " tried to change user " 14262 + oldPackage.mSharedUserId); 14263 return; 14264 } 14265 14266 // In case of rollback, remember per-user/profile install state 14267 allUsers = sUserManager.getUserIds(); 14268 installedUsers = ps.queryInstalledUsers(allUsers, true); 14269 } 14270 14271 // Update what is removed 14272 res.removedInfo = new PackageRemovedInfo(); 14273 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14274 res.removedInfo.removedPackage = oldPackage.packageName; 14275 res.removedInfo.isUpdate = true; 14276 res.removedInfo.origUsers = installedUsers; 14277 final int childCount = (oldPackage.childPackages != null) 14278 ? oldPackage.childPackages.size() : 0; 14279 for (int i = 0; i < childCount; i++) { 14280 boolean childPackageUpdated = false; 14281 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14282 if (res.addedChildPackages != null) { 14283 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14284 if (childRes != null) { 14285 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14286 childRes.removedInfo.removedPackage = childPkg.packageName; 14287 childRes.removedInfo.isUpdate = true; 14288 childPackageUpdated = true; 14289 } 14290 } 14291 if (!childPackageUpdated) { 14292 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14293 childRemovedRes.removedPackage = childPkg.packageName; 14294 childRemovedRes.isUpdate = false; 14295 childRemovedRes.dataRemoved = true; 14296 synchronized (mPackages) { 14297 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14298 if (childPs != null) { 14299 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14300 } 14301 } 14302 if (res.removedInfo.removedChildPackages == null) { 14303 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14304 } 14305 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14306 } 14307 } 14308 14309 boolean sysPkg = (isSystemApp(oldPackage)); 14310 if (sysPkg) { 14311 // Set the system/privileged flags as needed 14312 final boolean privileged = 14313 (oldPackage.applicationInfo.privateFlags 14314 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14315 final int systemPolicyFlags = policyFlags 14316 | PackageParser.PARSE_IS_SYSTEM 14317 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14318 14319 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14320 user, allUsers, installerPackageName, res); 14321 } else { 14322 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14323 user, allUsers, installerPackageName, res); 14324 } 14325 } 14326 14327 public List<String> getPreviousCodePaths(String packageName) { 14328 final PackageSetting ps = mSettings.mPackages.get(packageName); 14329 final List<String> result = new ArrayList<String>(); 14330 if (ps != null && ps.oldCodePaths != null) { 14331 result.addAll(ps.oldCodePaths); 14332 } 14333 return result; 14334 } 14335 14336 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14337 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14338 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14339 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14340 + deletedPackage); 14341 14342 String pkgName = deletedPackage.packageName; 14343 boolean deletedPkg = true; 14344 boolean addedPkg = false; 14345 boolean updatedSettings = false; 14346 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14347 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14348 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14349 14350 final long origUpdateTime = (pkg.mExtras != null) 14351 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14352 14353 // First delete the existing package while retaining the data directory 14354 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14355 res.removedInfo, true, pkg)) { 14356 // If the existing package wasn't successfully deleted 14357 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14358 deletedPkg = false; 14359 } else { 14360 // Successfully deleted the old package; proceed with replace. 14361 14362 // If deleted package lived in a container, give users a chance to 14363 // relinquish resources before killing. 14364 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14365 if (DEBUG_INSTALL) { 14366 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14367 } 14368 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14369 final ArrayList<String> pkgList = new ArrayList<String>(1); 14370 pkgList.add(deletedPackage.applicationInfo.packageName); 14371 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14372 } 14373 14374 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14375 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14376 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14377 14378 try { 14379 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14380 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14381 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14382 14383 // Update the in-memory copy of the previous code paths. 14384 PackageSetting ps = mSettings.mPackages.get(pkgName); 14385 if (!killApp) { 14386 if (ps.oldCodePaths == null) { 14387 ps.oldCodePaths = new ArraySet<>(); 14388 } 14389 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14390 if (deletedPackage.splitCodePaths != null) { 14391 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14392 } 14393 } else { 14394 ps.oldCodePaths = null; 14395 } 14396 if (ps.childPackageNames != null) { 14397 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14398 final String childPkgName = ps.childPackageNames.get(i); 14399 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14400 childPs.oldCodePaths = ps.oldCodePaths; 14401 } 14402 } 14403 prepareAppDataAfterInstallLIF(newPackage); 14404 addedPkg = true; 14405 } catch (PackageManagerException e) { 14406 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14407 } 14408 } 14409 14410 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14411 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14412 14413 // Revert all internal state mutations and added folders for the failed install 14414 if (addedPkg) { 14415 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14416 res.removedInfo, true, null); 14417 } 14418 14419 // Restore the old package 14420 if (deletedPkg) { 14421 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14422 File restoreFile = new File(deletedPackage.codePath); 14423 // Parse old package 14424 boolean oldExternal = isExternal(deletedPackage); 14425 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14426 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14427 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14428 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14429 try { 14430 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14431 null); 14432 } catch (PackageManagerException e) { 14433 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14434 + e.getMessage()); 14435 return; 14436 } 14437 14438 synchronized (mPackages) { 14439 // Ensure the installer package name up to date 14440 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14441 14442 // Update permissions for restored package 14443 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14444 14445 mSettings.writeLPr(); 14446 } 14447 14448 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14449 } 14450 } else { 14451 synchronized (mPackages) { 14452 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14453 if (ps != null) { 14454 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14455 if (res.removedInfo.removedChildPackages != null) { 14456 final int childCount = res.removedInfo.removedChildPackages.size(); 14457 // Iterate in reverse as we may modify the collection 14458 for (int i = childCount - 1; i >= 0; i--) { 14459 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14460 if (res.addedChildPackages.containsKey(childPackageName)) { 14461 res.removedInfo.removedChildPackages.removeAt(i); 14462 } else { 14463 PackageRemovedInfo childInfo = res.removedInfo 14464 .removedChildPackages.valueAt(i); 14465 childInfo.removedForAllUsers = mPackages.get( 14466 childInfo.removedPackage) == null; 14467 } 14468 } 14469 } 14470 } 14471 } 14472 } 14473 } 14474 14475 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14476 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14477 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14478 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14479 + ", old=" + deletedPackage); 14480 14481 final boolean disabledSystem; 14482 14483 // Remove existing system package 14484 removePackageLI(deletedPackage, true); 14485 14486 synchronized (mPackages) { 14487 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14488 } 14489 if (!disabledSystem) { 14490 // We didn't need to disable the .apk as a current system package, 14491 // which means we are replacing another update that is already 14492 // installed. We need to make sure to delete the older one's .apk. 14493 res.removedInfo.args = createInstallArgsForExisting(0, 14494 deletedPackage.applicationInfo.getCodePath(), 14495 deletedPackage.applicationInfo.getResourcePath(), 14496 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14497 } else { 14498 res.removedInfo.args = null; 14499 } 14500 14501 // Successfully disabled the old package. Now proceed with re-installation 14502 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14503 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14504 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14505 14506 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14507 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14508 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14509 14510 PackageParser.Package newPackage = null; 14511 try { 14512 // Add the package to the internal data structures 14513 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14514 14515 // Set the update and install times 14516 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14517 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14518 System.currentTimeMillis()); 14519 14520 // Update the package dynamic state if succeeded 14521 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14522 // Now that the install succeeded make sure we remove data 14523 // directories for any child package the update removed. 14524 final int deletedChildCount = (deletedPackage.childPackages != null) 14525 ? deletedPackage.childPackages.size() : 0; 14526 final int newChildCount = (newPackage.childPackages != null) 14527 ? newPackage.childPackages.size() : 0; 14528 for (int i = 0; i < deletedChildCount; i++) { 14529 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14530 boolean childPackageDeleted = true; 14531 for (int j = 0; j < newChildCount; j++) { 14532 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14533 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14534 childPackageDeleted = false; 14535 break; 14536 } 14537 } 14538 if (childPackageDeleted) { 14539 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14540 deletedChildPkg.packageName); 14541 if (ps != null && res.removedInfo.removedChildPackages != null) { 14542 PackageRemovedInfo removedChildRes = res.removedInfo 14543 .removedChildPackages.get(deletedChildPkg.packageName); 14544 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14545 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14546 } 14547 } 14548 } 14549 14550 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14551 prepareAppDataAfterInstallLIF(newPackage); 14552 } 14553 } catch (PackageManagerException e) { 14554 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14555 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14556 } 14557 14558 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14559 // Re installation failed. Restore old information 14560 // Remove new pkg information 14561 if (newPackage != null) { 14562 removeInstalledPackageLI(newPackage, true); 14563 } 14564 // Add back the old system package 14565 try { 14566 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14567 } catch (PackageManagerException e) { 14568 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14569 } 14570 14571 synchronized (mPackages) { 14572 if (disabledSystem) { 14573 enableSystemPackageLPw(deletedPackage); 14574 } 14575 14576 // Ensure the installer package name up to date 14577 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14578 14579 // Update permissions for restored package 14580 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14581 14582 mSettings.writeLPr(); 14583 } 14584 14585 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14586 + " after failed upgrade"); 14587 } 14588 } 14589 14590 /** 14591 * Checks whether the parent or any of the child packages have a change shared 14592 * user. For a package to be a valid update the shred users of the parent and 14593 * the children should match. We may later support changing child shared users. 14594 * @param oldPkg The updated package. 14595 * @param newPkg The update package. 14596 * @return The shared user that change between the versions. 14597 */ 14598 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14599 PackageParser.Package newPkg) { 14600 // Check parent shared user 14601 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14602 return newPkg.packageName; 14603 } 14604 // Check child shared users 14605 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14606 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14607 for (int i = 0; i < newChildCount; i++) { 14608 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14609 // If this child was present, did it have the same shared user? 14610 for (int j = 0; j < oldChildCount; j++) { 14611 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14612 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14613 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14614 return newChildPkg.packageName; 14615 } 14616 } 14617 } 14618 return null; 14619 } 14620 14621 private void removeNativeBinariesLI(PackageSetting ps) { 14622 // Remove the lib path for the parent package 14623 if (ps != null) { 14624 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14625 // Remove the lib path for the child packages 14626 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14627 for (int i = 0; i < childCount; i++) { 14628 PackageSetting childPs = null; 14629 synchronized (mPackages) { 14630 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14631 } 14632 if (childPs != null) { 14633 NativeLibraryHelper.removeNativeBinariesLI(childPs 14634 .legacyNativeLibraryPathString); 14635 } 14636 } 14637 } 14638 } 14639 14640 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14641 // Enable the parent package 14642 mSettings.enableSystemPackageLPw(pkg.packageName); 14643 // Enable the child packages 14644 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14645 for (int i = 0; i < childCount; i++) { 14646 PackageParser.Package childPkg = pkg.childPackages.get(i); 14647 mSettings.enableSystemPackageLPw(childPkg.packageName); 14648 } 14649 } 14650 14651 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14652 PackageParser.Package newPkg) { 14653 // Disable the parent package (parent always replaced) 14654 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14655 // Disable the child packages 14656 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14657 for (int i = 0; i < childCount; i++) { 14658 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14659 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14660 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14661 } 14662 return disabled; 14663 } 14664 14665 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14666 String installerPackageName) { 14667 // Enable the parent package 14668 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14669 // Enable the child packages 14670 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14671 for (int i = 0; i < childCount; i++) { 14672 PackageParser.Package childPkg = pkg.childPackages.get(i); 14673 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14674 } 14675 } 14676 14677 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14678 // Collect all used permissions in the UID 14679 ArraySet<String> usedPermissions = new ArraySet<>(); 14680 final int packageCount = su.packages.size(); 14681 for (int i = 0; i < packageCount; i++) { 14682 PackageSetting ps = su.packages.valueAt(i); 14683 if (ps.pkg == null) { 14684 continue; 14685 } 14686 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14687 for (int j = 0; j < requestedPermCount; j++) { 14688 String permission = ps.pkg.requestedPermissions.get(j); 14689 BasePermission bp = mSettings.mPermissions.get(permission); 14690 if (bp != null) { 14691 usedPermissions.add(permission); 14692 } 14693 } 14694 } 14695 14696 PermissionsState permissionsState = su.getPermissionsState(); 14697 // Prune install permissions 14698 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14699 final int installPermCount = installPermStates.size(); 14700 for (int i = installPermCount - 1; i >= 0; i--) { 14701 PermissionState permissionState = installPermStates.get(i); 14702 if (!usedPermissions.contains(permissionState.getName())) { 14703 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14704 if (bp != null) { 14705 permissionsState.revokeInstallPermission(bp); 14706 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14707 PackageManager.MASK_PERMISSION_FLAGS, 0); 14708 } 14709 } 14710 } 14711 14712 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14713 14714 // Prune runtime permissions 14715 for (int userId : allUserIds) { 14716 List<PermissionState> runtimePermStates = permissionsState 14717 .getRuntimePermissionStates(userId); 14718 final int runtimePermCount = runtimePermStates.size(); 14719 for (int i = runtimePermCount - 1; i >= 0; i--) { 14720 PermissionState permissionState = runtimePermStates.get(i); 14721 if (!usedPermissions.contains(permissionState.getName())) { 14722 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14723 if (bp != null) { 14724 permissionsState.revokeRuntimePermission(bp, userId); 14725 permissionsState.updatePermissionFlags(bp, userId, 14726 PackageManager.MASK_PERMISSION_FLAGS, 0); 14727 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14728 runtimePermissionChangedUserIds, userId); 14729 } 14730 } 14731 } 14732 } 14733 14734 return runtimePermissionChangedUserIds; 14735 } 14736 14737 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14738 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14739 // Update the parent package setting 14740 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14741 res, user); 14742 // Update the child packages setting 14743 final int childCount = (newPackage.childPackages != null) 14744 ? newPackage.childPackages.size() : 0; 14745 for (int i = 0; i < childCount; i++) { 14746 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14747 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14748 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14749 childRes.origUsers, childRes, user); 14750 } 14751 } 14752 14753 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14754 String installerPackageName, int[] allUsers, int[] installedForUsers, 14755 PackageInstalledInfo res, UserHandle user) { 14756 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14757 14758 String pkgName = newPackage.packageName; 14759 synchronized (mPackages) { 14760 //write settings. the installStatus will be incomplete at this stage. 14761 //note that the new package setting would have already been 14762 //added to mPackages. It hasn't been persisted yet. 14763 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14765 mSettings.writeLPr(); 14766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14767 } 14768 14769 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14770 synchronized (mPackages) { 14771 updatePermissionsLPw(newPackage.packageName, newPackage, 14772 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14773 ? UPDATE_PERMISSIONS_ALL : 0)); 14774 // For system-bundled packages, we assume that installing an upgraded version 14775 // of the package implies that the user actually wants to run that new code, 14776 // so we enable the package. 14777 PackageSetting ps = mSettings.mPackages.get(pkgName); 14778 final int userId = user.getIdentifier(); 14779 if (ps != null) { 14780 if (isSystemApp(newPackage)) { 14781 if (DEBUG_INSTALL) { 14782 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14783 } 14784 // Enable system package for requested users 14785 if (res.origUsers != null) { 14786 for (int origUserId : res.origUsers) { 14787 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14788 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14789 origUserId, installerPackageName); 14790 } 14791 } 14792 } 14793 // Also convey the prior install/uninstall state 14794 if (allUsers != null && installedForUsers != null) { 14795 for (int currentUserId : allUsers) { 14796 final boolean installed = ArrayUtils.contains( 14797 installedForUsers, currentUserId); 14798 if (DEBUG_INSTALL) { 14799 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14800 } 14801 ps.setInstalled(installed, currentUserId); 14802 } 14803 // these install state changes will be persisted in the 14804 // upcoming call to mSettings.writeLPr(). 14805 } 14806 } 14807 // It's implied that when a user requests installation, they want the app to be 14808 // installed and enabled. 14809 if (userId != UserHandle.USER_ALL) { 14810 ps.setInstalled(true, userId); 14811 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14812 } 14813 } 14814 res.name = pkgName; 14815 res.uid = newPackage.applicationInfo.uid; 14816 res.pkg = newPackage; 14817 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14818 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14819 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14820 //to update install status 14821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14822 mSettings.writeLPr(); 14823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14824 } 14825 14826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14827 } 14828 14829 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14830 try { 14831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14832 installPackageLI(args, res); 14833 } finally { 14834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14835 } 14836 } 14837 14838 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14839 final int installFlags = args.installFlags; 14840 final String installerPackageName = args.installerPackageName; 14841 final String volumeUuid = args.volumeUuid; 14842 final File tmpPackageFile = new File(args.getCodePath()); 14843 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14844 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14845 || (args.volumeUuid != null)); 14846 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14847 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14848 boolean replace = false; 14849 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14850 if (args.move != null) { 14851 // moving a complete application; perform an initial scan on the new install location 14852 scanFlags |= SCAN_INITIAL; 14853 } 14854 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14855 scanFlags |= SCAN_DONT_KILL_APP; 14856 } 14857 14858 // Result object to be returned 14859 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14860 14861 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14862 14863 // Sanity check 14864 if (ephemeral && (forwardLocked || onExternal)) { 14865 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14866 + " external=" + onExternal); 14867 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14868 return; 14869 } 14870 14871 // Retrieve PackageSettings and parse package 14872 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14873 | PackageParser.PARSE_ENFORCE_CODE 14874 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14875 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14876 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14877 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14878 PackageParser pp = new PackageParser(); 14879 pp.setSeparateProcesses(mSeparateProcesses); 14880 pp.setDisplayMetrics(mMetrics); 14881 14882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14883 final PackageParser.Package pkg; 14884 try { 14885 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14886 } catch (PackageParserException e) { 14887 res.setError("Failed parse during installPackageLI", e); 14888 return; 14889 } finally { 14890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14891 } 14892 14893 // If we are installing a clustered package add results for the children 14894 if (pkg.childPackages != null) { 14895 synchronized (mPackages) { 14896 final int childCount = pkg.childPackages.size(); 14897 for (int i = 0; i < childCount; i++) { 14898 PackageParser.Package childPkg = pkg.childPackages.get(i); 14899 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14900 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14901 childRes.pkg = childPkg; 14902 childRes.name = childPkg.packageName; 14903 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14904 if (childPs != null) { 14905 childRes.origUsers = childPs.queryInstalledUsers( 14906 sUserManager.getUserIds(), true); 14907 } 14908 if ((mPackages.containsKey(childPkg.packageName))) { 14909 childRes.removedInfo = new PackageRemovedInfo(); 14910 childRes.removedInfo.removedPackage = childPkg.packageName; 14911 } 14912 if (res.addedChildPackages == null) { 14913 res.addedChildPackages = new ArrayMap<>(); 14914 } 14915 res.addedChildPackages.put(childPkg.packageName, childRes); 14916 } 14917 } 14918 } 14919 14920 // If package doesn't declare API override, mark that we have an install 14921 // time CPU ABI override. 14922 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14923 pkg.cpuAbiOverride = args.abiOverride; 14924 } 14925 14926 String pkgName = res.name = pkg.packageName; 14927 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14928 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14929 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14930 return; 14931 } 14932 } 14933 14934 try { 14935 // either use what we've been given or parse directly from the APK 14936 if (args.certificates != null) { 14937 try { 14938 PackageParser.populateCertificates(pkg, args.certificates); 14939 } catch (PackageParserException e) { 14940 // there was something wrong with the certificates we were given; 14941 // try to pull them from the APK 14942 PackageParser.collectCertificates(pkg, parseFlags); 14943 } 14944 } else { 14945 PackageParser.collectCertificates(pkg, parseFlags); 14946 } 14947 } catch (PackageParserException e) { 14948 res.setError("Failed collect during installPackageLI", e); 14949 return; 14950 } 14951 14952 // Get rid of all references to package scan path via parser. 14953 pp = null; 14954 String oldCodePath = null; 14955 boolean systemApp = false; 14956 synchronized (mPackages) { 14957 // Check if installing already existing package 14958 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14959 String oldName = mSettings.mRenamedPackages.get(pkgName); 14960 if (pkg.mOriginalPackages != null 14961 && pkg.mOriginalPackages.contains(oldName) 14962 && mPackages.containsKey(oldName)) { 14963 // This package is derived from an original package, 14964 // and this device has been updating from that original 14965 // name. We must continue using the original name, so 14966 // rename the new package here. 14967 pkg.setPackageName(oldName); 14968 pkgName = pkg.packageName; 14969 replace = true; 14970 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14971 + oldName + " pkgName=" + pkgName); 14972 } else if (mPackages.containsKey(pkgName)) { 14973 // This package, under its official name, already exists 14974 // on the device; we should replace it. 14975 replace = true; 14976 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14977 } 14978 14979 // Child packages are installed through the parent package 14980 if (pkg.parentPackage != null) { 14981 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14982 "Package " + pkg.packageName + " is child of package " 14983 + pkg.parentPackage.parentPackage + ". Child packages " 14984 + "can be updated only through the parent package."); 14985 return; 14986 } 14987 14988 if (replace) { 14989 // Prevent apps opting out from runtime permissions 14990 PackageParser.Package oldPackage = mPackages.get(pkgName); 14991 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14992 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14993 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14994 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14995 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14996 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14997 + " doesn't support runtime permissions but the old" 14998 + " target SDK " + oldTargetSdk + " does."); 14999 return; 15000 } 15001 15002 // Prevent installing of child packages 15003 if (oldPackage.parentPackage != null) { 15004 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15005 "Package " + pkg.packageName + " is child of package " 15006 + oldPackage.parentPackage + ". Child packages " 15007 + "can be updated only through the parent package."); 15008 return; 15009 } 15010 } 15011 } 15012 15013 PackageSetting ps = mSettings.mPackages.get(pkgName); 15014 if (ps != null) { 15015 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15016 15017 // Quick sanity check that we're signed correctly if updating; 15018 // we'll check this again later when scanning, but we want to 15019 // bail early here before tripping over redefined permissions. 15020 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15021 if (!checkUpgradeKeySetLP(ps, pkg)) { 15022 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15023 + pkg.packageName + " upgrade keys do not match the " 15024 + "previously installed version"); 15025 return; 15026 } 15027 } else { 15028 try { 15029 verifySignaturesLP(ps, pkg); 15030 } catch (PackageManagerException e) { 15031 res.setError(e.error, e.getMessage()); 15032 return; 15033 } 15034 } 15035 15036 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15037 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15038 systemApp = (ps.pkg.applicationInfo.flags & 15039 ApplicationInfo.FLAG_SYSTEM) != 0; 15040 } 15041 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15042 } 15043 15044 // Check whether the newly-scanned package wants to define an already-defined perm 15045 int N = pkg.permissions.size(); 15046 for (int i = N-1; i >= 0; i--) { 15047 PackageParser.Permission perm = pkg.permissions.get(i); 15048 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15049 if (bp != null) { 15050 // If the defining package is signed with our cert, it's okay. This 15051 // also includes the "updating the same package" case, of course. 15052 // "updating same package" could also involve key-rotation. 15053 final boolean sigsOk; 15054 if (bp.sourcePackage.equals(pkg.packageName) 15055 && (bp.packageSetting instanceof PackageSetting) 15056 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15057 scanFlags))) { 15058 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15059 } else { 15060 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15061 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15062 } 15063 if (!sigsOk) { 15064 // If the owning package is the system itself, we log but allow 15065 // install to proceed; we fail the install on all other permission 15066 // redefinitions. 15067 if (!bp.sourcePackage.equals("android")) { 15068 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15069 + pkg.packageName + " attempting to redeclare permission " 15070 + perm.info.name + " already owned by " + bp.sourcePackage); 15071 res.origPermission = perm.info.name; 15072 res.origPackage = bp.sourcePackage; 15073 return; 15074 } else { 15075 Slog.w(TAG, "Package " + pkg.packageName 15076 + " attempting to redeclare system permission " 15077 + perm.info.name + "; ignoring new declaration"); 15078 pkg.permissions.remove(i); 15079 } 15080 } 15081 } 15082 } 15083 } 15084 15085 if (systemApp) { 15086 if (onExternal) { 15087 // Abort update; system app can't be replaced with app on sdcard 15088 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15089 "Cannot install updates to system apps on sdcard"); 15090 return; 15091 } else if (ephemeral) { 15092 // Abort update; system app can't be replaced with an ephemeral app 15093 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15094 "Cannot update a system app with an ephemeral app"); 15095 return; 15096 } 15097 } 15098 15099 if (args.move != null) { 15100 // We did an in-place move, so dex is ready to roll 15101 scanFlags |= SCAN_NO_DEX; 15102 scanFlags |= SCAN_MOVE; 15103 15104 synchronized (mPackages) { 15105 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15106 if (ps == null) { 15107 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15108 "Missing settings for moved package " + pkgName); 15109 } 15110 15111 // We moved the entire application as-is, so bring over the 15112 // previously derived ABI information. 15113 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15114 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15115 } 15116 15117 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15118 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15119 scanFlags |= SCAN_NO_DEX; 15120 15121 try { 15122 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15123 args.abiOverride : pkg.cpuAbiOverride); 15124 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15125 true /* extract libs */); 15126 } catch (PackageManagerException pme) { 15127 Slog.e(TAG, "Error deriving application ABI", pme); 15128 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15129 return; 15130 } 15131 15132 // Shared libraries for the package need to be updated. 15133 synchronized (mPackages) { 15134 try { 15135 updateSharedLibrariesLPw(pkg, null); 15136 } catch (PackageManagerException e) { 15137 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15138 } 15139 } 15140 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15141 // Do not run PackageDexOptimizer through the local performDexOpt 15142 // method because `pkg` is not in `mPackages` yet. 15143 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15144 null /* instructionSets */, false /* checkProfiles */, 15145 getCompilerFilterForReason(REASON_INSTALL)); 15146 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15147 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15148 String msg = "Extracting package failed for " + pkgName; 15149 res.setError(INSTALL_FAILED_DEXOPT, msg); 15150 return; 15151 } 15152 15153 // Notify BackgroundDexOptService that the package has been changed. 15154 // If this is an update of a package which used to fail to compile, 15155 // BDOS will remove it from its blacklist. 15156 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15157 } 15158 15159 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15160 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15161 return; 15162 } 15163 15164 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15165 15166 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15167 "installPackageLI")) { 15168 if (replace) { 15169 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15170 installerPackageName, res); 15171 } else { 15172 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15173 args.user, installerPackageName, volumeUuid, res); 15174 } 15175 } 15176 synchronized (mPackages) { 15177 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15178 if (ps != null) { 15179 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15180 } 15181 15182 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15183 for (int i = 0; i < childCount; i++) { 15184 PackageParser.Package childPkg = pkg.childPackages.get(i); 15185 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15186 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15187 if (childPs != null) { 15188 childRes.newUsers = childPs.queryInstalledUsers( 15189 sUserManager.getUserIds(), true); 15190 } 15191 } 15192 } 15193 } 15194 15195 private void startIntentFilterVerifications(int userId, boolean replacing, 15196 PackageParser.Package pkg) { 15197 if (mIntentFilterVerifierComponent == null) { 15198 Slog.w(TAG, "No IntentFilter verification will not be done as " 15199 + "there is no IntentFilterVerifier available!"); 15200 return; 15201 } 15202 15203 final int verifierUid = getPackageUid( 15204 mIntentFilterVerifierComponent.getPackageName(), 15205 MATCH_DEBUG_TRIAGED_MISSING, 15206 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15207 15208 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15209 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15210 mHandler.sendMessage(msg); 15211 15212 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15213 for (int i = 0; i < childCount; i++) { 15214 PackageParser.Package childPkg = pkg.childPackages.get(i); 15215 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15216 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15217 mHandler.sendMessage(msg); 15218 } 15219 } 15220 15221 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15222 PackageParser.Package pkg) { 15223 int size = pkg.activities.size(); 15224 if (size == 0) { 15225 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15226 "No activity, so no need to verify any IntentFilter!"); 15227 return; 15228 } 15229 15230 final boolean hasDomainURLs = hasDomainURLs(pkg); 15231 if (!hasDomainURLs) { 15232 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15233 "No domain URLs, so no need to verify any IntentFilter!"); 15234 return; 15235 } 15236 15237 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15238 + " if any IntentFilter from the " + size 15239 + " Activities needs verification ..."); 15240 15241 int count = 0; 15242 final String packageName = pkg.packageName; 15243 15244 synchronized (mPackages) { 15245 // If this is a new install and we see that we've already run verification for this 15246 // package, we have nothing to do: it means the state was restored from backup. 15247 if (!replacing) { 15248 IntentFilterVerificationInfo ivi = 15249 mSettings.getIntentFilterVerificationLPr(packageName); 15250 if (ivi != null) { 15251 if (DEBUG_DOMAIN_VERIFICATION) { 15252 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15253 + ivi.getStatusString()); 15254 } 15255 return; 15256 } 15257 } 15258 15259 // If any filters need to be verified, then all need to be. 15260 boolean needToVerify = false; 15261 for (PackageParser.Activity a : pkg.activities) { 15262 for (ActivityIntentInfo filter : a.intents) { 15263 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15264 if (DEBUG_DOMAIN_VERIFICATION) { 15265 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15266 } 15267 needToVerify = true; 15268 break; 15269 } 15270 } 15271 } 15272 15273 if (needToVerify) { 15274 final int verificationId = mIntentFilterVerificationToken++; 15275 for (PackageParser.Activity a : pkg.activities) { 15276 for (ActivityIntentInfo filter : a.intents) { 15277 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15278 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15279 "Verification needed for IntentFilter:" + filter.toString()); 15280 mIntentFilterVerifier.addOneIntentFilterVerification( 15281 verifierUid, userId, verificationId, filter, packageName); 15282 count++; 15283 } 15284 } 15285 } 15286 } 15287 } 15288 15289 if (count > 0) { 15290 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15291 + " IntentFilter verification" + (count > 1 ? "s" : "") 15292 + " for userId:" + userId); 15293 mIntentFilterVerifier.startVerifications(userId); 15294 } else { 15295 if (DEBUG_DOMAIN_VERIFICATION) { 15296 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15297 } 15298 } 15299 } 15300 15301 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15302 final ComponentName cn = filter.activity.getComponentName(); 15303 final String packageName = cn.getPackageName(); 15304 15305 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15306 packageName); 15307 if (ivi == null) { 15308 return true; 15309 } 15310 int status = ivi.getStatus(); 15311 switch (status) { 15312 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15313 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15314 return true; 15315 15316 default: 15317 // Nothing to do 15318 return false; 15319 } 15320 } 15321 15322 private static boolean isMultiArch(ApplicationInfo info) { 15323 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15324 } 15325 15326 private static boolean isExternal(PackageParser.Package pkg) { 15327 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15328 } 15329 15330 private static boolean isExternal(PackageSetting ps) { 15331 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15332 } 15333 15334 private static boolean isEphemeral(PackageParser.Package pkg) { 15335 return pkg.applicationInfo.isEphemeralApp(); 15336 } 15337 15338 private static boolean isEphemeral(PackageSetting ps) { 15339 return ps.pkg != null && isEphemeral(ps.pkg); 15340 } 15341 15342 private static boolean isSystemApp(PackageParser.Package pkg) { 15343 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15344 } 15345 15346 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15347 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15348 } 15349 15350 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15351 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15352 } 15353 15354 private static boolean isSystemApp(PackageSetting ps) { 15355 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15356 } 15357 15358 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15359 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15360 } 15361 15362 private int packageFlagsToInstallFlags(PackageSetting ps) { 15363 int installFlags = 0; 15364 if (isEphemeral(ps)) { 15365 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15366 } 15367 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15368 // This existing package was an external ASEC install when we have 15369 // the external flag without a UUID 15370 installFlags |= PackageManager.INSTALL_EXTERNAL; 15371 } 15372 if (ps.isForwardLocked()) { 15373 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15374 } 15375 return installFlags; 15376 } 15377 15378 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15379 if (isExternal(pkg)) { 15380 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15381 return StorageManager.UUID_PRIMARY_PHYSICAL; 15382 } else { 15383 return pkg.volumeUuid; 15384 } 15385 } else { 15386 return StorageManager.UUID_PRIVATE_INTERNAL; 15387 } 15388 } 15389 15390 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15391 if (isExternal(pkg)) { 15392 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15393 return mSettings.getExternalVersion(); 15394 } else { 15395 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15396 } 15397 } else { 15398 return mSettings.getInternalVersion(); 15399 } 15400 } 15401 15402 private void deleteTempPackageFiles() { 15403 final FilenameFilter filter = new FilenameFilter() { 15404 public boolean accept(File dir, String name) { 15405 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15406 } 15407 }; 15408 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15409 file.delete(); 15410 } 15411 } 15412 15413 @Override 15414 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15415 int flags) { 15416 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15417 flags); 15418 } 15419 15420 @Override 15421 public void deletePackage(final String packageName, 15422 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15423 mContext.enforceCallingOrSelfPermission( 15424 android.Manifest.permission.DELETE_PACKAGES, null); 15425 Preconditions.checkNotNull(packageName); 15426 Preconditions.checkNotNull(observer); 15427 final int uid = Binder.getCallingUid(); 15428 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15429 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15430 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15431 mContext.enforceCallingOrSelfPermission( 15432 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15433 "deletePackage for user " + userId); 15434 } 15435 15436 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15437 try { 15438 observer.onPackageDeleted(packageName, 15439 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15440 } catch (RemoteException re) { 15441 } 15442 return; 15443 } 15444 15445 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15446 try { 15447 observer.onPackageDeleted(packageName, 15448 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15449 } catch (RemoteException re) { 15450 } 15451 return; 15452 } 15453 15454 if (DEBUG_REMOVE) { 15455 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15456 + " deleteAllUsers: " + deleteAllUsers ); 15457 } 15458 // Queue up an async operation since the package deletion may take a little while. 15459 mHandler.post(new Runnable() { 15460 public void run() { 15461 mHandler.removeCallbacks(this); 15462 int returnCode; 15463 if (!deleteAllUsers) { 15464 returnCode = deletePackageX(packageName, userId, deleteFlags); 15465 } else { 15466 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15467 // If nobody is blocking uninstall, proceed with delete for all users 15468 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15469 returnCode = deletePackageX(packageName, userId, deleteFlags); 15470 } else { 15471 // Otherwise uninstall individually for users with blockUninstalls=false 15472 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15473 for (int userId : users) { 15474 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15475 returnCode = deletePackageX(packageName, userId, userFlags); 15476 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15477 Slog.w(TAG, "Package delete failed for user " + userId 15478 + ", returnCode " + returnCode); 15479 } 15480 } 15481 } 15482 // The app has only been marked uninstalled for certain users. 15483 // We still need to report that delete was blocked 15484 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15485 } 15486 } 15487 try { 15488 observer.onPackageDeleted(packageName, returnCode, null); 15489 } catch (RemoteException e) { 15490 Log.i(TAG, "Observer no longer exists."); 15491 } //end catch 15492 } //end run 15493 }); 15494 } 15495 15496 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15497 int[] result = EMPTY_INT_ARRAY; 15498 for (int userId : userIds) { 15499 if (getBlockUninstallForUser(packageName, userId)) { 15500 result = ArrayUtils.appendInt(result, userId); 15501 } 15502 } 15503 return result; 15504 } 15505 15506 @Override 15507 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15508 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15509 } 15510 15511 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15512 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15513 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15514 try { 15515 if (dpm != null) { 15516 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15517 /* callingUserOnly =*/ false); 15518 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15519 : deviceOwnerComponentName.getPackageName(); 15520 // Does the package contains the device owner? 15521 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15522 // this check is probably not needed, since DO should be registered as a device 15523 // admin on some user too. (Original bug for this: b/17657954) 15524 if (packageName.equals(deviceOwnerPackageName)) { 15525 return true; 15526 } 15527 // Does it contain a device admin for any user? 15528 int[] users; 15529 if (userId == UserHandle.USER_ALL) { 15530 users = sUserManager.getUserIds(); 15531 } else { 15532 users = new int[]{userId}; 15533 } 15534 for (int i = 0; i < users.length; ++i) { 15535 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15536 return true; 15537 } 15538 } 15539 } 15540 } catch (RemoteException e) { 15541 } 15542 return false; 15543 } 15544 15545 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15546 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15547 } 15548 15549 /** 15550 * This method is an internal method that could be get invoked either 15551 * to delete an installed package or to clean up a failed installation. 15552 * After deleting an installed package, a broadcast is sent to notify any 15553 * listeners that the package has been removed. For cleaning up a failed 15554 * installation, the broadcast is not necessary since the package's 15555 * installation wouldn't have sent the initial broadcast either 15556 * The key steps in deleting a package are 15557 * deleting the package information in internal structures like mPackages, 15558 * deleting the packages base directories through installd 15559 * updating mSettings to reflect current status 15560 * persisting settings for later use 15561 * sending a broadcast if necessary 15562 */ 15563 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15564 final PackageRemovedInfo info = new PackageRemovedInfo(); 15565 final boolean res; 15566 15567 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15568 ? UserHandle.ALL : new UserHandle(userId); 15569 15570 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15571 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15572 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15573 } 15574 15575 PackageSetting uninstalledPs = null; 15576 15577 // for the uninstall-updates case and restricted profiles, remember the per- 15578 // user handle installed state 15579 int[] allUsers; 15580 synchronized (mPackages) { 15581 uninstalledPs = mSettings.mPackages.get(packageName); 15582 if (uninstalledPs == null) { 15583 Slog.w(TAG, "Not removing non-existent package " + packageName); 15584 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15585 } 15586 allUsers = sUserManager.getUserIds(); 15587 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15588 } 15589 15590 synchronized (mInstallLock) { 15591 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15592 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15593 "deletePackageX")) { 15594 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15595 deleteFlags | REMOVE_CHATTY, info, true, null); 15596 } 15597 synchronized (mPackages) { 15598 if (res) { 15599 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15600 } 15601 } 15602 } 15603 15604 if (res) { 15605 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15606 info.sendPackageRemovedBroadcasts(killApp); 15607 info.sendSystemPackageUpdatedBroadcasts(); 15608 info.sendSystemPackageAppearedBroadcasts(); 15609 } 15610 // Force a gc here. 15611 Runtime.getRuntime().gc(); 15612 // Delete the resources here after sending the broadcast to let 15613 // other processes clean up before deleting resources. 15614 if (info.args != null) { 15615 synchronized (mInstallLock) { 15616 info.args.doPostDeleteLI(true); 15617 } 15618 } 15619 15620 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15621 } 15622 15623 class PackageRemovedInfo { 15624 String removedPackage; 15625 int uid = -1; 15626 int removedAppId = -1; 15627 int[] origUsers; 15628 int[] removedUsers = null; 15629 boolean isRemovedPackageSystemUpdate = false; 15630 boolean isUpdate; 15631 boolean dataRemoved; 15632 boolean removedForAllUsers; 15633 // Clean up resources deleted packages. 15634 InstallArgs args = null; 15635 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15636 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15637 15638 void sendPackageRemovedBroadcasts(boolean killApp) { 15639 sendPackageRemovedBroadcastInternal(killApp); 15640 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15641 for (int i = 0; i < childCount; i++) { 15642 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15643 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15644 } 15645 } 15646 15647 void sendSystemPackageUpdatedBroadcasts() { 15648 if (isRemovedPackageSystemUpdate) { 15649 sendSystemPackageUpdatedBroadcastsInternal(); 15650 final int childCount = (removedChildPackages != null) 15651 ? removedChildPackages.size() : 0; 15652 for (int i = 0; i < childCount; i++) { 15653 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15654 if (childInfo.isRemovedPackageSystemUpdate) { 15655 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15656 } 15657 } 15658 } 15659 } 15660 15661 void sendSystemPackageAppearedBroadcasts() { 15662 final int packageCount = (appearedChildPackages != null) 15663 ? appearedChildPackages.size() : 0; 15664 for (int i = 0; i < packageCount; i++) { 15665 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15666 for (int userId : installedInfo.newUsers) { 15667 sendPackageAddedForUser(installedInfo.name, true, 15668 UserHandle.getAppId(installedInfo.uid), userId); 15669 } 15670 } 15671 } 15672 15673 private void sendSystemPackageUpdatedBroadcastsInternal() { 15674 Bundle extras = new Bundle(2); 15675 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15676 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15677 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15678 extras, 0, null, null, null); 15679 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15680 extras, 0, null, null, null); 15681 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15682 null, 0, removedPackage, null, null); 15683 } 15684 15685 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15686 Bundle extras = new Bundle(2); 15687 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15688 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15689 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15690 if (isUpdate || isRemovedPackageSystemUpdate) { 15691 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15692 } 15693 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15694 if (removedPackage != null) { 15695 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15696 extras, 0, null, null, removedUsers); 15697 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15698 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15699 removedPackage, extras, 0, null, null, removedUsers); 15700 } 15701 } 15702 if (removedAppId >= 0) { 15703 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15704 removedUsers); 15705 } 15706 } 15707 } 15708 15709 /* 15710 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15711 * flag is not set, the data directory is removed as well. 15712 * make sure this flag is set for partially installed apps. If not its meaningless to 15713 * delete a partially installed application. 15714 */ 15715 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15716 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15717 String packageName = ps.name; 15718 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15719 // Retrieve object to delete permissions for shared user later on 15720 final PackageParser.Package deletedPkg; 15721 final PackageSetting deletedPs; 15722 // reader 15723 synchronized (mPackages) { 15724 deletedPkg = mPackages.get(packageName); 15725 deletedPs = mSettings.mPackages.get(packageName); 15726 if (outInfo != null) { 15727 outInfo.removedPackage = packageName; 15728 outInfo.removedUsers = deletedPs != null 15729 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15730 : null; 15731 } 15732 } 15733 15734 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15735 15736 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15737 final PackageParser.Package resolvedPkg; 15738 if (deletedPkg != null) { 15739 resolvedPkg = deletedPkg; 15740 } else { 15741 // We don't have a parsed package when it lives on an ejected 15742 // adopted storage device, so fake something together 15743 resolvedPkg = new PackageParser.Package(ps.name); 15744 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15745 } 15746 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15747 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15748 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15749 if (outInfo != null) { 15750 outInfo.dataRemoved = true; 15751 } 15752 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15753 } 15754 15755 // writer 15756 synchronized (mPackages) { 15757 if (deletedPs != null) { 15758 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15759 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15760 clearDefaultBrowserIfNeeded(packageName); 15761 if (outInfo != null) { 15762 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15763 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15764 } 15765 updatePermissionsLPw(deletedPs.name, null, 0); 15766 if (deletedPs.sharedUser != null) { 15767 // Remove permissions associated with package. Since runtime 15768 // permissions are per user we have to kill the removed package 15769 // or packages running under the shared user of the removed 15770 // package if revoking the permissions requested only by the removed 15771 // package is successful and this causes a change in gids. 15772 for (int userId : UserManagerService.getInstance().getUserIds()) { 15773 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15774 userId); 15775 if (userIdToKill == UserHandle.USER_ALL 15776 || userIdToKill >= UserHandle.USER_SYSTEM) { 15777 // If gids changed for this user, kill all affected packages. 15778 mHandler.post(new Runnable() { 15779 @Override 15780 public void run() { 15781 // This has to happen with no lock held. 15782 killApplication(deletedPs.name, deletedPs.appId, 15783 KILL_APP_REASON_GIDS_CHANGED); 15784 } 15785 }); 15786 break; 15787 } 15788 } 15789 } 15790 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15791 } 15792 // make sure to preserve per-user disabled state if this removal was just 15793 // a downgrade of a system app to the factory package 15794 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15795 if (DEBUG_REMOVE) { 15796 Slog.d(TAG, "Propagating install state across downgrade"); 15797 } 15798 for (int userId : allUserHandles) { 15799 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15800 if (DEBUG_REMOVE) { 15801 Slog.d(TAG, " user " + userId + " => " + installed); 15802 } 15803 ps.setInstalled(installed, userId); 15804 } 15805 } 15806 } 15807 // can downgrade to reader 15808 if (writeSettings) { 15809 // Save settings now 15810 mSettings.writeLPr(); 15811 } 15812 } 15813 if (outInfo != null) { 15814 // A user ID was deleted here. Go through all users and remove it 15815 // from KeyStore. 15816 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15817 } 15818 } 15819 15820 static boolean locationIsPrivileged(File path) { 15821 try { 15822 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15823 .getCanonicalPath(); 15824 return path.getCanonicalPath().startsWith(privilegedAppDir); 15825 } catch (IOException e) { 15826 Slog.e(TAG, "Unable to access code path " + path); 15827 } 15828 return false; 15829 } 15830 15831 /* 15832 * Tries to delete system package. 15833 */ 15834 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15835 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15836 boolean writeSettings) { 15837 if (deletedPs.parentPackageName != null) { 15838 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15839 return false; 15840 } 15841 15842 final boolean applyUserRestrictions 15843 = (allUserHandles != null) && (outInfo.origUsers != null); 15844 final PackageSetting disabledPs; 15845 // Confirm if the system package has been updated 15846 // An updated system app can be deleted. This will also have to restore 15847 // the system pkg from system partition 15848 // reader 15849 synchronized (mPackages) { 15850 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15851 } 15852 15853 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15854 + " disabledPs=" + disabledPs); 15855 15856 if (disabledPs == null) { 15857 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15858 return false; 15859 } else if (DEBUG_REMOVE) { 15860 Slog.d(TAG, "Deleting system pkg from data partition"); 15861 } 15862 15863 if (DEBUG_REMOVE) { 15864 if (applyUserRestrictions) { 15865 Slog.d(TAG, "Remembering install states:"); 15866 for (int userId : allUserHandles) { 15867 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15868 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15869 } 15870 } 15871 } 15872 15873 // Delete the updated package 15874 outInfo.isRemovedPackageSystemUpdate = true; 15875 if (outInfo.removedChildPackages != null) { 15876 final int childCount = (deletedPs.childPackageNames != null) 15877 ? deletedPs.childPackageNames.size() : 0; 15878 for (int i = 0; i < childCount; i++) { 15879 String childPackageName = deletedPs.childPackageNames.get(i); 15880 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15881 .contains(childPackageName)) { 15882 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15883 childPackageName); 15884 if (childInfo != null) { 15885 childInfo.isRemovedPackageSystemUpdate = true; 15886 } 15887 } 15888 } 15889 } 15890 15891 if (disabledPs.versionCode < deletedPs.versionCode) { 15892 // Delete data for downgrades 15893 flags &= ~PackageManager.DELETE_KEEP_DATA; 15894 } else { 15895 // Preserve data by setting flag 15896 flags |= PackageManager.DELETE_KEEP_DATA; 15897 } 15898 15899 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15900 outInfo, writeSettings, disabledPs.pkg); 15901 if (!ret) { 15902 return false; 15903 } 15904 15905 // writer 15906 synchronized (mPackages) { 15907 // Reinstate the old system package 15908 enableSystemPackageLPw(disabledPs.pkg); 15909 // Remove any native libraries from the upgraded package. 15910 removeNativeBinariesLI(deletedPs); 15911 } 15912 15913 // Install the system package 15914 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15915 int parseFlags = mDefParseFlags 15916 | PackageParser.PARSE_MUST_BE_APK 15917 | PackageParser.PARSE_IS_SYSTEM 15918 | PackageParser.PARSE_IS_SYSTEM_DIR; 15919 if (locationIsPrivileged(disabledPs.codePath)) { 15920 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15921 } 15922 15923 final PackageParser.Package newPkg; 15924 try { 15925 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15926 } catch (PackageManagerException e) { 15927 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15928 + e.getMessage()); 15929 return false; 15930 } 15931 15932 prepareAppDataAfterInstallLIF(newPkg); 15933 15934 // writer 15935 synchronized (mPackages) { 15936 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15937 15938 // Propagate the permissions state as we do not want to drop on the floor 15939 // runtime permissions. The update permissions method below will take 15940 // care of removing obsolete permissions and grant install permissions. 15941 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15942 updatePermissionsLPw(newPkg.packageName, newPkg, 15943 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15944 15945 if (applyUserRestrictions) { 15946 if (DEBUG_REMOVE) { 15947 Slog.d(TAG, "Propagating install state across reinstall"); 15948 } 15949 for (int userId : allUserHandles) { 15950 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15951 if (DEBUG_REMOVE) { 15952 Slog.d(TAG, " user " + userId + " => " + installed); 15953 } 15954 ps.setInstalled(installed, userId); 15955 15956 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15957 } 15958 // Regardless of writeSettings we need to ensure that this restriction 15959 // state propagation is persisted 15960 mSettings.writeAllUsersPackageRestrictionsLPr(); 15961 } 15962 // can downgrade to reader here 15963 if (writeSettings) { 15964 mSettings.writeLPr(); 15965 } 15966 } 15967 return true; 15968 } 15969 15970 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15971 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15972 PackageRemovedInfo outInfo, boolean writeSettings, 15973 PackageParser.Package replacingPackage) { 15974 synchronized (mPackages) { 15975 if (outInfo != null) { 15976 outInfo.uid = ps.appId; 15977 } 15978 15979 if (outInfo != null && outInfo.removedChildPackages != null) { 15980 final int childCount = (ps.childPackageNames != null) 15981 ? ps.childPackageNames.size() : 0; 15982 for (int i = 0; i < childCount; i++) { 15983 String childPackageName = ps.childPackageNames.get(i); 15984 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15985 if (childPs == null) { 15986 return false; 15987 } 15988 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15989 childPackageName); 15990 if (childInfo != null) { 15991 childInfo.uid = childPs.appId; 15992 } 15993 } 15994 } 15995 } 15996 15997 // Delete package data from internal structures and also remove data if flag is set 15998 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15999 16000 // Delete the child packages data 16001 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16002 for (int i = 0; i < childCount; i++) { 16003 PackageSetting childPs; 16004 synchronized (mPackages) { 16005 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16006 } 16007 if (childPs != null) { 16008 PackageRemovedInfo childOutInfo = (outInfo != null 16009 && outInfo.removedChildPackages != null) 16010 ? outInfo.removedChildPackages.get(childPs.name) : null; 16011 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16012 && (replacingPackage != null 16013 && !replacingPackage.hasChildPackage(childPs.name)) 16014 ? flags & ~DELETE_KEEP_DATA : flags; 16015 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16016 deleteFlags, writeSettings); 16017 } 16018 } 16019 16020 // Delete application code and resources only for parent packages 16021 if (ps.parentPackageName == null) { 16022 if (deleteCodeAndResources && (outInfo != null)) { 16023 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16024 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16025 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16026 } 16027 } 16028 16029 return true; 16030 } 16031 16032 @Override 16033 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16034 int userId) { 16035 mContext.enforceCallingOrSelfPermission( 16036 android.Manifest.permission.DELETE_PACKAGES, null); 16037 synchronized (mPackages) { 16038 PackageSetting ps = mSettings.mPackages.get(packageName); 16039 if (ps == null) { 16040 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16041 return false; 16042 } 16043 if (!ps.getInstalled(userId)) { 16044 // Can't block uninstall for an app that is not installed or enabled. 16045 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16046 return false; 16047 } 16048 ps.setBlockUninstall(blockUninstall, userId); 16049 mSettings.writePackageRestrictionsLPr(userId); 16050 } 16051 return true; 16052 } 16053 16054 @Override 16055 public boolean getBlockUninstallForUser(String packageName, int userId) { 16056 synchronized (mPackages) { 16057 PackageSetting ps = mSettings.mPackages.get(packageName); 16058 if (ps == null) { 16059 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16060 return false; 16061 } 16062 return ps.getBlockUninstall(userId); 16063 } 16064 } 16065 16066 @Override 16067 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16068 int callingUid = Binder.getCallingUid(); 16069 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16070 throw new SecurityException( 16071 "setRequiredForSystemUser can only be run by the system or root"); 16072 } 16073 synchronized (mPackages) { 16074 PackageSetting ps = mSettings.mPackages.get(packageName); 16075 if (ps == null) { 16076 Log.w(TAG, "Package doesn't exist: " + packageName); 16077 return false; 16078 } 16079 if (systemUserApp) { 16080 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16081 } else { 16082 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16083 } 16084 mSettings.writeLPr(); 16085 } 16086 return true; 16087 } 16088 16089 /* 16090 * This method handles package deletion in general 16091 */ 16092 private boolean deletePackageLIF(String packageName, UserHandle user, 16093 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16094 PackageRemovedInfo outInfo, boolean writeSettings, 16095 PackageParser.Package replacingPackage) { 16096 if (packageName == null) { 16097 Slog.w(TAG, "Attempt to delete null packageName."); 16098 return false; 16099 } 16100 16101 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16102 16103 PackageSetting ps; 16104 16105 synchronized (mPackages) { 16106 ps = mSettings.mPackages.get(packageName); 16107 if (ps == null) { 16108 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16109 return false; 16110 } 16111 16112 if (ps.parentPackageName != null && (!isSystemApp(ps) 16113 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16114 if (DEBUG_REMOVE) { 16115 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16116 + ((user == null) ? UserHandle.USER_ALL : user)); 16117 } 16118 final int removedUserId = (user != null) ? user.getIdentifier() 16119 : UserHandle.USER_ALL; 16120 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16121 return false; 16122 } 16123 markPackageUninstalledForUserLPw(ps, user); 16124 scheduleWritePackageRestrictionsLocked(user); 16125 return true; 16126 } 16127 } 16128 16129 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16130 && user.getIdentifier() != UserHandle.USER_ALL)) { 16131 // The caller is asking that the package only be deleted for a single 16132 // user. To do this, we just mark its uninstalled state and delete 16133 // its data. If this is a system app, we only allow this to happen if 16134 // they have set the special DELETE_SYSTEM_APP which requests different 16135 // semantics than normal for uninstalling system apps. 16136 markPackageUninstalledForUserLPw(ps, user); 16137 16138 if (!isSystemApp(ps)) { 16139 // Do not uninstall the APK if an app should be cached 16140 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16141 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16142 // Other user still have this package installed, so all 16143 // we need to do is clear this user's data and save that 16144 // it is uninstalled. 16145 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16146 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16147 return false; 16148 } 16149 scheduleWritePackageRestrictionsLocked(user); 16150 return true; 16151 } else { 16152 // We need to set it back to 'installed' so the uninstall 16153 // broadcasts will be sent correctly. 16154 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16155 ps.setInstalled(true, user.getIdentifier()); 16156 } 16157 } else { 16158 // This is a system app, so we assume that the 16159 // other users still have this package installed, so all 16160 // we need to do is clear this user's data and save that 16161 // it is uninstalled. 16162 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16163 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16164 return false; 16165 } 16166 scheduleWritePackageRestrictionsLocked(user); 16167 return true; 16168 } 16169 } 16170 16171 // If we are deleting a composite package for all users, keep track 16172 // of result for each child. 16173 if (ps.childPackageNames != null && outInfo != null) { 16174 synchronized (mPackages) { 16175 final int childCount = ps.childPackageNames.size(); 16176 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16177 for (int i = 0; i < childCount; i++) { 16178 String childPackageName = ps.childPackageNames.get(i); 16179 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16180 childInfo.removedPackage = childPackageName; 16181 outInfo.removedChildPackages.put(childPackageName, childInfo); 16182 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16183 if (childPs != null) { 16184 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16185 } 16186 } 16187 } 16188 } 16189 16190 boolean ret = false; 16191 if (isSystemApp(ps)) { 16192 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16193 // When an updated system application is deleted we delete the existing resources 16194 // as well and fall back to existing code in system partition 16195 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16196 } else { 16197 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16198 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16199 outInfo, writeSettings, replacingPackage); 16200 } 16201 16202 // Take a note whether we deleted the package for all users 16203 if (outInfo != null) { 16204 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16205 if (outInfo.removedChildPackages != null) { 16206 synchronized (mPackages) { 16207 final int childCount = outInfo.removedChildPackages.size(); 16208 for (int i = 0; i < childCount; i++) { 16209 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16210 if (childInfo != null) { 16211 childInfo.removedForAllUsers = mPackages.get( 16212 childInfo.removedPackage) == null; 16213 } 16214 } 16215 } 16216 } 16217 // If we uninstalled an update to a system app there may be some 16218 // child packages that appeared as they are declared in the system 16219 // app but were not declared in the update. 16220 if (isSystemApp(ps)) { 16221 synchronized (mPackages) { 16222 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16223 final int childCount = (updatedPs.childPackageNames != null) 16224 ? updatedPs.childPackageNames.size() : 0; 16225 for (int i = 0; i < childCount; i++) { 16226 String childPackageName = updatedPs.childPackageNames.get(i); 16227 if (outInfo.removedChildPackages == null 16228 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16229 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16230 if (childPs == null) { 16231 continue; 16232 } 16233 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16234 installRes.name = childPackageName; 16235 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16236 installRes.pkg = mPackages.get(childPackageName); 16237 installRes.uid = childPs.pkg.applicationInfo.uid; 16238 if (outInfo.appearedChildPackages == null) { 16239 outInfo.appearedChildPackages = new ArrayMap<>(); 16240 } 16241 outInfo.appearedChildPackages.put(childPackageName, installRes); 16242 } 16243 } 16244 } 16245 } 16246 } 16247 16248 return ret; 16249 } 16250 16251 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16252 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16253 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16254 for (int nextUserId : userIds) { 16255 if (DEBUG_REMOVE) { 16256 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16257 } 16258 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16259 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16260 false /*hidden*/, false /*suspended*/, null, null, null, 16261 false /*blockUninstall*/, 16262 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16263 } 16264 } 16265 16266 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16267 PackageRemovedInfo outInfo) { 16268 final PackageParser.Package pkg; 16269 synchronized (mPackages) { 16270 pkg = mPackages.get(ps.name); 16271 } 16272 16273 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16274 : new int[] {userId}; 16275 for (int nextUserId : userIds) { 16276 if (DEBUG_REMOVE) { 16277 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16278 + nextUserId); 16279 } 16280 16281 destroyAppDataLIF(pkg, userId, 16282 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16283 destroyAppProfilesLIF(pkg, userId); 16284 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16285 schedulePackageCleaning(ps.name, nextUserId, false); 16286 synchronized (mPackages) { 16287 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16288 scheduleWritePackageRestrictionsLocked(nextUserId); 16289 } 16290 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16291 } 16292 } 16293 16294 if (outInfo != null) { 16295 outInfo.removedPackage = ps.name; 16296 outInfo.removedAppId = ps.appId; 16297 outInfo.removedUsers = userIds; 16298 } 16299 16300 return true; 16301 } 16302 16303 private final class ClearStorageConnection implements ServiceConnection { 16304 IMediaContainerService mContainerService; 16305 16306 @Override 16307 public void onServiceConnected(ComponentName name, IBinder service) { 16308 synchronized (this) { 16309 mContainerService = IMediaContainerService.Stub.asInterface(service); 16310 notifyAll(); 16311 } 16312 } 16313 16314 @Override 16315 public void onServiceDisconnected(ComponentName name) { 16316 } 16317 } 16318 16319 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16320 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16321 16322 final boolean mounted; 16323 if (Environment.isExternalStorageEmulated()) { 16324 mounted = true; 16325 } else { 16326 final String status = Environment.getExternalStorageState(); 16327 16328 mounted = status.equals(Environment.MEDIA_MOUNTED) 16329 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16330 } 16331 16332 if (!mounted) { 16333 return; 16334 } 16335 16336 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16337 int[] users; 16338 if (userId == UserHandle.USER_ALL) { 16339 users = sUserManager.getUserIds(); 16340 } else { 16341 users = new int[] { userId }; 16342 } 16343 final ClearStorageConnection conn = new ClearStorageConnection(); 16344 if (mContext.bindServiceAsUser( 16345 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16346 try { 16347 for (int curUser : users) { 16348 long timeout = SystemClock.uptimeMillis() + 5000; 16349 synchronized (conn) { 16350 long now; 16351 while (conn.mContainerService == null && 16352 (now = SystemClock.uptimeMillis()) < timeout) { 16353 try { 16354 conn.wait(timeout - now); 16355 } catch (InterruptedException e) { 16356 } 16357 } 16358 } 16359 if (conn.mContainerService == null) { 16360 return; 16361 } 16362 16363 final UserEnvironment userEnv = new UserEnvironment(curUser); 16364 clearDirectory(conn.mContainerService, 16365 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16366 if (allData) { 16367 clearDirectory(conn.mContainerService, 16368 userEnv.buildExternalStorageAppDataDirs(packageName)); 16369 clearDirectory(conn.mContainerService, 16370 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16371 } 16372 } 16373 } finally { 16374 mContext.unbindService(conn); 16375 } 16376 } 16377 } 16378 16379 @Override 16380 public void clearApplicationProfileData(String packageName) { 16381 enforceSystemOrRoot("Only the system can clear all profile data"); 16382 16383 final PackageParser.Package pkg; 16384 synchronized (mPackages) { 16385 pkg = mPackages.get(packageName); 16386 } 16387 16388 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16389 synchronized (mInstallLock) { 16390 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16391 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16392 true /* removeBaseMarker */); 16393 } 16394 } 16395 } 16396 16397 @Override 16398 public void clearApplicationUserData(final String packageName, 16399 final IPackageDataObserver observer, final int userId) { 16400 mContext.enforceCallingOrSelfPermission( 16401 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16402 16403 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16404 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16405 16406 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16407 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16408 } 16409 // Queue up an async operation since the package deletion may take a little while. 16410 mHandler.post(new Runnable() { 16411 public void run() { 16412 mHandler.removeCallbacks(this); 16413 final boolean succeeded; 16414 try (PackageFreezer freezer = freezePackage(packageName, 16415 "clearApplicationUserData")) { 16416 synchronized (mInstallLock) { 16417 succeeded = clearApplicationUserDataLIF(packageName, userId); 16418 } 16419 clearExternalStorageDataSync(packageName, userId, true); 16420 } 16421 if (succeeded) { 16422 // invoke DeviceStorageMonitor's update method to clear any notifications 16423 DeviceStorageMonitorInternal dsm = LocalServices 16424 .getService(DeviceStorageMonitorInternal.class); 16425 if (dsm != null) { 16426 dsm.checkMemory(); 16427 } 16428 } 16429 if(observer != null) { 16430 try { 16431 observer.onRemoveCompleted(packageName, succeeded); 16432 } catch (RemoteException e) { 16433 Log.i(TAG, "Observer no longer exists."); 16434 } 16435 } //end if observer 16436 } //end run 16437 }); 16438 } 16439 16440 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16441 if (packageName == null) { 16442 Slog.w(TAG, "Attempt to delete null packageName."); 16443 return false; 16444 } 16445 16446 // Try finding details about the requested package 16447 PackageParser.Package pkg; 16448 synchronized (mPackages) { 16449 pkg = mPackages.get(packageName); 16450 if (pkg == null) { 16451 final PackageSetting ps = mSettings.mPackages.get(packageName); 16452 if (ps != null) { 16453 pkg = ps.pkg; 16454 } 16455 } 16456 16457 if (pkg == null) { 16458 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16459 return false; 16460 } 16461 16462 PackageSetting ps = (PackageSetting) pkg.mExtras; 16463 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16464 } 16465 16466 clearAppDataLIF(pkg, userId, 16467 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16468 16469 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16470 removeKeystoreDataIfNeeded(userId, appId); 16471 16472 UserManagerInternal umInternal = getUserManagerInternal(); 16473 final int flags; 16474 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16475 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16476 } else if (umInternal.isUserRunning(userId)) { 16477 flags = StorageManager.FLAG_STORAGE_DE; 16478 } else { 16479 flags = 0; 16480 } 16481 prepareAppDataContentsLIF(pkg, userId, flags); 16482 16483 return true; 16484 } 16485 16486 /** 16487 * Reverts user permission state changes (permissions and flags) in 16488 * all packages for a given user. 16489 * 16490 * @param userId The device user for which to do a reset. 16491 */ 16492 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16493 final int packageCount = mPackages.size(); 16494 for (int i = 0; i < packageCount; i++) { 16495 PackageParser.Package pkg = mPackages.valueAt(i); 16496 PackageSetting ps = (PackageSetting) pkg.mExtras; 16497 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16498 } 16499 } 16500 16501 private void resetNetworkPolicies(int userId) { 16502 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16503 } 16504 16505 /** 16506 * Reverts user permission state changes (permissions and flags). 16507 * 16508 * @param ps The package for which to reset. 16509 * @param userId The device user for which to do a reset. 16510 */ 16511 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16512 final PackageSetting ps, final int userId) { 16513 if (ps.pkg == null) { 16514 return; 16515 } 16516 16517 // These are flags that can change base on user actions. 16518 final int userSettableMask = FLAG_PERMISSION_USER_SET 16519 | FLAG_PERMISSION_USER_FIXED 16520 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16521 | FLAG_PERMISSION_REVIEW_REQUIRED; 16522 16523 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16524 | FLAG_PERMISSION_POLICY_FIXED; 16525 16526 boolean writeInstallPermissions = false; 16527 boolean writeRuntimePermissions = false; 16528 16529 final int permissionCount = ps.pkg.requestedPermissions.size(); 16530 for (int i = 0; i < permissionCount; i++) { 16531 String permission = ps.pkg.requestedPermissions.get(i); 16532 16533 BasePermission bp = mSettings.mPermissions.get(permission); 16534 if (bp == null) { 16535 continue; 16536 } 16537 16538 // If shared user we just reset the state to which only this app contributed. 16539 if (ps.sharedUser != null) { 16540 boolean used = false; 16541 final int packageCount = ps.sharedUser.packages.size(); 16542 for (int j = 0; j < packageCount; j++) { 16543 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16544 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16545 && pkg.pkg.requestedPermissions.contains(permission)) { 16546 used = true; 16547 break; 16548 } 16549 } 16550 if (used) { 16551 continue; 16552 } 16553 } 16554 16555 PermissionsState permissionsState = ps.getPermissionsState(); 16556 16557 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16558 16559 // Always clear the user settable flags. 16560 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16561 bp.name) != null; 16562 // If permission review is enabled and this is a legacy app, mark the 16563 // permission as requiring a review as this is the initial state. 16564 int flags = 0; 16565 if (Build.PERMISSIONS_REVIEW_REQUIRED 16566 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16567 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16568 } 16569 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16570 if (hasInstallState) { 16571 writeInstallPermissions = true; 16572 } else { 16573 writeRuntimePermissions = true; 16574 } 16575 } 16576 16577 // Below is only runtime permission handling. 16578 if (!bp.isRuntime()) { 16579 continue; 16580 } 16581 16582 // Never clobber system or policy. 16583 if ((oldFlags & policyOrSystemFlags) != 0) { 16584 continue; 16585 } 16586 16587 // If this permission was granted by default, make sure it is. 16588 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16589 if (permissionsState.grantRuntimePermission(bp, userId) 16590 != PERMISSION_OPERATION_FAILURE) { 16591 writeRuntimePermissions = true; 16592 } 16593 // If permission review is enabled the permissions for a legacy apps 16594 // are represented as constantly granted runtime ones, so don't revoke. 16595 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16596 // Otherwise, reset the permission. 16597 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16598 switch (revokeResult) { 16599 case PERMISSION_OPERATION_SUCCESS: 16600 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16601 writeRuntimePermissions = true; 16602 final int appId = ps.appId; 16603 mHandler.post(new Runnable() { 16604 @Override 16605 public void run() { 16606 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16607 } 16608 }); 16609 } break; 16610 } 16611 } 16612 } 16613 16614 // Synchronously write as we are taking permissions away. 16615 if (writeRuntimePermissions) { 16616 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16617 } 16618 16619 // Synchronously write as we are taking permissions away. 16620 if (writeInstallPermissions) { 16621 mSettings.writeLPr(); 16622 } 16623 } 16624 16625 /** 16626 * Remove entries from the keystore daemon. Will only remove it if the 16627 * {@code appId} is valid. 16628 */ 16629 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16630 if (appId < 0) { 16631 return; 16632 } 16633 16634 final KeyStore keyStore = KeyStore.getInstance(); 16635 if (keyStore != null) { 16636 if (userId == UserHandle.USER_ALL) { 16637 for (final int individual : sUserManager.getUserIds()) { 16638 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16639 } 16640 } else { 16641 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16642 } 16643 } else { 16644 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16645 } 16646 } 16647 16648 @Override 16649 public void deleteApplicationCacheFiles(final String packageName, 16650 final IPackageDataObserver observer) { 16651 final int userId = UserHandle.getCallingUserId(); 16652 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16653 } 16654 16655 @Override 16656 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16657 final IPackageDataObserver observer) { 16658 mContext.enforceCallingOrSelfPermission( 16659 android.Manifest.permission.DELETE_CACHE_FILES, null); 16660 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16661 /* requireFullPermission= */ true, /* checkShell= */ false, 16662 "delete application cache files"); 16663 16664 final PackageParser.Package pkg; 16665 synchronized (mPackages) { 16666 pkg = mPackages.get(packageName); 16667 } 16668 16669 // Queue up an async operation since the package deletion may take a little while. 16670 mHandler.post(new Runnable() { 16671 public void run() { 16672 synchronized (mInstallLock) { 16673 final int flags = StorageManager.FLAG_STORAGE_DE 16674 | StorageManager.FLAG_STORAGE_CE; 16675 // We're only clearing cache files, so we don't care if the 16676 // app is unfrozen and still able to run 16677 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16678 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16679 } 16680 clearExternalStorageDataSync(packageName, userId, false); 16681 if (observer != null) { 16682 try { 16683 observer.onRemoveCompleted(packageName, true); 16684 } catch (RemoteException e) { 16685 Log.i(TAG, "Observer no longer exists."); 16686 } 16687 } 16688 } 16689 }); 16690 } 16691 16692 @Override 16693 public void getPackageSizeInfo(final String packageName, int userHandle, 16694 final IPackageStatsObserver observer) { 16695 mContext.enforceCallingOrSelfPermission( 16696 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16697 if (packageName == null) { 16698 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16699 } 16700 16701 PackageStats stats = new PackageStats(packageName, userHandle); 16702 16703 /* 16704 * Queue up an async operation since the package measurement may take a 16705 * little while. 16706 */ 16707 Message msg = mHandler.obtainMessage(INIT_COPY); 16708 msg.obj = new MeasureParams(stats, observer); 16709 mHandler.sendMessage(msg); 16710 } 16711 16712 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16713 final PackageSetting ps; 16714 synchronized (mPackages) { 16715 ps = mSettings.mPackages.get(packageName); 16716 if (ps == null) { 16717 Slog.w(TAG, "Failed to find settings for " + packageName); 16718 return false; 16719 } 16720 } 16721 try { 16722 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16723 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16724 ps.getCeDataInode(userId), ps.codePathString, stats); 16725 } catch (InstallerException e) { 16726 Slog.w(TAG, String.valueOf(e)); 16727 return false; 16728 } 16729 16730 // For now, ignore code size of packages on system partition 16731 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16732 stats.codeSize = 0; 16733 } 16734 16735 return true; 16736 } 16737 16738 private int getUidTargetSdkVersionLockedLPr(int uid) { 16739 Object obj = mSettings.getUserIdLPr(uid); 16740 if (obj instanceof SharedUserSetting) { 16741 final SharedUserSetting sus = (SharedUserSetting) obj; 16742 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16743 final Iterator<PackageSetting> it = sus.packages.iterator(); 16744 while (it.hasNext()) { 16745 final PackageSetting ps = it.next(); 16746 if (ps.pkg != null) { 16747 int v = ps.pkg.applicationInfo.targetSdkVersion; 16748 if (v < vers) vers = v; 16749 } 16750 } 16751 return vers; 16752 } else if (obj instanceof PackageSetting) { 16753 final PackageSetting ps = (PackageSetting) obj; 16754 if (ps.pkg != null) { 16755 return ps.pkg.applicationInfo.targetSdkVersion; 16756 } 16757 } 16758 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16759 } 16760 16761 @Override 16762 public void addPreferredActivity(IntentFilter filter, int match, 16763 ComponentName[] set, ComponentName activity, int userId) { 16764 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16765 "Adding preferred"); 16766 } 16767 16768 private void addPreferredActivityInternal(IntentFilter filter, int match, 16769 ComponentName[] set, ComponentName activity, boolean always, int userId, 16770 String opname) { 16771 // writer 16772 int callingUid = Binder.getCallingUid(); 16773 enforceCrossUserPermission(callingUid, userId, 16774 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16775 if (filter.countActions() == 0) { 16776 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16777 return; 16778 } 16779 synchronized (mPackages) { 16780 if (mContext.checkCallingOrSelfPermission( 16781 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16782 != PackageManager.PERMISSION_GRANTED) { 16783 if (getUidTargetSdkVersionLockedLPr(callingUid) 16784 < Build.VERSION_CODES.FROYO) { 16785 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16786 + callingUid); 16787 return; 16788 } 16789 mContext.enforceCallingOrSelfPermission( 16790 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16791 } 16792 16793 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16794 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16795 + userId + ":"); 16796 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16797 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16798 scheduleWritePackageRestrictionsLocked(userId); 16799 } 16800 } 16801 16802 @Override 16803 public void replacePreferredActivity(IntentFilter filter, int match, 16804 ComponentName[] set, ComponentName activity, int userId) { 16805 if (filter.countActions() != 1) { 16806 throw new IllegalArgumentException( 16807 "replacePreferredActivity expects filter to have only 1 action."); 16808 } 16809 if (filter.countDataAuthorities() != 0 16810 || filter.countDataPaths() != 0 16811 || filter.countDataSchemes() > 1 16812 || filter.countDataTypes() != 0) { 16813 throw new IllegalArgumentException( 16814 "replacePreferredActivity expects filter to have no data authorities, " + 16815 "paths, or types; and at most one scheme."); 16816 } 16817 16818 final int callingUid = Binder.getCallingUid(); 16819 enforceCrossUserPermission(callingUid, userId, 16820 true /* requireFullPermission */, false /* checkShell */, 16821 "replace preferred activity"); 16822 synchronized (mPackages) { 16823 if (mContext.checkCallingOrSelfPermission( 16824 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16825 != PackageManager.PERMISSION_GRANTED) { 16826 if (getUidTargetSdkVersionLockedLPr(callingUid) 16827 < Build.VERSION_CODES.FROYO) { 16828 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16829 + Binder.getCallingUid()); 16830 return; 16831 } 16832 mContext.enforceCallingOrSelfPermission( 16833 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16834 } 16835 16836 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16837 if (pir != null) { 16838 // Get all of the existing entries that exactly match this filter. 16839 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16840 if (existing != null && existing.size() == 1) { 16841 PreferredActivity cur = existing.get(0); 16842 if (DEBUG_PREFERRED) { 16843 Slog.i(TAG, "Checking replace of preferred:"); 16844 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16845 if (!cur.mPref.mAlways) { 16846 Slog.i(TAG, " -- CUR; not mAlways!"); 16847 } else { 16848 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16849 Slog.i(TAG, " -- CUR: mSet=" 16850 + Arrays.toString(cur.mPref.mSetComponents)); 16851 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16852 Slog.i(TAG, " -- NEW: mMatch=" 16853 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16854 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16855 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16856 } 16857 } 16858 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16859 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16860 && cur.mPref.sameSet(set)) { 16861 // Setting the preferred activity to what it happens to be already 16862 if (DEBUG_PREFERRED) { 16863 Slog.i(TAG, "Replacing with same preferred activity " 16864 + cur.mPref.mShortComponent + " for user " 16865 + userId + ":"); 16866 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16867 } 16868 return; 16869 } 16870 } 16871 16872 if (existing != null) { 16873 if (DEBUG_PREFERRED) { 16874 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16875 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16876 } 16877 for (int i = 0; i < existing.size(); i++) { 16878 PreferredActivity pa = existing.get(i); 16879 if (DEBUG_PREFERRED) { 16880 Slog.i(TAG, "Removing existing preferred activity " 16881 + pa.mPref.mComponent + ":"); 16882 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16883 } 16884 pir.removeFilter(pa); 16885 } 16886 } 16887 } 16888 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16889 "Replacing preferred"); 16890 } 16891 } 16892 16893 @Override 16894 public void clearPackagePreferredActivities(String packageName) { 16895 final int uid = Binder.getCallingUid(); 16896 // writer 16897 synchronized (mPackages) { 16898 PackageParser.Package pkg = mPackages.get(packageName); 16899 if (pkg == null || pkg.applicationInfo.uid != uid) { 16900 if (mContext.checkCallingOrSelfPermission( 16901 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16902 != PackageManager.PERMISSION_GRANTED) { 16903 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16904 < Build.VERSION_CODES.FROYO) { 16905 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16906 + Binder.getCallingUid()); 16907 return; 16908 } 16909 mContext.enforceCallingOrSelfPermission( 16910 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16911 } 16912 } 16913 16914 int user = UserHandle.getCallingUserId(); 16915 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16916 scheduleWritePackageRestrictionsLocked(user); 16917 } 16918 } 16919 } 16920 16921 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16922 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16923 ArrayList<PreferredActivity> removed = null; 16924 boolean changed = false; 16925 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16926 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16927 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16928 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16929 continue; 16930 } 16931 Iterator<PreferredActivity> it = pir.filterIterator(); 16932 while (it.hasNext()) { 16933 PreferredActivity pa = it.next(); 16934 // Mark entry for removal only if it matches the package name 16935 // and the entry is of type "always". 16936 if (packageName == null || 16937 (pa.mPref.mComponent.getPackageName().equals(packageName) 16938 && pa.mPref.mAlways)) { 16939 if (removed == null) { 16940 removed = new ArrayList<PreferredActivity>(); 16941 } 16942 removed.add(pa); 16943 } 16944 } 16945 if (removed != null) { 16946 for (int j=0; j<removed.size(); j++) { 16947 PreferredActivity pa = removed.get(j); 16948 pir.removeFilter(pa); 16949 } 16950 changed = true; 16951 } 16952 } 16953 return changed; 16954 } 16955 16956 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16957 private void clearIntentFilterVerificationsLPw(int userId) { 16958 final int packageCount = mPackages.size(); 16959 for (int i = 0; i < packageCount; i++) { 16960 PackageParser.Package pkg = mPackages.valueAt(i); 16961 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16962 } 16963 } 16964 16965 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16966 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16967 if (userId == UserHandle.USER_ALL) { 16968 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16969 sUserManager.getUserIds())) { 16970 for (int oneUserId : sUserManager.getUserIds()) { 16971 scheduleWritePackageRestrictionsLocked(oneUserId); 16972 } 16973 } 16974 } else { 16975 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16976 scheduleWritePackageRestrictionsLocked(userId); 16977 } 16978 } 16979 } 16980 16981 void clearDefaultBrowserIfNeeded(String packageName) { 16982 for (int oneUserId : sUserManager.getUserIds()) { 16983 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16984 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16985 if (packageName.equals(defaultBrowserPackageName)) { 16986 setDefaultBrowserPackageName(null, oneUserId); 16987 } 16988 } 16989 } 16990 16991 @Override 16992 public void resetApplicationPreferences(int userId) { 16993 mContext.enforceCallingOrSelfPermission( 16994 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16995 final long identity = Binder.clearCallingIdentity(); 16996 // writer 16997 try { 16998 synchronized (mPackages) { 16999 clearPackagePreferredActivitiesLPw(null, userId); 17000 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17001 // TODO: We have to reset the default SMS and Phone. This requires 17002 // significant refactoring to keep all default apps in the package 17003 // manager (cleaner but more work) or have the services provide 17004 // callbacks to the package manager to request a default app reset. 17005 applyFactoryDefaultBrowserLPw(userId); 17006 clearIntentFilterVerificationsLPw(userId); 17007 primeDomainVerificationsLPw(userId); 17008 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17009 scheduleWritePackageRestrictionsLocked(userId); 17010 } 17011 resetNetworkPolicies(userId); 17012 } finally { 17013 Binder.restoreCallingIdentity(identity); 17014 } 17015 } 17016 17017 @Override 17018 public int getPreferredActivities(List<IntentFilter> outFilters, 17019 List<ComponentName> outActivities, String packageName) { 17020 17021 int num = 0; 17022 final int userId = UserHandle.getCallingUserId(); 17023 // reader 17024 synchronized (mPackages) { 17025 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17026 if (pir != null) { 17027 final Iterator<PreferredActivity> it = pir.filterIterator(); 17028 while (it.hasNext()) { 17029 final PreferredActivity pa = it.next(); 17030 if (packageName == null 17031 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17032 && pa.mPref.mAlways)) { 17033 if (outFilters != null) { 17034 outFilters.add(new IntentFilter(pa)); 17035 } 17036 if (outActivities != null) { 17037 outActivities.add(pa.mPref.mComponent); 17038 } 17039 } 17040 } 17041 } 17042 } 17043 17044 return num; 17045 } 17046 17047 @Override 17048 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17049 int userId) { 17050 int callingUid = Binder.getCallingUid(); 17051 if (callingUid != Process.SYSTEM_UID) { 17052 throw new SecurityException( 17053 "addPersistentPreferredActivity can only be run by the system"); 17054 } 17055 if (filter.countActions() == 0) { 17056 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17057 return; 17058 } 17059 synchronized (mPackages) { 17060 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17061 ":"); 17062 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17063 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17064 new PersistentPreferredActivity(filter, activity)); 17065 scheduleWritePackageRestrictionsLocked(userId); 17066 } 17067 } 17068 17069 @Override 17070 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17071 int callingUid = Binder.getCallingUid(); 17072 if (callingUid != Process.SYSTEM_UID) { 17073 throw new SecurityException( 17074 "clearPackagePersistentPreferredActivities can only be run by the system"); 17075 } 17076 ArrayList<PersistentPreferredActivity> removed = null; 17077 boolean changed = false; 17078 synchronized (mPackages) { 17079 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17080 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17081 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17082 .valueAt(i); 17083 if (userId != thisUserId) { 17084 continue; 17085 } 17086 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17087 while (it.hasNext()) { 17088 PersistentPreferredActivity ppa = it.next(); 17089 // Mark entry for removal only if it matches the package name. 17090 if (ppa.mComponent.getPackageName().equals(packageName)) { 17091 if (removed == null) { 17092 removed = new ArrayList<PersistentPreferredActivity>(); 17093 } 17094 removed.add(ppa); 17095 } 17096 } 17097 if (removed != null) { 17098 for (int j=0; j<removed.size(); j++) { 17099 PersistentPreferredActivity ppa = removed.get(j); 17100 ppir.removeFilter(ppa); 17101 } 17102 changed = true; 17103 } 17104 } 17105 17106 if (changed) { 17107 scheduleWritePackageRestrictionsLocked(userId); 17108 } 17109 } 17110 } 17111 17112 /** 17113 * Common machinery for picking apart a restored XML blob and passing 17114 * it to a caller-supplied functor to be applied to the running system. 17115 */ 17116 private void restoreFromXml(XmlPullParser parser, int userId, 17117 String expectedStartTag, BlobXmlRestorer functor) 17118 throws IOException, XmlPullParserException { 17119 int type; 17120 while ((type = parser.next()) != XmlPullParser.START_TAG 17121 && type != XmlPullParser.END_DOCUMENT) { 17122 } 17123 if (type != XmlPullParser.START_TAG) { 17124 // oops didn't find a start tag?! 17125 if (DEBUG_BACKUP) { 17126 Slog.e(TAG, "Didn't find start tag during restore"); 17127 } 17128 return; 17129 } 17130Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17131 // this is supposed to be TAG_PREFERRED_BACKUP 17132 if (!expectedStartTag.equals(parser.getName())) { 17133 if (DEBUG_BACKUP) { 17134 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17135 } 17136 return; 17137 } 17138 17139 // skip interfering stuff, then we're aligned with the backing implementation 17140 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17141Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17142 functor.apply(parser, userId); 17143 } 17144 17145 private interface BlobXmlRestorer { 17146 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17147 } 17148 17149 /** 17150 * Non-Binder method, support for the backup/restore mechanism: write the 17151 * full set of preferred activities in its canonical XML format. Returns the 17152 * XML output as a byte array, or null if there is none. 17153 */ 17154 @Override 17155 public byte[] getPreferredActivityBackup(int userId) { 17156 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17157 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17158 } 17159 17160 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17161 try { 17162 final XmlSerializer serializer = new FastXmlSerializer(); 17163 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17164 serializer.startDocument(null, true); 17165 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17166 17167 synchronized (mPackages) { 17168 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17169 } 17170 17171 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17172 serializer.endDocument(); 17173 serializer.flush(); 17174 } catch (Exception e) { 17175 if (DEBUG_BACKUP) { 17176 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17177 } 17178 return null; 17179 } 17180 17181 return dataStream.toByteArray(); 17182 } 17183 17184 @Override 17185 public void restorePreferredActivities(byte[] backup, int userId) { 17186 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17187 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17188 } 17189 17190 try { 17191 final XmlPullParser parser = Xml.newPullParser(); 17192 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17193 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17194 new BlobXmlRestorer() { 17195 @Override 17196 public void apply(XmlPullParser parser, int userId) 17197 throws XmlPullParserException, IOException { 17198 synchronized (mPackages) { 17199 mSettings.readPreferredActivitiesLPw(parser, userId); 17200 } 17201 } 17202 } ); 17203 } catch (Exception e) { 17204 if (DEBUG_BACKUP) { 17205 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17206 } 17207 } 17208 } 17209 17210 /** 17211 * Non-Binder method, support for the backup/restore mechanism: write the 17212 * default browser (etc) settings in its canonical XML format. Returns the default 17213 * browser XML representation as a byte array, or null if there is none. 17214 */ 17215 @Override 17216 public byte[] getDefaultAppsBackup(int userId) { 17217 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17218 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17219 } 17220 17221 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17222 try { 17223 final XmlSerializer serializer = new FastXmlSerializer(); 17224 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17225 serializer.startDocument(null, true); 17226 serializer.startTag(null, TAG_DEFAULT_APPS); 17227 17228 synchronized (mPackages) { 17229 mSettings.writeDefaultAppsLPr(serializer, userId); 17230 } 17231 17232 serializer.endTag(null, TAG_DEFAULT_APPS); 17233 serializer.endDocument(); 17234 serializer.flush(); 17235 } catch (Exception e) { 17236 if (DEBUG_BACKUP) { 17237 Slog.e(TAG, "Unable to write default apps for backup", e); 17238 } 17239 return null; 17240 } 17241 17242 return dataStream.toByteArray(); 17243 } 17244 17245 @Override 17246 public void restoreDefaultApps(byte[] backup, int userId) { 17247 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17248 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17249 } 17250 17251 try { 17252 final XmlPullParser parser = Xml.newPullParser(); 17253 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17254 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17255 new BlobXmlRestorer() { 17256 @Override 17257 public void apply(XmlPullParser parser, int userId) 17258 throws XmlPullParserException, IOException { 17259 synchronized (mPackages) { 17260 mSettings.readDefaultAppsLPw(parser, userId); 17261 } 17262 } 17263 } ); 17264 } catch (Exception e) { 17265 if (DEBUG_BACKUP) { 17266 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17267 } 17268 } 17269 } 17270 17271 @Override 17272 public byte[] getIntentFilterVerificationBackup(int userId) { 17273 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17274 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17275 } 17276 17277 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17278 try { 17279 final XmlSerializer serializer = new FastXmlSerializer(); 17280 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17281 serializer.startDocument(null, true); 17282 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17283 17284 synchronized (mPackages) { 17285 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17286 } 17287 17288 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17289 serializer.endDocument(); 17290 serializer.flush(); 17291 } catch (Exception e) { 17292 if (DEBUG_BACKUP) { 17293 Slog.e(TAG, "Unable to write default apps for backup", e); 17294 } 17295 return null; 17296 } 17297 17298 return dataStream.toByteArray(); 17299 } 17300 17301 @Override 17302 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17303 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17304 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17305 } 17306 17307 try { 17308 final XmlPullParser parser = Xml.newPullParser(); 17309 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17310 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17311 new BlobXmlRestorer() { 17312 @Override 17313 public void apply(XmlPullParser parser, int userId) 17314 throws XmlPullParserException, IOException { 17315 synchronized (mPackages) { 17316 mSettings.readAllDomainVerificationsLPr(parser, userId); 17317 mSettings.writeLPr(); 17318 } 17319 } 17320 } ); 17321 } catch (Exception e) { 17322 if (DEBUG_BACKUP) { 17323 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17324 } 17325 } 17326 } 17327 17328 @Override 17329 public byte[] getPermissionGrantBackup(int userId) { 17330 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17331 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17332 } 17333 17334 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17335 try { 17336 final XmlSerializer serializer = new FastXmlSerializer(); 17337 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17338 serializer.startDocument(null, true); 17339 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17340 17341 synchronized (mPackages) { 17342 serializeRuntimePermissionGrantsLPr(serializer, userId); 17343 } 17344 17345 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17346 serializer.endDocument(); 17347 serializer.flush(); 17348 } catch (Exception e) { 17349 if (DEBUG_BACKUP) { 17350 Slog.e(TAG, "Unable to write default apps for backup", e); 17351 } 17352 return null; 17353 } 17354 17355 return dataStream.toByteArray(); 17356 } 17357 17358 @Override 17359 public void restorePermissionGrants(byte[] backup, int userId) { 17360 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17361 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17362 } 17363 17364 try { 17365 final XmlPullParser parser = Xml.newPullParser(); 17366 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17367 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17368 new BlobXmlRestorer() { 17369 @Override 17370 public void apply(XmlPullParser parser, int userId) 17371 throws XmlPullParserException, IOException { 17372 synchronized (mPackages) { 17373 processRestoredPermissionGrantsLPr(parser, userId); 17374 } 17375 } 17376 } ); 17377 } catch (Exception e) { 17378 if (DEBUG_BACKUP) { 17379 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17380 } 17381 } 17382 } 17383 17384 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17385 throws IOException { 17386 serializer.startTag(null, TAG_ALL_GRANTS); 17387 17388 final int N = mSettings.mPackages.size(); 17389 for (int i = 0; i < N; i++) { 17390 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17391 boolean pkgGrantsKnown = false; 17392 17393 PermissionsState packagePerms = ps.getPermissionsState(); 17394 17395 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17396 final int grantFlags = state.getFlags(); 17397 // only look at grants that are not system/policy fixed 17398 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17399 final boolean isGranted = state.isGranted(); 17400 // And only back up the user-twiddled state bits 17401 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17402 final String packageName = mSettings.mPackages.keyAt(i); 17403 if (!pkgGrantsKnown) { 17404 serializer.startTag(null, TAG_GRANT); 17405 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17406 pkgGrantsKnown = true; 17407 } 17408 17409 final boolean userSet = 17410 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17411 final boolean userFixed = 17412 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17413 final boolean revoke = 17414 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17415 17416 serializer.startTag(null, TAG_PERMISSION); 17417 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17418 if (isGranted) { 17419 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17420 } 17421 if (userSet) { 17422 serializer.attribute(null, ATTR_USER_SET, "true"); 17423 } 17424 if (userFixed) { 17425 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17426 } 17427 if (revoke) { 17428 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17429 } 17430 serializer.endTag(null, TAG_PERMISSION); 17431 } 17432 } 17433 } 17434 17435 if (pkgGrantsKnown) { 17436 serializer.endTag(null, TAG_GRANT); 17437 } 17438 } 17439 17440 serializer.endTag(null, TAG_ALL_GRANTS); 17441 } 17442 17443 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17444 throws XmlPullParserException, IOException { 17445 String pkgName = null; 17446 int outerDepth = parser.getDepth(); 17447 int type; 17448 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17449 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17450 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17451 continue; 17452 } 17453 17454 final String tagName = parser.getName(); 17455 if (tagName.equals(TAG_GRANT)) { 17456 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17457 if (DEBUG_BACKUP) { 17458 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17459 } 17460 } else if (tagName.equals(TAG_PERMISSION)) { 17461 17462 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17463 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17464 17465 int newFlagSet = 0; 17466 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17467 newFlagSet |= FLAG_PERMISSION_USER_SET; 17468 } 17469 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17470 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17471 } 17472 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17473 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17474 } 17475 if (DEBUG_BACKUP) { 17476 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17477 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17478 } 17479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17480 if (ps != null) { 17481 // Already installed so we apply the grant immediately 17482 if (DEBUG_BACKUP) { 17483 Slog.v(TAG, " + already installed; applying"); 17484 } 17485 PermissionsState perms = ps.getPermissionsState(); 17486 BasePermission bp = mSettings.mPermissions.get(permName); 17487 if (bp != null) { 17488 if (isGranted) { 17489 perms.grantRuntimePermission(bp, userId); 17490 } 17491 if (newFlagSet != 0) { 17492 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17493 } 17494 } 17495 } else { 17496 // Need to wait for post-restore install to apply the grant 17497 if (DEBUG_BACKUP) { 17498 Slog.v(TAG, " - not yet installed; saving for later"); 17499 } 17500 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17501 isGranted, newFlagSet, userId); 17502 } 17503 } else { 17504 PackageManagerService.reportSettingsProblem(Log.WARN, 17505 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17506 XmlUtils.skipCurrentTag(parser); 17507 } 17508 } 17509 17510 scheduleWriteSettingsLocked(); 17511 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17512 } 17513 17514 @Override 17515 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17516 int sourceUserId, int targetUserId, int flags) { 17517 mContext.enforceCallingOrSelfPermission( 17518 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17519 int callingUid = Binder.getCallingUid(); 17520 enforceOwnerRights(ownerPackage, callingUid); 17521 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17522 if (intentFilter.countActions() == 0) { 17523 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17524 return; 17525 } 17526 synchronized (mPackages) { 17527 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17528 ownerPackage, targetUserId, flags); 17529 CrossProfileIntentResolver resolver = 17530 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17531 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17532 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17533 if (existing != null) { 17534 int size = existing.size(); 17535 for (int i = 0; i < size; i++) { 17536 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17537 return; 17538 } 17539 } 17540 } 17541 resolver.addFilter(newFilter); 17542 scheduleWritePackageRestrictionsLocked(sourceUserId); 17543 } 17544 } 17545 17546 @Override 17547 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17548 mContext.enforceCallingOrSelfPermission( 17549 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17550 int callingUid = Binder.getCallingUid(); 17551 enforceOwnerRights(ownerPackage, callingUid); 17552 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17553 synchronized (mPackages) { 17554 CrossProfileIntentResolver resolver = 17555 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17556 ArraySet<CrossProfileIntentFilter> set = 17557 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17558 for (CrossProfileIntentFilter filter : set) { 17559 if (filter.getOwnerPackage().equals(ownerPackage)) { 17560 resolver.removeFilter(filter); 17561 } 17562 } 17563 scheduleWritePackageRestrictionsLocked(sourceUserId); 17564 } 17565 } 17566 17567 // Enforcing that callingUid is owning pkg on userId 17568 private void enforceOwnerRights(String pkg, int callingUid) { 17569 // The system owns everything. 17570 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17571 return; 17572 } 17573 int callingUserId = UserHandle.getUserId(callingUid); 17574 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17575 if (pi == null) { 17576 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17577 + callingUserId); 17578 } 17579 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17580 throw new SecurityException("Calling uid " + callingUid 17581 + " does not own package " + pkg); 17582 } 17583 } 17584 17585 @Override 17586 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17587 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17588 } 17589 17590 private Intent getHomeIntent() { 17591 Intent intent = new Intent(Intent.ACTION_MAIN); 17592 intent.addCategory(Intent.CATEGORY_HOME); 17593 return intent; 17594 } 17595 17596 private IntentFilter getHomeFilter() { 17597 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17598 filter.addCategory(Intent.CATEGORY_HOME); 17599 filter.addCategory(Intent.CATEGORY_DEFAULT); 17600 return filter; 17601 } 17602 17603 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17604 int userId) { 17605 Intent intent = getHomeIntent(); 17606 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17607 PackageManager.GET_META_DATA, userId); 17608 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17609 true, false, false, userId); 17610 17611 allHomeCandidates.clear(); 17612 if (list != null) { 17613 for (ResolveInfo ri : list) { 17614 allHomeCandidates.add(ri); 17615 } 17616 } 17617 return (preferred == null || preferred.activityInfo == null) 17618 ? null 17619 : new ComponentName(preferred.activityInfo.packageName, 17620 preferred.activityInfo.name); 17621 } 17622 17623 @Override 17624 public void setHomeActivity(ComponentName comp, int userId) { 17625 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17626 getHomeActivitiesAsUser(homeActivities, userId); 17627 17628 boolean found = false; 17629 17630 final int size = homeActivities.size(); 17631 final ComponentName[] set = new ComponentName[size]; 17632 for (int i = 0; i < size; i++) { 17633 final ResolveInfo candidate = homeActivities.get(i); 17634 final ActivityInfo info = candidate.activityInfo; 17635 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17636 set[i] = activityName; 17637 if (!found && activityName.equals(comp)) { 17638 found = true; 17639 } 17640 } 17641 if (!found) { 17642 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17643 + userId); 17644 } 17645 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17646 set, comp, userId); 17647 } 17648 17649 private @Nullable String getSetupWizardPackageName() { 17650 final Intent intent = new Intent(Intent.ACTION_MAIN); 17651 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17652 17653 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17654 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17655 | MATCH_DISABLED_COMPONENTS, 17656 UserHandle.myUserId()); 17657 if (matches.size() == 1) { 17658 return matches.get(0).getComponentInfo().packageName; 17659 } else { 17660 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17661 + ": matches=" + matches); 17662 return null; 17663 } 17664 } 17665 17666 @Override 17667 public void setApplicationEnabledSetting(String appPackageName, 17668 int newState, int flags, int userId, String callingPackage) { 17669 if (!sUserManager.exists(userId)) return; 17670 if (callingPackage == null) { 17671 callingPackage = Integer.toString(Binder.getCallingUid()); 17672 } 17673 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17674 } 17675 17676 @Override 17677 public void setComponentEnabledSetting(ComponentName componentName, 17678 int newState, int flags, int userId) { 17679 if (!sUserManager.exists(userId)) return; 17680 setEnabledSetting(componentName.getPackageName(), 17681 componentName.getClassName(), newState, flags, userId, null); 17682 } 17683 17684 private void setEnabledSetting(final String packageName, String className, int newState, 17685 final int flags, int userId, String callingPackage) { 17686 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17687 || newState == COMPONENT_ENABLED_STATE_ENABLED 17688 || newState == COMPONENT_ENABLED_STATE_DISABLED 17689 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17690 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17691 throw new IllegalArgumentException("Invalid new component state: " 17692 + newState); 17693 } 17694 PackageSetting pkgSetting; 17695 final int uid = Binder.getCallingUid(); 17696 final int permission; 17697 if (uid == Process.SYSTEM_UID) { 17698 permission = PackageManager.PERMISSION_GRANTED; 17699 } else { 17700 permission = mContext.checkCallingOrSelfPermission( 17701 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17702 } 17703 enforceCrossUserPermission(uid, userId, 17704 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17705 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17706 boolean sendNow = false; 17707 boolean isApp = (className == null); 17708 String componentName = isApp ? packageName : className; 17709 int packageUid = -1; 17710 ArrayList<String> components; 17711 17712 // writer 17713 synchronized (mPackages) { 17714 pkgSetting = mSettings.mPackages.get(packageName); 17715 if (pkgSetting == null) { 17716 if (className == null) { 17717 throw new IllegalArgumentException("Unknown package: " + packageName); 17718 } 17719 throw new IllegalArgumentException( 17720 "Unknown component: " + packageName + "/" + className); 17721 } 17722 } 17723 17724 // Limit who can change which apps 17725 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17726 // Don't allow apps that don't have permission to modify other apps 17727 if (!allowedByPermission) { 17728 throw new SecurityException( 17729 "Permission Denial: attempt to change component state from pid=" 17730 + Binder.getCallingPid() 17731 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17732 } 17733 // Don't allow changing profile and device owners. 17734 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17735 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17736 } 17737 } 17738 17739 synchronized (mPackages) { 17740 if (uid == Process.SHELL_UID) { 17741 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17742 int oldState = pkgSetting.getEnabled(userId); 17743 if (className == null 17744 && 17745 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17746 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17747 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17748 && 17749 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17750 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17751 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17752 // ok 17753 } else { 17754 throw new SecurityException( 17755 "Shell cannot change component state for " + packageName + "/" 17756 + className + " to " + newState); 17757 } 17758 } 17759 if (className == null) { 17760 // We're dealing with an application/package level state change 17761 if (pkgSetting.getEnabled(userId) == newState) { 17762 // Nothing to do 17763 return; 17764 } 17765 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17766 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17767 // Don't care about who enables an app. 17768 callingPackage = null; 17769 } 17770 pkgSetting.setEnabled(newState, userId, callingPackage); 17771 // pkgSetting.pkg.mSetEnabled = newState; 17772 } else { 17773 // We're dealing with a component level state change 17774 // First, verify that this is a valid class name. 17775 PackageParser.Package pkg = pkgSetting.pkg; 17776 if (pkg == null || !pkg.hasComponentClassName(className)) { 17777 if (pkg != null && 17778 pkg.applicationInfo.targetSdkVersion >= 17779 Build.VERSION_CODES.JELLY_BEAN) { 17780 throw new IllegalArgumentException("Component class " + className 17781 + " does not exist in " + packageName); 17782 } else { 17783 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17784 + className + " does not exist in " + packageName); 17785 } 17786 } 17787 switch (newState) { 17788 case COMPONENT_ENABLED_STATE_ENABLED: 17789 if (!pkgSetting.enableComponentLPw(className, userId)) { 17790 return; 17791 } 17792 break; 17793 case COMPONENT_ENABLED_STATE_DISABLED: 17794 if (!pkgSetting.disableComponentLPw(className, userId)) { 17795 return; 17796 } 17797 break; 17798 case COMPONENT_ENABLED_STATE_DEFAULT: 17799 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17800 return; 17801 } 17802 break; 17803 default: 17804 Slog.e(TAG, "Invalid new component state: " + newState); 17805 return; 17806 } 17807 } 17808 scheduleWritePackageRestrictionsLocked(userId); 17809 components = mPendingBroadcasts.get(userId, packageName); 17810 final boolean newPackage = components == null; 17811 if (newPackage) { 17812 components = new ArrayList<String>(); 17813 } 17814 if (!components.contains(componentName)) { 17815 components.add(componentName); 17816 } 17817 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17818 sendNow = true; 17819 // Purge entry from pending broadcast list if another one exists already 17820 // since we are sending one right away. 17821 mPendingBroadcasts.remove(userId, packageName); 17822 } else { 17823 if (newPackage) { 17824 mPendingBroadcasts.put(userId, packageName, components); 17825 } 17826 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17827 // Schedule a message 17828 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17829 } 17830 } 17831 } 17832 17833 long callingId = Binder.clearCallingIdentity(); 17834 try { 17835 if (sendNow) { 17836 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17837 sendPackageChangedBroadcast(packageName, 17838 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17839 } 17840 } finally { 17841 Binder.restoreCallingIdentity(callingId); 17842 } 17843 } 17844 17845 @Override 17846 public void flushPackageRestrictionsAsUser(int userId) { 17847 if (!sUserManager.exists(userId)) { 17848 return; 17849 } 17850 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17851 false /* checkShell */, "flushPackageRestrictions"); 17852 synchronized (mPackages) { 17853 mSettings.writePackageRestrictionsLPr(userId); 17854 mDirtyUsers.remove(userId); 17855 if (mDirtyUsers.isEmpty()) { 17856 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17857 } 17858 } 17859 } 17860 17861 private void sendPackageChangedBroadcast(String packageName, 17862 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17863 if (DEBUG_INSTALL) 17864 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17865 + componentNames); 17866 Bundle extras = new Bundle(4); 17867 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17868 String nameList[] = new String[componentNames.size()]; 17869 componentNames.toArray(nameList); 17870 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17871 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17872 extras.putInt(Intent.EXTRA_UID, packageUid); 17873 // If this is not reporting a change of the overall package, then only send it 17874 // to registered receivers. We don't want to launch a swath of apps for every 17875 // little component state change. 17876 final int flags = !componentNames.contains(packageName) 17877 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17878 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17879 new int[] {UserHandle.getUserId(packageUid)}); 17880 } 17881 17882 @Override 17883 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17884 if (!sUserManager.exists(userId)) return; 17885 final int uid = Binder.getCallingUid(); 17886 final int permission = mContext.checkCallingOrSelfPermission( 17887 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17888 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17889 enforceCrossUserPermission(uid, userId, 17890 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17891 // writer 17892 synchronized (mPackages) { 17893 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17894 allowedByPermission, uid, userId)) { 17895 scheduleWritePackageRestrictionsLocked(userId); 17896 } 17897 } 17898 } 17899 17900 @Override 17901 public String getInstallerPackageName(String packageName) { 17902 // reader 17903 synchronized (mPackages) { 17904 return mSettings.getInstallerPackageNameLPr(packageName); 17905 } 17906 } 17907 17908 public boolean isOrphaned(String packageName) { 17909 // reader 17910 synchronized (mPackages) { 17911 return mSettings.isOrphaned(packageName); 17912 } 17913 } 17914 17915 @Override 17916 public int getApplicationEnabledSetting(String packageName, int userId) { 17917 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17918 int uid = Binder.getCallingUid(); 17919 enforceCrossUserPermission(uid, userId, 17920 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17921 // reader 17922 synchronized (mPackages) { 17923 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17924 } 17925 } 17926 17927 @Override 17928 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17929 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17930 int uid = Binder.getCallingUid(); 17931 enforceCrossUserPermission(uid, userId, 17932 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17933 // reader 17934 synchronized (mPackages) { 17935 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17936 } 17937 } 17938 17939 @Override 17940 public void enterSafeMode() { 17941 enforceSystemOrRoot("Only the system can request entering safe mode"); 17942 17943 if (!mSystemReady) { 17944 mSafeMode = true; 17945 } 17946 } 17947 17948 @Override 17949 public void systemReady() { 17950 mSystemReady = true; 17951 17952 // Read the compatibilty setting when the system is ready. 17953 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17954 mContext.getContentResolver(), 17955 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17956 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17957 if (DEBUG_SETTINGS) { 17958 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17959 } 17960 17961 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17962 17963 synchronized (mPackages) { 17964 // Verify that all of the preferred activity components actually 17965 // exist. It is possible for applications to be updated and at 17966 // that point remove a previously declared activity component that 17967 // had been set as a preferred activity. We try to clean this up 17968 // the next time we encounter that preferred activity, but it is 17969 // possible for the user flow to never be able to return to that 17970 // situation so here we do a sanity check to make sure we haven't 17971 // left any junk around. 17972 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17973 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17974 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17975 removed.clear(); 17976 for (PreferredActivity pa : pir.filterSet()) { 17977 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17978 removed.add(pa); 17979 } 17980 } 17981 if (removed.size() > 0) { 17982 for (int r=0; r<removed.size(); r++) { 17983 PreferredActivity pa = removed.get(r); 17984 Slog.w(TAG, "Removing dangling preferred activity: " 17985 + pa.mPref.mComponent); 17986 pir.removeFilter(pa); 17987 } 17988 mSettings.writePackageRestrictionsLPr( 17989 mSettings.mPreferredActivities.keyAt(i)); 17990 } 17991 } 17992 17993 for (int userId : UserManagerService.getInstance().getUserIds()) { 17994 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17995 grantPermissionsUserIds = ArrayUtils.appendInt( 17996 grantPermissionsUserIds, userId); 17997 } 17998 } 17999 } 18000 sUserManager.systemReady(); 18001 18002 // If we upgraded grant all default permissions before kicking off. 18003 for (int userId : grantPermissionsUserIds) { 18004 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18005 } 18006 18007 // Kick off any messages waiting for system ready 18008 if (mPostSystemReadyMessages != null) { 18009 for (Message msg : mPostSystemReadyMessages) { 18010 msg.sendToTarget(); 18011 } 18012 mPostSystemReadyMessages = null; 18013 } 18014 18015 // Watch for external volumes that come and go over time 18016 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18017 storage.registerListener(mStorageListener); 18018 18019 mInstallerService.systemReady(); 18020 mPackageDexOptimizer.systemReady(); 18021 18022 MountServiceInternal mountServiceInternal = LocalServices.getService( 18023 MountServiceInternal.class); 18024 mountServiceInternal.addExternalStoragePolicy( 18025 new MountServiceInternal.ExternalStorageMountPolicy() { 18026 @Override 18027 public int getMountMode(int uid, String packageName) { 18028 if (Process.isIsolated(uid)) { 18029 return Zygote.MOUNT_EXTERNAL_NONE; 18030 } 18031 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18032 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18033 } 18034 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18035 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18036 } 18037 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18038 return Zygote.MOUNT_EXTERNAL_READ; 18039 } 18040 return Zygote.MOUNT_EXTERNAL_WRITE; 18041 } 18042 18043 @Override 18044 public boolean hasExternalStorage(int uid, String packageName) { 18045 return true; 18046 } 18047 }); 18048 18049 // Now that we're mostly running, clean up stale users and apps 18050 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18051 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18052 } 18053 18054 @Override 18055 public boolean isSafeMode() { 18056 return mSafeMode; 18057 } 18058 18059 @Override 18060 public boolean hasSystemUidErrors() { 18061 return mHasSystemUidErrors; 18062 } 18063 18064 static String arrayToString(int[] array) { 18065 StringBuffer buf = new StringBuffer(128); 18066 buf.append('['); 18067 if (array != null) { 18068 for (int i=0; i<array.length; i++) { 18069 if (i > 0) buf.append(", "); 18070 buf.append(array[i]); 18071 } 18072 } 18073 buf.append(']'); 18074 return buf.toString(); 18075 } 18076 18077 static class DumpState { 18078 public static final int DUMP_LIBS = 1 << 0; 18079 public static final int DUMP_FEATURES = 1 << 1; 18080 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18081 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18082 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18083 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18084 public static final int DUMP_PERMISSIONS = 1 << 6; 18085 public static final int DUMP_PACKAGES = 1 << 7; 18086 public static final int DUMP_SHARED_USERS = 1 << 8; 18087 public static final int DUMP_MESSAGES = 1 << 9; 18088 public static final int DUMP_PROVIDERS = 1 << 10; 18089 public static final int DUMP_VERIFIERS = 1 << 11; 18090 public static final int DUMP_PREFERRED = 1 << 12; 18091 public static final int DUMP_PREFERRED_XML = 1 << 13; 18092 public static final int DUMP_KEYSETS = 1 << 14; 18093 public static final int DUMP_VERSION = 1 << 15; 18094 public static final int DUMP_INSTALLS = 1 << 16; 18095 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18096 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18097 public static final int DUMP_FROZEN = 1 << 19; 18098 public static final int DUMP_DEXOPT = 1 << 20; 18099 18100 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18101 18102 private int mTypes; 18103 18104 private int mOptions; 18105 18106 private boolean mTitlePrinted; 18107 18108 private SharedUserSetting mSharedUser; 18109 18110 public boolean isDumping(int type) { 18111 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18112 return true; 18113 } 18114 18115 return (mTypes & type) != 0; 18116 } 18117 18118 public void setDump(int type) { 18119 mTypes |= type; 18120 } 18121 18122 public boolean isOptionEnabled(int option) { 18123 return (mOptions & option) != 0; 18124 } 18125 18126 public void setOptionEnabled(int option) { 18127 mOptions |= option; 18128 } 18129 18130 public boolean onTitlePrinted() { 18131 final boolean printed = mTitlePrinted; 18132 mTitlePrinted = true; 18133 return printed; 18134 } 18135 18136 public boolean getTitlePrinted() { 18137 return mTitlePrinted; 18138 } 18139 18140 public void setTitlePrinted(boolean enabled) { 18141 mTitlePrinted = enabled; 18142 } 18143 18144 public SharedUserSetting getSharedUser() { 18145 return mSharedUser; 18146 } 18147 18148 public void setSharedUser(SharedUserSetting user) { 18149 mSharedUser = user; 18150 } 18151 } 18152 18153 @Override 18154 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18155 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18156 (new PackageManagerShellCommand(this)).exec( 18157 this, in, out, err, args, resultReceiver); 18158 } 18159 18160 @Override 18161 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18162 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18163 != PackageManager.PERMISSION_GRANTED) { 18164 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18165 + Binder.getCallingPid() 18166 + ", uid=" + Binder.getCallingUid() 18167 + " without permission " 18168 + android.Manifest.permission.DUMP); 18169 return; 18170 } 18171 18172 DumpState dumpState = new DumpState(); 18173 boolean fullPreferred = false; 18174 boolean checkin = false; 18175 18176 String packageName = null; 18177 ArraySet<String> permissionNames = null; 18178 18179 int opti = 0; 18180 while (opti < args.length) { 18181 String opt = args[opti]; 18182 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18183 break; 18184 } 18185 opti++; 18186 18187 if ("-a".equals(opt)) { 18188 // Right now we only know how to print all. 18189 } else if ("-h".equals(opt)) { 18190 pw.println("Package manager dump options:"); 18191 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18192 pw.println(" --checkin: dump for a checkin"); 18193 pw.println(" -f: print details of intent filters"); 18194 pw.println(" -h: print this help"); 18195 pw.println(" cmd may be one of:"); 18196 pw.println(" l[ibraries]: list known shared libraries"); 18197 pw.println(" f[eatures]: list device features"); 18198 pw.println(" k[eysets]: print known keysets"); 18199 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18200 pw.println(" perm[issions]: dump permissions"); 18201 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18202 pw.println(" pref[erred]: print preferred package settings"); 18203 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18204 pw.println(" prov[iders]: dump content providers"); 18205 pw.println(" p[ackages]: dump installed packages"); 18206 pw.println(" s[hared-users]: dump shared user IDs"); 18207 pw.println(" m[essages]: print collected runtime messages"); 18208 pw.println(" v[erifiers]: print package verifier info"); 18209 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18210 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18211 pw.println(" version: print database version info"); 18212 pw.println(" write: write current settings now"); 18213 pw.println(" installs: details about install sessions"); 18214 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18215 pw.println(" dexopt: dump dexopt state"); 18216 pw.println(" <package.name>: info about given package"); 18217 return; 18218 } else if ("--checkin".equals(opt)) { 18219 checkin = true; 18220 } else if ("-f".equals(opt)) { 18221 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18222 } else { 18223 pw.println("Unknown argument: " + opt + "; use -h for help"); 18224 } 18225 } 18226 18227 // Is the caller requesting to dump a particular piece of data? 18228 if (opti < args.length) { 18229 String cmd = args[opti]; 18230 opti++; 18231 // Is this a package name? 18232 if ("android".equals(cmd) || cmd.contains(".")) { 18233 packageName = cmd; 18234 // When dumping a single package, we always dump all of its 18235 // filter information since the amount of data will be reasonable. 18236 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18237 } else if ("check-permission".equals(cmd)) { 18238 if (opti >= args.length) { 18239 pw.println("Error: check-permission missing permission argument"); 18240 return; 18241 } 18242 String perm = args[opti]; 18243 opti++; 18244 if (opti >= args.length) { 18245 pw.println("Error: check-permission missing package argument"); 18246 return; 18247 } 18248 String pkg = args[opti]; 18249 opti++; 18250 int user = UserHandle.getUserId(Binder.getCallingUid()); 18251 if (opti < args.length) { 18252 try { 18253 user = Integer.parseInt(args[opti]); 18254 } catch (NumberFormatException e) { 18255 pw.println("Error: check-permission user argument is not a number: " 18256 + args[opti]); 18257 return; 18258 } 18259 } 18260 pw.println(checkPermission(perm, pkg, user)); 18261 return; 18262 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18263 dumpState.setDump(DumpState.DUMP_LIBS); 18264 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18265 dumpState.setDump(DumpState.DUMP_FEATURES); 18266 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18267 if (opti >= args.length) { 18268 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18269 | DumpState.DUMP_SERVICE_RESOLVERS 18270 | DumpState.DUMP_RECEIVER_RESOLVERS 18271 | DumpState.DUMP_CONTENT_RESOLVERS); 18272 } else { 18273 while (opti < args.length) { 18274 String name = args[opti]; 18275 if ("a".equals(name) || "activity".equals(name)) { 18276 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18277 } else if ("s".equals(name) || "service".equals(name)) { 18278 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18279 } else if ("r".equals(name) || "receiver".equals(name)) { 18280 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18281 } else if ("c".equals(name) || "content".equals(name)) { 18282 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18283 } else { 18284 pw.println("Error: unknown resolver table type: " + name); 18285 return; 18286 } 18287 opti++; 18288 } 18289 } 18290 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18291 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18292 } else if ("permission".equals(cmd)) { 18293 if (opti >= args.length) { 18294 pw.println("Error: permission requires permission name"); 18295 return; 18296 } 18297 permissionNames = new ArraySet<>(); 18298 while (opti < args.length) { 18299 permissionNames.add(args[opti]); 18300 opti++; 18301 } 18302 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18303 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18304 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18305 dumpState.setDump(DumpState.DUMP_PREFERRED); 18306 } else if ("preferred-xml".equals(cmd)) { 18307 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18308 if (opti < args.length && "--full".equals(args[opti])) { 18309 fullPreferred = true; 18310 opti++; 18311 } 18312 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18313 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18314 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18315 dumpState.setDump(DumpState.DUMP_PACKAGES); 18316 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18317 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18318 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18319 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18320 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18321 dumpState.setDump(DumpState.DUMP_MESSAGES); 18322 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18323 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18324 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18325 || "intent-filter-verifiers".equals(cmd)) { 18326 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18327 } else if ("version".equals(cmd)) { 18328 dumpState.setDump(DumpState.DUMP_VERSION); 18329 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18330 dumpState.setDump(DumpState.DUMP_KEYSETS); 18331 } else if ("installs".equals(cmd)) { 18332 dumpState.setDump(DumpState.DUMP_INSTALLS); 18333 } else if ("frozen".equals(cmd)) { 18334 dumpState.setDump(DumpState.DUMP_FROZEN); 18335 } else if ("dexopt".equals(cmd)) { 18336 dumpState.setDump(DumpState.DUMP_DEXOPT); 18337 } else if ("write".equals(cmd)) { 18338 synchronized (mPackages) { 18339 mSettings.writeLPr(); 18340 pw.println("Settings written."); 18341 return; 18342 } 18343 } 18344 } 18345 18346 if (checkin) { 18347 pw.println("vers,1"); 18348 } 18349 18350 // reader 18351 synchronized (mPackages) { 18352 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18353 if (!checkin) { 18354 if (dumpState.onTitlePrinted()) 18355 pw.println(); 18356 pw.println("Database versions:"); 18357 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18358 } 18359 } 18360 18361 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18362 if (!checkin) { 18363 if (dumpState.onTitlePrinted()) 18364 pw.println(); 18365 pw.println("Verifiers:"); 18366 pw.print(" Required: "); 18367 pw.print(mRequiredVerifierPackage); 18368 pw.print(" (uid="); 18369 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18370 UserHandle.USER_SYSTEM)); 18371 pw.println(")"); 18372 } else if (mRequiredVerifierPackage != null) { 18373 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18374 pw.print(","); 18375 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18376 UserHandle.USER_SYSTEM)); 18377 } 18378 } 18379 18380 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18381 packageName == null) { 18382 if (mIntentFilterVerifierComponent != null) { 18383 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18384 if (!checkin) { 18385 if (dumpState.onTitlePrinted()) 18386 pw.println(); 18387 pw.println("Intent Filter Verifier:"); 18388 pw.print(" Using: "); 18389 pw.print(verifierPackageName); 18390 pw.print(" (uid="); 18391 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18392 UserHandle.USER_SYSTEM)); 18393 pw.println(")"); 18394 } else if (verifierPackageName != null) { 18395 pw.print("ifv,"); pw.print(verifierPackageName); 18396 pw.print(","); 18397 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18398 UserHandle.USER_SYSTEM)); 18399 } 18400 } else { 18401 pw.println(); 18402 pw.println("No Intent Filter Verifier available!"); 18403 } 18404 } 18405 18406 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18407 boolean printedHeader = false; 18408 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18409 while (it.hasNext()) { 18410 String name = it.next(); 18411 SharedLibraryEntry ent = mSharedLibraries.get(name); 18412 if (!checkin) { 18413 if (!printedHeader) { 18414 if (dumpState.onTitlePrinted()) 18415 pw.println(); 18416 pw.println("Libraries:"); 18417 printedHeader = true; 18418 } 18419 pw.print(" "); 18420 } else { 18421 pw.print("lib,"); 18422 } 18423 pw.print(name); 18424 if (!checkin) { 18425 pw.print(" -> "); 18426 } 18427 if (ent.path != null) { 18428 if (!checkin) { 18429 pw.print("(jar) "); 18430 pw.print(ent.path); 18431 } else { 18432 pw.print(",jar,"); 18433 pw.print(ent.path); 18434 } 18435 } else { 18436 if (!checkin) { 18437 pw.print("(apk) "); 18438 pw.print(ent.apk); 18439 } else { 18440 pw.print(",apk,"); 18441 pw.print(ent.apk); 18442 } 18443 } 18444 pw.println(); 18445 } 18446 } 18447 18448 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18449 if (dumpState.onTitlePrinted()) 18450 pw.println(); 18451 if (!checkin) { 18452 pw.println("Features:"); 18453 } 18454 18455 for (FeatureInfo feat : mAvailableFeatures.values()) { 18456 if (checkin) { 18457 pw.print("feat,"); 18458 pw.print(feat.name); 18459 pw.print(","); 18460 pw.println(feat.version); 18461 } else { 18462 pw.print(" "); 18463 pw.print(feat.name); 18464 if (feat.version > 0) { 18465 pw.print(" version="); 18466 pw.print(feat.version); 18467 } 18468 pw.println(); 18469 } 18470 } 18471 } 18472 18473 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18474 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18475 : "Activity Resolver Table:", " ", packageName, 18476 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18477 dumpState.setTitlePrinted(true); 18478 } 18479 } 18480 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18481 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18482 : "Receiver Resolver Table:", " ", packageName, 18483 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18484 dumpState.setTitlePrinted(true); 18485 } 18486 } 18487 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18488 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18489 : "Service Resolver Table:", " ", packageName, 18490 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18491 dumpState.setTitlePrinted(true); 18492 } 18493 } 18494 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18495 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18496 : "Provider Resolver Table:", " ", packageName, 18497 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18498 dumpState.setTitlePrinted(true); 18499 } 18500 } 18501 18502 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18503 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18504 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18505 int user = mSettings.mPreferredActivities.keyAt(i); 18506 if (pir.dump(pw, 18507 dumpState.getTitlePrinted() 18508 ? "\nPreferred Activities User " + user + ":" 18509 : "Preferred Activities User " + user + ":", " ", 18510 packageName, true, false)) { 18511 dumpState.setTitlePrinted(true); 18512 } 18513 } 18514 } 18515 18516 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18517 pw.flush(); 18518 FileOutputStream fout = new FileOutputStream(fd); 18519 BufferedOutputStream str = new BufferedOutputStream(fout); 18520 XmlSerializer serializer = new FastXmlSerializer(); 18521 try { 18522 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18523 serializer.startDocument(null, true); 18524 serializer.setFeature( 18525 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18526 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18527 serializer.endDocument(); 18528 serializer.flush(); 18529 } catch (IllegalArgumentException e) { 18530 pw.println("Failed writing: " + e); 18531 } catch (IllegalStateException e) { 18532 pw.println("Failed writing: " + e); 18533 } catch (IOException e) { 18534 pw.println("Failed writing: " + e); 18535 } 18536 } 18537 18538 if (!checkin 18539 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18540 && packageName == null) { 18541 pw.println(); 18542 int count = mSettings.mPackages.size(); 18543 if (count == 0) { 18544 pw.println("No applications!"); 18545 pw.println(); 18546 } else { 18547 final String prefix = " "; 18548 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18549 if (allPackageSettings.size() == 0) { 18550 pw.println("No domain preferred apps!"); 18551 pw.println(); 18552 } else { 18553 pw.println("App verification status:"); 18554 pw.println(); 18555 count = 0; 18556 for (PackageSetting ps : allPackageSettings) { 18557 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18558 if (ivi == null || ivi.getPackageName() == null) continue; 18559 pw.println(prefix + "Package: " + ivi.getPackageName()); 18560 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18561 pw.println(prefix + "Status: " + ivi.getStatusString()); 18562 pw.println(); 18563 count++; 18564 } 18565 if (count == 0) { 18566 pw.println(prefix + "No app verification established."); 18567 pw.println(); 18568 } 18569 for (int userId : sUserManager.getUserIds()) { 18570 pw.println("App linkages for user " + userId + ":"); 18571 pw.println(); 18572 count = 0; 18573 for (PackageSetting ps : allPackageSettings) { 18574 final long status = ps.getDomainVerificationStatusForUser(userId); 18575 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18576 continue; 18577 } 18578 pw.println(prefix + "Package: " + ps.name); 18579 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18580 String statusStr = IntentFilterVerificationInfo. 18581 getStatusStringFromValue(status); 18582 pw.println(prefix + "Status: " + statusStr); 18583 pw.println(); 18584 count++; 18585 } 18586 if (count == 0) { 18587 pw.println(prefix + "No configured app linkages."); 18588 pw.println(); 18589 } 18590 } 18591 } 18592 } 18593 } 18594 18595 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18596 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18597 if (packageName == null && permissionNames == null) { 18598 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18599 if (iperm == 0) { 18600 if (dumpState.onTitlePrinted()) 18601 pw.println(); 18602 pw.println("AppOp Permissions:"); 18603 } 18604 pw.print(" AppOp Permission "); 18605 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18606 pw.println(":"); 18607 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18608 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18609 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18610 } 18611 } 18612 } 18613 } 18614 18615 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18616 boolean printedSomething = false; 18617 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18618 if (packageName != null && !packageName.equals(p.info.packageName)) { 18619 continue; 18620 } 18621 if (!printedSomething) { 18622 if (dumpState.onTitlePrinted()) 18623 pw.println(); 18624 pw.println("Registered ContentProviders:"); 18625 printedSomething = true; 18626 } 18627 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18628 pw.print(" "); pw.println(p.toString()); 18629 } 18630 printedSomething = false; 18631 for (Map.Entry<String, PackageParser.Provider> entry : 18632 mProvidersByAuthority.entrySet()) { 18633 PackageParser.Provider p = entry.getValue(); 18634 if (packageName != null && !packageName.equals(p.info.packageName)) { 18635 continue; 18636 } 18637 if (!printedSomething) { 18638 if (dumpState.onTitlePrinted()) 18639 pw.println(); 18640 pw.println("ContentProvider Authorities:"); 18641 printedSomething = true; 18642 } 18643 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18644 pw.print(" "); pw.println(p.toString()); 18645 if (p.info != null && p.info.applicationInfo != null) { 18646 final String appInfo = p.info.applicationInfo.toString(); 18647 pw.print(" applicationInfo="); pw.println(appInfo); 18648 } 18649 } 18650 } 18651 18652 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18653 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18654 } 18655 18656 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18657 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18658 } 18659 18660 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18661 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18662 } 18663 18664 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18665 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18666 } 18667 18668 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18669 // XXX should handle packageName != null by dumping only install data that 18670 // the given package is involved with. 18671 if (dumpState.onTitlePrinted()) pw.println(); 18672 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18673 } 18674 18675 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18676 // XXX should handle packageName != null by dumping only install data that 18677 // the given package is involved with. 18678 if (dumpState.onTitlePrinted()) pw.println(); 18679 18680 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18681 ipw.println(); 18682 ipw.println("Frozen packages:"); 18683 ipw.increaseIndent(); 18684 if (mFrozenPackages.size() == 0) { 18685 ipw.println("(none)"); 18686 } else { 18687 for (int i = 0; i < mFrozenPackages.size(); i++) { 18688 ipw.println(mFrozenPackages.valueAt(i)); 18689 } 18690 } 18691 ipw.decreaseIndent(); 18692 } 18693 18694 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18695 if (dumpState.onTitlePrinted()) pw.println(); 18696 dumpDexoptStateLPr(pw, packageName); 18697 } 18698 18699 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18700 if (dumpState.onTitlePrinted()) pw.println(); 18701 mSettings.dumpReadMessagesLPr(pw, dumpState); 18702 18703 pw.println(); 18704 pw.println("Package warning messages:"); 18705 BufferedReader in = null; 18706 String line = null; 18707 try { 18708 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18709 while ((line = in.readLine()) != null) { 18710 if (line.contains("ignored: updated version")) continue; 18711 pw.println(line); 18712 } 18713 } catch (IOException ignored) { 18714 } finally { 18715 IoUtils.closeQuietly(in); 18716 } 18717 } 18718 18719 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18720 BufferedReader in = null; 18721 String line = null; 18722 try { 18723 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18724 while ((line = in.readLine()) != null) { 18725 if (line.contains("ignored: updated version")) continue; 18726 pw.print("msg,"); 18727 pw.println(line); 18728 } 18729 } catch (IOException ignored) { 18730 } finally { 18731 IoUtils.closeQuietly(in); 18732 } 18733 } 18734 } 18735 } 18736 18737 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18738 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18739 ipw.println(); 18740 ipw.println("Dexopt state:"); 18741 ipw.increaseIndent(); 18742 Collection<PackageParser.Package> packages = null; 18743 if (packageName != null) { 18744 PackageParser.Package targetPackage = mPackages.get(packageName); 18745 if (targetPackage != null) { 18746 packages = Collections.singletonList(targetPackage); 18747 } else { 18748 ipw.println("Unable to find package: " + packageName); 18749 return; 18750 } 18751 } else { 18752 packages = mPackages.values(); 18753 } 18754 18755 for (PackageParser.Package pkg : packages) { 18756 ipw.println("[" + pkg.packageName + "]"); 18757 ipw.increaseIndent(); 18758 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18759 ipw.decreaseIndent(); 18760 } 18761 } 18762 18763 private String dumpDomainString(String packageName) { 18764 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18765 .getList(); 18766 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18767 18768 ArraySet<String> result = new ArraySet<>(); 18769 if (iviList.size() > 0) { 18770 for (IntentFilterVerificationInfo ivi : iviList) { 18771 for (String host : ivi.getDomains()) { 18772 result.add(host); 18773 } 18774 } 18775 } 18776 if (filters != null && filters.size() > 0) { 18777 for (IntentFilter filter : filters) { 18778 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18779 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18780 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18781 result.addAll(filter.getHostsList()); 18782 } 18783 } 18784 } 18785 18786 StringBuilder sb = new StringBuilder(result.size() * 16); 18787 for (String domain : result) { 18788 if (sb.length() > 0) sb.append(" "); 18789 sb.append(domain); 18790 } 18791 return sb.toString(); 18792 } 18793 18794 // ------- apps on sdcard specific code ------- 18795 static final boolean DEBUG_SD_INSTALL = false; 18796 18797 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18798 18799 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18800 18801 private boolean mMediaMounted = false; 18802 18803 static String getEncryptKey() { 18804 try { 18805 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18806 SD_ENCRYPTION_KEYSTORE_NAME); 18807 if (sdEncKey == null) { 18808 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18809 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18810 if (sdEncKey == null) { 18811 Slog.e(TAG, "Failed to create encryption keys"); 18812 return null; 18813 } 18814 } 18815 return sdEncKey; 18816 } catch (NoSuchAlgorithmException nsae) { 18817 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18818 return null; 18819 } catch (IOException ioe) { 18820 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18821 return null; 18822 } 18823 } 18824 18825 /* 18826 * Update media status on PackageManager. 18827 */ 18828 @Override 18829 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18830 int callingUid = Binder.getCallingUid(); 18831 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18832 throw new SecurityException("Media status can only be updated by the system"); 18833 } 18834 // reader; this apparently protects mMediaMounted, but should probably 18835 // be a different lock in that case. 18836 synchronized (mPackages) { 18837 Log.i(TAG, "Updating external media status from " 18838 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18839 + (mediaStatus ? "mounted" : "unmounted")); 18840 if (DEBUG_SD_INSTALL) 18841 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18842 + ", mMediaMounted=" + mMediaMounted); 18843 if (mediaStatus == mMediaMounted) { 18844 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18845 : 0, -1); 18846 mHandler.sendMessage(msg); 18847 return; 18848 } 18849 mMediaMounted = mediaStatus; 18850 } 18851 // Queue up an async operation since the package installation may take a 18852 // little while. 18853 mHandler.post(new Runnable() { 18854 public void run() { 18855 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18856 } 18857 }); 18858 } 18859 18860 /** 18861 * Called by MountService when the initial ASECs to scan are available. 18862 * Should block until all the ASEC containers are finished being scanned. 18863 */ 18864 public void scanAvailableAsecs() { 18865 updateExternalMediaStatusInner(true, false, false); 18866 } 18867 18868 /* 18869 * Collect information of applications on external media, map them against 18870 * existing containers and update information based on current mount status. 18871 * Please note that we always have to report status if reportStatus has been 18872 * set to true especially when unloading packages. 18873 */ 18874 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18875 boolean externalStorage) { 18876 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18877 int[] uidArr = EmptyArray.INT; 18878 18879 final String[] list = PackageHelper.getSecureContainerList(); 18880 if (ArrayUtils.isEmpty(list)) { 18881 Log.i(TAG, "No secure containers found"); 18882 } else { 18883 // Process list of secure containers and categorize them 18884 // as active or stale based on their package internal state. 18885 18886 // reader 18887 synchronized (mPackages) { 18888 for (String cid : list) { 18889 // Leave stages untouched for now; installer service owns them 18890 if (PackageInstallerService.isStageName(cid)) continue; 18891 18892 if (DEBUG_SD_INSTALL) 18893 Log.i(TAG, "Processing container " + cid); 18894 String pkgName = getAsecPackageName(cid); 18895 if (pkgName == null) { 18896 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18897 continue; 18898 } 18899 if (DEBUG_SD_INSTALL) 18900 Log.i(TAG, "Looking for pkg : " + pkgName); 18901 18902 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18903 if (ps == null) { 18904 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18905 continue; 18906 } 18907 18908 /* 18909 * Skip packages that are not external if we're unmounting 18910 * external storage. 18911 */ 18912 if (externalStorage && !isMounted && !isExternal(ps)) { 18913 continue; 18914 } 18915 18916 final AsecInstallArgs args = new AsecInstallArgs(cid, 18917 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18918 // The package status is changed only if the code path 18919 // matches between settings and the container id. 18920 if (ps.codePathString != null 18921 && ps.codePathString.startsWith(args.getCodePath())) { 18922 if (DEBUG_SD_INSTALL) { 18923 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18924 + " at code path: " + ps.codePathString); 18925 } 18926 18927 // We do have a valid package installed on sdcard 18928 processCids.put(args, ps.codePathString); 18929 final int uid = ps.appId; 18930 if (uid != -1) { 18931 uidArr = ArrayUtils.appendInt(uidArr, uid); 18932 } 18933 } else { 18934 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18935 + ps.codePathString); 18936 } 18937 } 18938 } 18939 18940 Arrays.sort(uidArr); 18941 } 18942 18943 // Process packages with valid entries. 18944 if (isMounted) { 18945 if (DEBUG_SD_INSTALL) 18946 Log.i(TAG, "Loading packages"); 18947 loadMediaPackages(processCids, uidArr, externalStorage); 18948 startCleaningPackages(); 18949 mInstallerService.onSecureContainersAvailable(); 18950 } else { 18951 if (DEBUG_SD_INSTALL) 18952 Log.i(TAG, "Unloading packages"); 18953 unloadMediaPackages(processCids, uidArr, reportStatus); 18954 } 18955 } 18956 18957 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18958 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18959 final int size = infos.size(); 18960 final String[] packageNames = new String[size]; 18961 final int[] packageUids = new int[size]; 18962 for (int i = 0; i < size; i++) { 18963 final ApplicationInfo info = infos.get(i); 18964 packageNames[i] = info.packageName; 18965 packageUids[i] = info.uid; 18966 } 18967 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18968 finishedReceiver); 18969 } 18970 18971 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18972 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18973 sendResourcesChangedBroadcast(mediaStatus, replacing, 18974 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18975 } 18976 18977 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18978 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18979 int size = pkgList.length; 18980 if (size > 0) { 18981 // Send broadcasts here 18982 Bundle extras = new Bundle(); 18983 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18984 if (uidArr != null) { 18985 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18986 } 18987 if (replacing) { 18988 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18989 } 18990 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18991 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18992 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18993 } 18994 } 18995 18996 /* 18997 * Look at potentially valid container ids from processCids If package 18998 * information doesn't match the one on record or package scanning fails, 18999 * the cid is added to list of removeCids. We currently don't delete stale 19000 * containers. 19001 */ 19002 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19003 boolean externalStorage) { 19004 ArrayList<String> pkgList = new ArrayList<String>(); 19005 Set<AsecInstallArgs> keys = processCids.keySet(); 19006 19007 for (AsecInstallArgs args : keys) { 19008 String codePath = processCids.get(args); 19009 if (DEBUG_SD_INSTALL) 19010 Log.i(TAG, "Loading container : " + args.cid); 19011 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19012 try { 19013 // Make sure there are no container errors first. 19014 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19015 Slog.e(TAG, "Failed to mount cid : " + args.cid 19016 + " when installing from sdcard"); 19017 continue; 19018 } 19019 // Check code path here. 19020 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19021 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19022 + " does not match one in settings " + codePath); 19023 continue; 19024 } 19025 // Parse package 19026 int parseFlags = mDefParseFlags; 19027 if (args.isExternalAsec()) { 19028 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19029 } 19030 if (args.isFwdLocked()) { 19031 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19032 } 19033 19034 synchronized (mInstallLock) { 19035 PackageParser.Package pkg = null; 19036 try { 19037 // Sadly we don't know the package name yet to freeze it 19038 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19039 SCAN_IGNORE_FROZEN, 0, null); 19040 } catch (PackageManagerException e) { 19041 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19042 } 19043 // Scan the package 19044 if (pkg != null) { 19045 /* 19046 * TODO why is the lock being held? doPostInstall is 19047 * called in other places without the lock. This needs 19048 * to be straightened out. 19049 */ 19050 // writer 19051 synchronized (mPackages) { 19052 retCode = PackageManager.INSTALL_SUCCEEDED; 19053 pkgList.add(pkg.packageName); 19054 // Post process args 19055 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19056 pkg.applicationInfo.uid); 19057 } 19058 } else { 19059 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19060 } 19061 } 19062 19063 } finally { 19064 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19065 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19066 } 19067 } 19068 } 19069 // writer 19070 synchronized (mPackages) { 19071 // If the platform SDK has changed since the last time we booted, 19072 // we need to re-grant app permission to catch any new ones that 19073 // appear. This is really a hack, and means that apps can in some 19074 // cases get permissions that the user didn't initially explicitly 19075 // allow... it would be nice to have some better way to handle 19076 // this situation. 19077 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19078 : mSettings.getInternalVersion(); 19079 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19080 : StorageManager.UUID_PRIVATE_INTERNAL; 19081 19082 int updateFlags = UPDATE_PERMISSIONS_ALL; 19083 if (ver.sdkVersion != mSdkVersion) { 19084 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19085 + mSdkVersion + "; regranting permissions for external"); 19086 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19087 } 19088 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19089 19090 // Yay, everything is now upgraded 19091 ver.forceCurrent(); 19092 19093 // can downgrade to reader 19094 // Persist settings 19095 mSettings.writeLPr(); 19096 } 19097 // Send a broadcast to let everyone know we are done processing 19098 if (pkgList.size() > 0) { 19099 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19100 } 19101 } 19102 19103 /* 19104 * Utility method to unload a list of specified containers 19105 */ 19106 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19107 // Just unmount all valid containers. 19108 for (AsecInstallArgs arg : cidArgs) { 19109 synchronized (mInstallLock) { 19110 arg.doPostDeleteLI(false); 19111 } 19112 } 19113 } 19114 19115 /* 19116 * Unload packages mounted on external media. This involves deleting package 19117 * data from internal structures, sending broadcasts about disabled packages, 19118 * gc'ing to free up references, unmounting all secure containers 19119 * corresponding to packages on external media, and posting a 19120 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19121 * that we always have to post this message if status has been requested no 19122 * matter what. 19123 */ 19124 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19125 final boolean reportStatus) { 19126 if (DEBUG_SD_INSTALL) 19127 Log.i(TAG, "unloading media packages"); 19128 ArrayList<String> pkgList = new ArrayList<String>(); 19129 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19130 final Set<AsecInstallArgs> keys = processCids.keySet(); 19131 for (AsecInstallArgs args : keys) { 19132 String pkgName = args.getPackageName(); 19133 if (DEBUG_SD_INSTALL) 19134 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19135 // Delete package internally 19136 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19137 synchronized (mInstallLock) { 19138 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19139 final boolean res; 19140 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19141 "unloadMediaPackages")) { 19142 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19143 null); 19144 } 19145 if (res) { 19146 pkgList.add(pkgName); 19147 } else { 19148 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19149 failedList.add(args); 19150 } 19151 } 19152 } 19153 19154 // reader 19155 synchronized (mPackages) { 19156 // We didn't update the settings after removing each package; 19157 // write them now for all packages. 19158 mSettings.writeLPr(); 19159 } 19160 19161 // We have to absolutely send UPDATED_MEDIA_STATUS only 19162 // after confirming that all the receivers processed the ordered 19163 // broadcast when packages get disabled, force a gc to clean things up. 19164 // and unload all the containers. 19165 if (pkgList.size() > 0) { 19166 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19167 new IIntentReceiver.Stub() { 19168 public void performReceive(Intent intent, int resultCode, String data, 19169 Bundle extras, boolean ordered, boolean sticky, 19170 int sendingUser) throws RemoteException { 19171 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19172 reportStatus ? 1 : 0, 1, keys); 19173 mHandler.sendMessage(msg); 19174 } 19175 }); 19176 } else { 19177 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19178 keys); 19179 mHandler.sendMessage(msg); 19180 } 19181 } 19182 19183 private void loadPrivatePackages(final VolumeInfo vol) { 19184 mHandler.post(new Runnable() { 19185 @Override 19186 public void run() { 19187 loadPrivatePackagesInner(vol); 19188 } 19189 }); 19190 } 19191 19192 private void loadPrivatePackagesInner(VolumeInfo vol) { 19193 final String volumeUuid = vol.fsUuid; 19194 if (TextUtils.isEmpty(volumeUuid)) { 19195 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19196 return; 19197 } 19198 19199 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19200 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19201 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19202 19203 final VersionInfo ver; 19204 final List<PackageSetting> packages; 19205 synchronized (mPackages) { 19206 ver = mSettings.findOrCreateVersion(volumeUuid); 19207 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19208 } 19209 19210 for (PackageSetting ps : packages) { 19211 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19212 synchronized (mInstallLock) { 19213 final PackageParser.Package pkg; 19214 try { 19215 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19216 loaded.add(pkg.applicationInfo); 19217 19218 } catch (PackageManagerException e) { 19219 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19220 } 19221 19222 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19223 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19224 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19225 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19226 } 19227 } 19228 } 19229 19230 // Reconcile app data for all started/unlocked users 19231 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19232 final UserManager um = mContext.getSystemService(UserManager.class); 19233 UserManagerInternal umInternal = getUserManagerInternal(); 19234 for (UserInfo user : um.getUsers()) { 19235 final int flags; 19236 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19237 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19238 } else if (umInternal.isUserRunning(user.id)) { 19239 flags = StorageManager.FLAG_STORAGE_DE; 19240 } else { 19241 continue; 19242 } 19243 19244 try { 19245 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19246 synchronized (mInstallLock) { 19247 reconcileAppsDataLI(volumeUuid, user.id, flags); 19248 } 19249 } catch (IllegalStateException e) { 19250 // Device was probably ejected, and we'll process that event momentarily 19251 Slog.w(TAG, "Failed to prepare storage: " + e); 19252 } 19253 } 19254 19255 synchronized (mPackages) { 19256 int updateFlags = UPDATE_PERMISSIONS_ALL; 19257 if (ver.sdkVersion != mSdkVersion) { 19258 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19259 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19260 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19261 } 19262 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19263 19264 // Yay, everything is now upgraded 19265 ver.forceCurrent(); 19266 19267 mSettings.writeLPr(); 19268 } 19269 19270 for (PackageFreezer freezer : freezers) { 19271 freezer.close(); 19272 } 19273 19274 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19275 sendResourcesChangedBroadcast(true, false, loaded, null); 19276 } 19277 19278 private void unloadPrivatePackages(final VolumeInfo vol) { 19279 mHandler.post(new Runnable() { 19280 @Override 19281 public void run() { 19282 unloadPrivatePackagesInner(vol); 19283 } 19284 }); 19285 } 19286 19287 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19288 final String volumeUuid = vol.fsUuid; 19289 if (TextUtils.isEmpty(volumeUuid)) { 19290 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19291 return; 19292 } 19293 19294 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19295 synchronized (mInstallLock) { 19296 synchronized (mPackages) { 19297 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19298 for (PackageSetting ps : packages) { 19299 if (ps.pkg == null) continue; 19300 19301 final ApplicationInfo info = ps.pkg.applicationInfo; 19302 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19303 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19304 19305 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19306 "unloadPrivatePackagesInner")) { 19307 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19308 false, null)) { 19309 unloaded.add(info); 19310 } else { 19311 Slog.w(TAG, "Failed to unload " + ps.codePath); 19312 } 19313 } 19314 19315 // Try very hard to release any references to this package 19316 // so we don't risk the system server being killed due to 19317 // open FDs 19318 AttributeCache.instance().removePackage(ps.name); 19319 } 19320 19321 mSettings.writeLPr(); 19322 } 19323 } 19324 19325 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19326 sendResourcesChangedBroadcast(false, false, unloaded, null); 19327 19328 // Try very hard to release any references to this path so we don't risk 19329 // the system server being killed due to open FDs 19330 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19331 19332 for (int i = 0; i < 3; i++) { 19333 System.gc(); 19334 System.runFinalization(); 19335 } 19336 } 19337 19338 /** 19339 * Prepare storage areas for given user on all mounted devices. 19340 */ 19341 void prepareUserData(int userId, int userSerial, int flags) { 19342 synchronized (mInstallLock) { 19343 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19344 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19345 final String volumeUuid = vol.getFsUuid(); 19346 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19347 } 19348 } 19349 } 19350 19351 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19352 boolean allowRecover) { 19353 // Prepare storage and verify that serial numbers are consistent; if 19354 // there's a mismatch we need to destroy to avoid leaking data 19355 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19356 try { 19357 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19358 19359 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19360 UserManagerService.enforceSerialNumber( 19361 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19362 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19363 UserManagerService.enforceSerialNumber( 19364 Environment.getDataSystemDeDirectory(userId), userSerial); 19365 } 19366 } 19367 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19368 UserManagerService.enforceSerialNumber( 19369 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19370 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19371 UserManagerService.enforceSerialNumber( 19372 Environment.getDataSystemCeDirectory(userId), userSerial); 19373 } 19374 } 19375 19376 synchronized (mInstallLock) { 19377 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19378 } 19379 } catch (Exception e) { 19380 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19381 + " because we failed to prepare: " + e); 19382 destroyUserDataLI(volumeUuid, userId, 19383 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19384 19385 if (allowRecover) { 19386 // Try one last time; if we fail again we're really in trouble 19387 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19388 } 19389 } 19390 } 19391 19392 /** 19393 * Destroy storage areas for given user on all mounted devices. 19394 */ 19395 void destroyUserData(int userId, int flags) { 19396 synchronized (mInstallLock) { 19397 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19398 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19399 final String volumeUuid = vol.getFsUuid(); 19400 destroyUserDataLI(volumeUuid, userId, flags); 19401 } 19402 } 19403 } 19404 19405 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19406 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19407 try { 19408 // Clean up app data, profile data, and media data 19409 mInstaller.destroyUserData(volumeUuid, userId, flags); 19410 19411 // Clean up system data 19412 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19413 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19414 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19415 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19416 } 19417 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19418 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19419 } 19420 } 19421 19422 // Data with special labels is now gone, so finish the job 19423 storage.destroyUserStorage(volumeUuid, userId, flags); 19424 19425 } catch (Exception e) { 19426 logCriticalInfo(Log.WARN, 19427 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19428 } 19429 } 19430 19431 /** 19432 * Examine all users present on given mounted volume, and destroy data 19433 * belonging to users that are no longer valid, or whose user ID has been 19434 * recycled. 19435 */ 19436 private void reconcileUsers(String volumeUuid) { 19437 final List<File> files = new ArrayList<>(); 19438 Collections.addAll(files, FileUtils 19439 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19440 Collections.addAll(files, FileUtils 19441 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19442 Collections.addAll(files, FileUtils 19443 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19444 Collections.addAll(files, FileUtils 19445 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19446 for (File file : files) { 19447 if (!file.isDirectory()) continue; 19448 19449 final int userId; 19450 final UserInfo info; 19451 try { 19452 userId = Integer.parseInt(file.getName()); 19453 info = sUserManager.getUserInfo(userId); 19454 } catch (NumberFormatException e) { 19455 Slog.w(TAG, "Invalid user directory " + file); 19456 continue; 19457 } 19458 19459 boolean destroyUser = false; 19460 if (info == null) { 19461 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19462 + " because no matching user was found"); 19463 destroyUser = true; 19464 } else if (!mOnlyCore) { 19465 try { 19466 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19467 } catch (IOException e) { 19468 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19469 + " because we failed to enforce serial number: " + e); 19470 destroyUser = true; 19471 } 19472 } 19473 19474 if (destroyUser) { 19475 synchronized (mInstallLock) { 19476 destroyUserDataLI(volumeUuid, userId, 19477 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19478 } 19479 } 19480 } 19481 } 19482 19483 private void assertPackageKnown(String volumeUuid, String packageName) 19484 throws PackageManagerException { 19485 synchronized (mPackages) { 19486 final PackageSetting ps = mSettings.mPackages.get(packageName); 19487 if (ps == null) { 19488 throw new PackageManagerException("Package " + packageName + " is unknown"); 19489 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19490 throw new PackageManagerException( 19491 "Package " + packageName + " found on unknown volume " + volumeUuid 19492 + "; expected volume " + ps.volumeUuid); 19493 } 19494 } 19495 } 19496 19497 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 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 } else if (!ps.getInstalled(userId)) { 19508 throw new PackageManagerException( 19509 "Package " + packageName + " not installed for user " + userId); 19510 } 19511 } 19512 } 19513 19514 /** 19515 * Examine all apps present on given mounted volume, and destroy apps that 19516 * aren't expected, either due to uninstallation or reinstallation on 19517 * another volume. 19518 */ 19519 private void reconcileApps(String volumeUuid) { 19520 final File[] files = FileUtils 19521 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19522 for (File file : files) { 19523 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19524 && !PackageInstallerService.isStageName(file.getName()); 19525 if (!isPackage) { 19526 // Ignore entries which are not packages 19527 continue; 19528 } 19529 19530 try { 19531 final PackageLite pkg = PackageParser.parsePackageLite(file, 19532 PackageParser.PARSE_MUST_BE_APK); 19533 assertPackageKnown(volumeUuid, pkg.packageName); 19534 19535 } catch (PackageParserException | PackageManagerException e) { 19536 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19537 synchronized (mInstallLock) { 19538 removeCodePathLI(file); 19539 } 19540 } 19541 } 19542 } 19543 19544 /** 19545 * Reconcile all app data for the given user. 19546 * <p> 19547 * Verifies that directories exist and that ownership and labeling is 19548 * correct for all installed apps on all mounted volumes. 19549 */ 19550 void reconcileAppsData(int userId, int flags) { 19551 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19552 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19553 final String volumeUuid = vol.getFsUuid(); 19554 synchronized (mInstallLock) { 19555 reconcileAppsDataLI(volumeUuid, userId, flags); 19556 } 19557 } 19558 } 19559 19560 /** 19561 * Reconcile all app data on given mounted volume. 19562 * <p> 19563 * Destroys app data that isn't expected, either due to uninstallation or 19564 * reinstallation on another volume. 19565 * <p> 19566 * Verifies that directories exist and that ownership and labeling is 19567 * correct for all installed apps. 19568 */ 19569 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19570 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19571 + Integer.toHexString(flags)); 19572 19573 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19574 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19575 19576 boolean restoreconNeeded = false; 19577 19578 // First look for stale data that doesn't belong, and check if things 19579 // have changed since we did our last restorecon 19580 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19581 if (StorageManager.isFileEncryptedNativeOrEmulated() 19582 && !StorageManager.isUserKeyUnlocked(userId)) { 19583 throw new RuntimeException( 19584 "Yikes, someone asked us to reconcile CE storage while " + userId 19585 + " was still locked; this would have caused massive data loss!"); 19586 } 19587 19588 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19589 19590 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19591 for (File file : files) { 19592 final String packageName = file.getName(); 19593 try { 19594 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19595 } catch (PackageManagerException e) { 19596 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19597 try { 19598 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19599 StorageManager.FLAG_STORAGE_CE, 0); 19600 } catch (InstallerException e2) { 19601 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19602 } 19603 } 19604 } 19605 } 19606 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19607 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19608 19609 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19610 for (File file : files) { 19611 final String packageName = file.getName(); 19612 try { 19613 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19614 } catch (PackageManagerException e) { 19615 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19616 try { 19617 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19618 StorageManager.FLAG_STORAGE_DE, 0); 19619 } catch (InstallerException e2) { 19620 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19621 } 19622 } 19623 } 19624 } 19625 19626 // Ensure that data directories are ready to roll for all packages 19627 // installed for this volume and user 19628 final List<PackageSetting> packages; 19629 synchronized (mPackages) { 19630 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19631 } 19632 int preparedCount = 0; 19633 for (PackageSetting ps : packages) { 19634 final String packageName = ps.name; 19635 if (ps.pkg == null) { 19636 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19637 // TODO: might be due to legacy ASEC apps; we should circle back 19638 // and reconcile again once they're scanned 19639 continue; 19640 } 19641 19642 if (ps.getInstalled(userId)) { 19643 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19644 19645 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19646 // We may have just shuffled around app data directories, so 19647 // prepare them one more time 19648 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19649 } 19650 19651 preparedCount++; 19652 } 19653 } 19654 19655 if (restoreconNeeded) { 19656 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19657 SELinuxMMAC.setRestoreconDone(ceDir); 19658 } 19659 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19660 SELinuxMMAC.setRestoreconDone(deDir); 19661 } 19662 } 19663 19664 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19665 + " packages; restoreconNeeded was " + restoreconNeeded); 19666 } 19667 19668 /** 19669 * Prepare app data for the given app just after it was installed or 19670 * upgraded. This method carefully only touches users that it's installed 19671 * for, and it forces a restorecon to handle any seinfo changes. 19672 * <p> 19673 * Verifies that directories exist and that ownership and labeling is 19674 * correct for all installed apps. If there is an ownership mismatch, it 19675 * will try recovering system apps by wiping data; third-party app data is 19676 * left intact. 19677 * <p> 19678 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19679 */ 19680 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19681 final PackageSetting ps; 19682 synchronized (mPackages) { 19683 ps = mSettings.mPackages.get(pkg.packageName); 19684 mSettings.writeKernelMappingLPr(ps); 19685 } 19686 19687 final UserManager um = mContext.getSystemService(UserManager.class); 19688 UserManagerInternal umInternal = getUserManagerInternal(); 19689 for (UserInfo user : um.getUsers()) { 19690 final int flags; 19691 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19692 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19693 } else if (umInternal.isUserRunning(user.id)) { 19694 flags = StorageManager.FLAG_STORAGE_DE; 19695 } else { 19696 continue; 19697 } 19698 19699 if (ps.getInstalled(user.id)) { 19700 // Whenever an app changes, force a restorecon of its data 19701 // TODO: when user data is locked, mark that we're still dirty 19702 prepareAppDataLIF(pkg, user.id, flags, true); 19703 } 19704 } 19705 } 19706 19707 /** 19708 * Prepare app data for the given app. 19709 * <p> 19710 * Verifies that directories exist and that ownership and labeling is 19711 * correct for all installed apps. If there is an ownership mismatch, this 19712 * will try recovering system apps by wiping data; third-party app data is 19713 * left intact. 19714 */ 19715 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19716 boolean restoreconNeeded) { 19717 if (pkg == null) { 19718 Slog.wtf(TAG, "Package was null!", new Throwable()); 19719 return; 19720 } 19721 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19722 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19723 for (int i = 0; i < childCount; i++) { 19724 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19725 } 19726 } 19727 19728 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19729 boolean restoreconNeeded) { 19730 if (DEBUG_APP_DATA) { 19731 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19732 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19733 } 19734 19735 final String volumeUuid = pkg.volumeUuid; 19736 final String packageName = pkg.packageName; 19737 final ApplicationInfo app = pkg.applicationInfo; 19738 final int appId = UserHandle.getAppId(app.uid); 19739 19740 Preconditions.checkNotNull(app.seinfo); 19741 19742 try { 19743 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19744 appId, app.seinfo, app.targetSdkVersion); 19745 } catch (InstallerException e) { 19746 if (app.isSystemApp()) { 19747 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19748 + ", but trying to recover: " + e); 19749 destroyAppDataLeafLIF(pkg, userId, flags); 19750 try { 19751 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19752 appId, app.seinfo, app.targetSdkVersion); 19753 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19754 } catch (InstallerException e2) { 19755 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19756 } 19757 } else { 19758 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19759 } 19760 } 19761 19762 if (restoreconNeeded) { 19763 try { 19764 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19765 app.seinfo); 19766 } catch (InstallerException e) { 19767 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19768 } 19769 } 19770 19771 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19772 try { 19773 // CE storage is unlocked right now, so read out the inode and 19774 // remember for use later when it's locked 19775 // TODO: mark this structure as dirty so we persist it! 19776 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19777 StorageManager.FLAG_STORAGE_CE); 19778 synchronized (mPackages) { 19779 final PackageSetting ps = mSettings.mPackages.get(packageName); 19780 if (ps != null) { 19781 ps.setCeDataInode(ceDataInode, userId); 19782 } 19783 } 19784 } catch (InstallerException e) { 19785 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19786 } 19787 } 19788 19789 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19790 } 19791 19792 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19793 if (pkg == null) { 19794 Slog.wtf(TAG, "Package was null!", new Throwable()); 19795 return; 19796 } 19797 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19799 for (int i = 0; i < childCount; i++) { 19800 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19801 } 19802 } 19803 19804 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19805 final String volumeUuid = pkg.volumeUuid; 19806 final String packageName = pkg.packageName; 19807 final ApplicationInfo app = pkg.applicationInfo; 19808 19809 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19810 // Create a native library symlink only if we have native libraries 19811 // and if the native libraries are 32 bit libraries. We do not provide 19812 // this symlink for 64 bit libraries. 19813 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19814 final String nativeLibPath = app.nativeLibraryDir; 19815 try { 19816 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19817 nativeLibPath, userId); 19818 } catch (InstallerException e) { 19819 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19820 } 19821 } 19822 } 19823 } 19824 19825 /** 19826 * For system apps on non-FBE devices, this method migrates any existing 19827 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19828 * requested by the app. 19829 */ 19830 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19831 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19832 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19833 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19834 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19835 try { 19836 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19837 storageTarget); 19838 } catch (InstallerException e) { 19839 logCriticalInfo(Log.WARN, 19840 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19841 } 19842 return true; 19843 } else { 19844 return false; 19845 } 19846 } 19847 19848 public PackageFreezer freezePackage(String packageName, String killReason) { 19849 return new PackageFreezer(packageName, killReason); 19850 } 19851 19852 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19853 String killReason) { 19854 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19855 return new PackageFreezer(); 19856 } else { 19857 return freezePackage(packageName, killReason); 19858 } 19859 } 19860 19861 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19862 String killReason) { 19863 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19864 return new PackageFreezer(); 19865 } else { 19866 return freezePackage(packageName, killReason); 19867 } 19868 } 19869 19870 /** 19871 * Class that freezes and kills the given package upon creation, and 19872 * unfreezes it upon closing. This is typically used when doing surgery on 19873 * app code/data to prevent the app from running while you're working. 19874 */ 19875 private class PackageFreezer implements AutoCloseable { 19876 private final String mPackageName; 19877 private final PackageFreezer[] mChildren; 19878 19879 private final boolean mWeFroze; 19880 19881 private final AtomicBoolean mClosed = new AtomicBoolean(); 19882 private final CloseGuard mCloseGuard = CloseGuard.get(); 19883 19884 /** 19885 * Create and return a stub freezer that doesn't actually do anything, 19886 * typically used when someone requested 19887 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19888 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19889 */ 19890 public PackageFreezer() { 19891 mPackageName = null; 19892 mChildren = null; 19893 mWeFroze = false; 19894 mCloseGuard.open("close"); 19895 } 19896 19897 public PackageFreezer(String packageName, String killReason) { 19898 synchronized (mPackages) { 19899 mPackageName = packageName; 19900 mWeFroze = mFrozenPackages.add(mPackageName); 19901 19902 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19903 if (ps != null) { 19904 killApplication(ps.name, ps.appId, killReason); 19905 } 19906 19907 final PackageParser.Package p = mPackages.get(packageName); 19908 if (p != null && p.childPackages != null) { 19909 final int N = p.childPackages.size(); 19910 mChildren = new PackageFreezer[N]; 19911 for (int i = 0; i < N; i++) { 19912 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19913 killReason); 19914 } 19915 } else { 19916 mChildren = null; 19917 } 19918 } 19919 mCloseGuard.open("close"); 19920 } 19921 19922 @Override 19923 protected void finalize() throws Throwable { 19924 try { 19925 mCloseGuard.warnIfOpen(); 19926 close(); 19927 } finally { 19928 super.finalize(); 19929 } 19930 } 19931 19932 @Override 19933 public void close() { 19934 mCloseGuard.close(); 19935 if (mClosed.compareAndSet(false, true)) { 19936 synchronized (mPackages) { 19937 if (mWeFroze) { 19938 mFrozenPackages.remove(mPackageName); 19939 } 19940 19941 if (mChildren != null) { 19942 for (PackageFreezer freezer : mChildren) { 19943 freezer.close(); 19944 } 19945 } 19946 } 19947 } 19948 } 19949 } 19950 19951 /** 19952 * Verify that given package is currently frozen. 19953 */ 19954 private void checkPackageFrozen(String packageName) { 19955 synchronized (mPackages) { 19956 if (!mFrozenPackages.contains(packageName)) { 19957 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19958 } 19959 } 19960 } 19961 19962 @Override 19963 public int movePackage(final String packageName, final String volumeUuid) { 19964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19965 19966 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19967 final int moveId = mNextMoveId.getAndIncrement(); 19968 mHandler.post(new Runnable() { 19969 @Override 19970 public void run() { 19971 try { 19972 movePackageInternal(packageName, volumeUuid, moveId, user); 19973 } catch (PackageManagerException e) { 19974 Slog.w(TAG, "Failed to move " + packageName, e); 19975 mMoveCallbacks.notifyStatusChanged(moveId, 19976 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19977 } 19978 } 19979 }); 19980 return moveId; 19981 } 19982 19983 private void movePackageInternal(final String packageName, final String volumeUuid, 19984 final int moveId, UserHandle user) throws PackageManagerException { 19985 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19986 final PackageManager pm = mContext.getPackageManager(); 19987 19988 final boolean currentAsec; 19989 final String currentVolumeUuid; 19990 final File codeFile; 19991 final String installerPackageName; 19992 final String packageAbiOverride; 19993 final int appId; 19994 final String seinfo; 19995 final String label; 19996 final int targetSdkVersion; 19997 final PackageFreezer freezer; 19998 final int[] installedUserIds; 19999 20000 // reader 20001 synchronized (mPackages) { 20002 final PackageParser.Package pkg = mPackages.get(packageName); 20003 final PackageSetting ps = mSettings.mPackages.get(packageName); 20004 if (pkg == null || ps == null) { 20005 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20006 } 20007 20008 if (pkg.applicationInfo.isSystemApp()) { 20009 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20010 "Cannot move system application"); 20011 } 20012 20013 if (pkg.applicationInfo.isExternalAsec()) { 20014 currentAsec = true; 20015 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20016 } else if (pkg.applicationInfo.isForwardLocked()) { 20017 currentAsec = true; 20018 currentVolumeUuid = "forward_locked"; 20019 } else { 20020 currentAsec = false; 20021 currentVolumeUuid = ps.volumeUuid; 20022 20023 final File probe = new File(pkg.codePath); 20024 final File probeOat = new File(probe, "oat"); 20025 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20026 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20027 "Move only supported for modern cluster style installs"); 20028 } 20029 } 20030 20031 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20032 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20033 "Package already moved to " + volumeUuid); 20034 } 20035 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20036 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20037 "Device admin cannot be moved"); 20038 } 20039 20040 if (mFrozenPackages.contains(packageName)) { 20041 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20042 "Failed to move already frozen package"); 20043 } 20044 20045 codeFile = new File(pkg.codePath); 20046 installerPackageName = ps.installerPackageName; 20047 packageAbiOverride = ps.cpuAbiOverrideString; 20048 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20049 seinfo = pkg.applicationInfo.seinfo; 20050 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20051 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20052 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20053 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20054 } 20055 20056 final Bundle extras = new Bundle(); 20057 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20058 extras.putString(Intent.EXTRA_TITLE, label); 20059 mMoveCallbacks.notifyCreated(moveId, extras); 20060 20061 int installFlags; 20062 final boolean moveCompleteApp; 20063 final File measurePath; 20064 20065 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20066 installFlags = INSTALL_INTERNAL; 20067 moveCompleteApp = !currentAsec; 20068 measurePath = Environment.getDataAppDirectory(volumeUuid); 20069 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20070 installFlags = INSTALL_EXTERNAL; 20071 moveCompleteApp = false; 20072 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20073 } else { 20074 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20075 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20076 || !volume.isMountedWritable()) { 20077 freezer.close(); 20078 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20079 "Move location not mounted private volume"); 20080 } 20081 20082 Preconditions.checkState(!currentAsec); 20083 20084 installFlags = INSTALL_INTERNAL; 20085 moveCompleteApp = true; 20086 measurePath = Environment.getDataAppDirectory(volumeUuid); 20087 } 20088 20089 final PackageStats stats = new PackageStats(null, -1); 20090 synchronized (mInstaller) { 20091 for (int userId : installedUserIds) { 20092 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20093 freezer.close(); 20094 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20095 "Failed to measure package size"); 20096 } 20097 } 20098 } 20099 20100 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20101 + stats.dataSize); 20102 20103 final long startFreeBytes = measurePath.getFreeSpace(); 20104 final long sizeBytes; 20105 if (moveCompleteApp) { 20106 sizeBytes = stats.codeSize + stats.dataSize; 20107 } else { 20108 sizeBytes = stats.codeSize; 20109 } 20110 20111 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20112 freezer.close(); 20113 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20114 "Not enough free space to move"); 20115 } 20116 20117 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20118 20119 final CountDownLatch installedLatch = new CountDownLatch(1); 20120 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20121 @Override 20122 public void onUserActionRequired(Intent intent) throws RemoteException { 20123 throw new IllegalStateException(); 20124 } 20125 20126 @Override 20127 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20128 Bundle extras) throws RemoteException { 20129 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20130 + PackageManager.installStatusToString(returnCode, msg)); 20131 20132 installedLatch.countDown(); 20133 freezer.close(); 20134 20135 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20136 switch (status) { 20137 case PackageInstaller.STATUS_SUCCESS: 20138 mMoveCallbacks.notifyStatusChanged(moveId, 20139 PackageManager.MOVE_SUCCEEDED); 20140 break; 20141 case PackageInstaller.STATUS_FAILURE_STORAGE: 20142 mMoveCallbacks.notifyStatusChanged(moveId, 20143 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20144 break; 20145 default: 20146 mMoveCallbacks.notifyStatusChanged(moveId, 20147 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20148 break; 20149 } 20150 } 20151 }; 20152 20153 final MoveInfo move; 20154 if (moveCompleteApp) { 20155 // Kick off a thread to report progress estimates 20156 new Thread() { 20157 @Override 20158 public void run() { 20159 while (true) { 20160 try { 20161 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20162 break; 20163 } 20164 } catch (InterruptedException ignored) { 20165 } 20166 20167 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20168 final int progress = 10 + (int) MathUtils.constrain( 20169 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20170 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20171 } 20172 } 20173 }.start(); 20174 20175 final String dataAppName = codeFile.getName(); 20176 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20177 dataAppName, appId, seinfo, targetSdkVersion); 20178 } else { 20179 move = null; 20180 } 20181 20182 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20183 20184 final Message msg = mHandler.obtainMessage(INIT_COPY); 20185 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20186 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20187 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20188 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20189 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20190 msg.obj = params; 20191 20192 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20193 System.identityHashCode(msg.obj)); 20194 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20195 System.identityHashCode(msg.obj)); 20196 20197 mHandler.sendMessage(msg); 20198 } 20199 20200 @Override 20201 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20202 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20203 20204 final int realMoveId = mNextMoveId.getAndIncrement(); 20205 final Bundle extras = new Bundle(); 20206 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20207 mMoveCallbacks.notifyCreated(realMoveId, extras); 20208 20209 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20210 @Override 20211 public void onCreated(int moveId, Bundle extras) { 20212 // Ignored 20213 } 20214 20215 @Override 20216 public void onStatusChanged(int moveId, int status, long estMillis) { 20217 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20218 } 20219 }; 20220 20221 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20222 storage.setPrimaryStorageUuid(volumeUuid, callback); 20223 return realMoveId; 20224 } 20225 20226 @Override 20227 public int getMoveStatus(int moveId) { 20228 mContext.enforceCallingOrSelfPermission( 20229 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20230 return mMoveCallbacks.mLastStatus.get(moveId); 20231 } 20232 20233 @Override 20234 public void registerMoveCallback(IPackageMoveObserver callback) { 20235 mContext.enforceCallingOrSelfPermission( 20236 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20237 mMoveCallbacks.register(callback); 20238 } 20239 20240 @Override 20241 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20242 mContext.enforceCallingOrSelfPermission( 20243 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20244 mMoveCallbacks.unregister(callback); 20245 } 20246 20247 @Override 20248 public boolean setInstallLocation(int loc) { 20249 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20250 null); 20251 if (getInstallLocation() == loc) { 20252 return true; 20253 } 20254 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20255 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20256 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20257 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20258 return true; 20259 } 20260 return false; 20261 } 20262 20263 @Override 20264 public int getInstallLocation() { 20265 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20266 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20267 PackageHelper.APP_INSTALL_AUTO); 20268 } 20269 20270 /** Called by UserManagerService */ 20271 void cleanUpUser(UserManagerService userManager, int userHandle) { 20272 synchronized (mPackages) { 20273 mDirtyUsers.remove(userHandle); 20274 mUserNeedsBadging.delete(userHandle); 20275 mSettings.removeUserLPw(userHandle); 20276 mPendingBroadcasts.remove(userHandle); 20277 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20278 removeUnusedPackagesLPw(userManager, userHandle); 20279 } 20280 } 20281 20282 /** 20283 * We're removing userHandle and would like to remove any downloaded packages 20284 * that are no longer in use by any other user. 20285 * @param userHandle the user being removed 20286 */ 20287 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20288 final boolean DEBUG_CLEAN_APKS = false; 20289 int [] users = userManager.getUserIds(); 20290 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20291 while (psit.hasNext()) { 20292 PackageSetting ps = psit.next(); 20293 if (ps.pkg == null) { 20294 continue; 20295 } 20296 final String packageName = ps.pkg.packageName; 20297 // Skip over if system app 20298 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20299 continue; 20300 } 20301 if (DEBUG_CLEAN_APKS) { 20302 Slog.i(TAG, "Checking package " + packageName); 20303 } 20304 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20305 if (keep) { 20306 if (DEBUG_CLEAN_APKS) { 20307 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20308 } 20309 } else { 20310 for (int i = 0; i < users.length; i++) { 20311 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20312 keep = true; 20313 if (DEBUG_CLEAN_APKS) { 20314 Slog.i(TAG, " Keeping package " + packageName + " for user " 20315 + users[i]); 20316 } 20317 break; 20318 } 20319 } 20320 } 20321 if (!keep) { 20322 if (DEBUG_CLEAN_APKS) { 20323 Slog.i(TAG, " Removing package " + packageName); 20324 } 20325 mHandler.post(new Runnable() { 20326 public void run() { 20327 deletePackageX(packageName, userHandle, 0); 20328 } //end run 20329 }); 20330 } 20331 } 20332 } 20333 20334 /** Called by UserManagerService */ 20335 void createNewUser(int userId) { 20336 synchronized (mInstallLock) { 20337 mSettings.createNewUserLI(this, mInstaller, userId); 20338 } 20339 synchronized (mPackages) { 20340 scheduleWritePackageRestrictionsLocked(userId); 20341 scheduleWritePackageListLocked(userId); 20342 applyFactoryDefaultBrowserLPw(userId); 20343 primeDomainVerificationsLPw(userId); 20344 } 20345 } 20346 20347 void onBeforeUserStartUninitialized(final int userId) { 20348 synchronized (mPackages) { 20349 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20350 return; 20351 } 20352 } 20353 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20354 // If permission review for legacy apps is required, we represent 20355 // dagerous permissions for such apps as always granted runtime 20356 // permissions to keep per user flag state whether review is needed. 20357 // Hence, if a new user is added we have to propagate dangerous 20358 // permission grants for these legacy apps. 20359 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20360 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20361 | UPDATE_PERMISSIONS_REPLACE_ALL); 20362 } 20363 } 20364 20365 @Override 20366 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20367 mContext.enforceCallingOrSelfPermission( 20368 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20369 "Only package verification agents can read the verifier device identity"); 20370 20371 synchronized (mPackages) { 20372 return mSettings.getVerifierDeviceIdentityLPw(); 20373 } 20374 } 20375 20376 @Override 20377 public void setPermissionEnforced(String permission, boolean enforced) { 20378 // TODO: Now that we no longer change GID for storage, this should to away. 20379 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20380 "setPermissionEnforced"); 20381 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20382 synchronized (mPackages) { 20383 if (mSettings.mReadExternalStorageEnforced == null 20384 || mSettings.mReadExternalStorageEnforced != enforced) { 20385 mSettings.mReadExternalStorageEnforced = enforced; 20386 mSettings.writeLPr(); 20387 } 20388 } 20389 // kill any non-foreground processes so we restart them and 20390 // grant/revoke the GID. 20391 final IActivityManager am = ActivityManagerNative.getDefault(); 20392 if (am != null) { 20393 final long token = Binder.clearCallingIdentity(); 20394 try { 20395 am.killProcessesBelowForeground("setPermissionEnforcement"); 20396 } catch (RemoteException e) { 20397 } finally { 20398 Binder.restoreCallingIdentity(token); 20399 } 20400 } 20401 } else { 20402 throw new IllegalArgumentException("No selective enforcement for " + permission); 20403 } 20404 } 20405 20406 @Override 20407 @Deprecated 20408 public boolean isPermissionEnforced(String permission) { 20409 return true; 20410 } 20411 20412 @Override 20413 public boolean isStorageLow() { 20414 final long token = Binder.clearCallingIdentity(); 20415 try { 20416 final DeviceStorageMonitorInternal 20417 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20418 if (dsm != null) { 20419 return dsm.isMemoryLow(); 20420 } else { 20421 return false; 20422 } 20423 } finally { 20424 Binder.restoreCallingIdentity(token); 20425 } 20426 } 20427 20428 @Override 20429 public IPackageInstaller getPackageInstaller() { 20430 return mInstallerService; 20431 } 20432 20433 private boolean userNeedsBadging(int userId) { 20434 int index = mUserNeedsBadging.indexOfKey(userId); 20435 if (index < 0) { 20436 final UserInfo userInfo; 20437 final long token = Binder.clearCallingIdentity(); 20438 try { 20439 userInfo = sUserManager.getUserInfo(userId); 20440 } finally { 20441 Binder.restoreCallingIdentity(token); 20442 } 20443 final boolean b; 20444 if (userInfo != null && userInfo.isManagedProfile()) { 20445 b = true; 20446 } else { 20447 b = false; 20448 } 20449 mUserNeedsBadging.put(userId, b); 20450 return b; 20451 } 20452 return mUserNeedsBadging.valueAt(index); 20453 } 20454 20455 @Override 20456 public KeySet getKeySetByAlias(String packageName, String alias) { 20457 if (packageName == null || alias == null) { 20458 return null; 20459 } 20460 synchronized(mPackages) { 20461 final PackageParser.Package pkg = mPackages.get(packageName); 20462 if (pkg == null) { 20463 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20464 throw new IllegalArgumentException("Unknown package: " + packageName); 20465 } 20466 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20467 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20468 } 20469 } 20470 20471 @Override 20472 public KeySet getSigningKeySet(String packageName) { 20473 if (packageName == null) { 20474 return null; 20475 } 20476 synchronized(mPackages) { 20477 final PackageParser.Package pkg = mPackages.get(packageName); 20478 if (pkg == null) { 20479 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20480 throw new IllegalArgumentException("Unknown package: " + packageName); 20481 } 20482 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20483 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20484 throw new SecurityException("May not access signing KeySet of other apps."); 20485 } 20486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20487 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20488 } 20489 } 20490 20491 @Override 20492 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20493 if (packageName == null || ks == null) { 20494 return false; 20495 } 20496 synchronized(mPackages) { 20497 final PackageParser.Package pkg = mPackages.get(packageName); 20498 if (pkg == null) { 20499 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20500 throw new IllegalArgumentException("Unknown package: " + packageName); 20501 } 20502 IBinder ksh = ks.getToken(); 20503 if (ksh instanceof KeySetHandle) { 20504 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20505 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20506 } 20507 return false; 20508 } 20509 } 20510 20511 @Override 20512 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20513 if (packageName == null || ks == null) { 20514 return false; 20515 } 20516 synchronized(mPackages) { 20517 final PackageParser.Package pkg = mPackages.get(packageName); 20518 if (pkg == null) { 20519 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20520 throw new IllegalArgumentException("Unknown package: " + packageName); 20521 } 20522 IBinder ksh = ks.getToken(); 20523 if (ksh instanceof KeySetHandle) { 20524 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20525 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20526 } 20527 return false; 20528 } 20529 } 20530 20531 private void deletePackageIfUnusedLPr(final String packageName) { 20532 PackageSetting ps = mSettings.mPackages.get(packageName); 20533 if (ps == null) { 20534 return; 20535 } 20536 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20537 // TODO Implement atomic delete if package is unused 20538 // It is currently possible that the package will be deleted even if it is installed 20539 // after this method returns. 20540 mHandler.post(new Runnable() { 20541 public void run() { 20542 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20543 } 20544 }); 20545 } 20546 } 20547 20548 /** 20549 * Check and throw if the given before/after packages would be considered a 20550 * downgrade. 20551 */ 20552 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20553 throws PackageManagerException { 20554 if (after.versionCode < before.mVersionCode) { 20555 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20556 "Update version code " + after.versionCode + " is older than current " 20557 + before.mVersionCode); 20558 } else if (after.versionCode == before.mVersionCode) { 20559 if (after.baseRevisionCode < before.baseRevisionCode) { 20560 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20561 "Update base revision code " + after.baseRevisionCode 20562 + " is older than current " + before.baseRevisionCode); 20563 } 20564 20565 if (!ArrayUtils.isEmpty(after.splitNames)) { 20566 for (int i = 0; i < after.splitNames.length; i++) { 20567 final String splitName = after.splitNames[i]; 20568 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20569 if (j != -1) { 20570 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20571 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20572 "Update split " + splitName + " revision code " 20573 + after.splitRevisionCodes[i] + " is older than current " 20574 + before.splitRevisionCodes[j]); 20575 } 20576 } 20577 } 20578 } 20579 } 20580 } 20581 20582 private static class MoveCallbacks extends Handler { 20583 private static final int MSG_CREATED = 1; 20584 private static final int MSG_STATUS_CHANGED = 2; 20585 20586 private final RemoteCallbackList<IPackageMoveObserver> 20587 mCallbacks = new RemoteCallbackList<>(); 20588 20589 private final SparseIntArray mLastStatus = new SparseIntArray(); 20590 20591 public MoveCallbacks(Looper looper) { 20592 super(looper); 20593 } 20594 20595 public void register(IPackageMoveObserver callback) { 20596 mCallbacks.register(callback); 20597 } 20598 20599 public void unregister(IPackageMoveObserver callback) { 20600 mCallbacks.unregister(callback); 20601 } 20602 20603 @Override 20604 public void handleMessage(Message msg) { 20605 final SomeArgs args = (SomeArgs) msg.obj; 20606 final int n = mCallbacks.beginBroadcast(); 20607 for (int i = 0; i < n; i++) { 20608 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20609 try { 20610 invokeCallback(callback, msg.what, args); 20611 } catch (RemoteException ignored) { 20612 } 20613 } 20614 mCallbacks.finishBroadcast(); 20615 args.recycle(); 20616 } 20617 20618 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20619 throws RemoteException { 20620 switch (what) { 20621 case MSG_CREATED: { 20622 callback.onCreated(args.argi1, (Bundle) args.arg2); 20623 break; 20624 } 20625 case MSG_STATUS_CHANGED: { 20626 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20627 break; 20628 } 20629 } 20630 } 20631 20632 private void notifyCreated(int moveId, Bundle extras) { 20633 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20634 20635 final SomeArgs args = SomeArgs.obtain(); 20636 args.argi1 = moveId; 20637 args.arg2 = extras; 20638 obtainMessage(MSG_CREATED, args).sendToTarget(); 20639 } 20640 20641 private void notifyStatusChanged(int moveId, int status) { 20642 notifyStatusChanged(moveId, status, -1); 20643 } 20644 20645 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20646 Slog.v(TAG, "Move " + moveId + " status " + status); 20647 20648 final SomeArgs args = SomeArgs.obtain(); 20649 args.argi1 = moveId; 20650 args.argi2 = status; 20651 args.arg3 = estMillis; 20652 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20653 20654 synchronized (mLastStatus) { 20655 mLastStatus.put(moveId, status); 20656 } 20657 } 20658 } 20659 20660 private final static class OnPermissionChangeListeners extends Handler { 20661 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20662 20663 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20664 new RemoteCallbackList<>(); 20665 20666 public OnPermissionChangeListeners(Looper looper) { 20667 super(looper); 20668 } 20669 20670 @Override 20671 public void handleMessage(Message msg) { 20672 switch (msg.what) { 20673 case MSG_ON_PERMISSIONS_CHANGED: { 20674 final int uid = msg.arg1; 20675 handleOnPermissionsChanged(uid); 20676 } break; 20677 } 20678 } 20679 20680 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20681 mPermissionListeners.register(listener); 20682 20683 } 20684 20685 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20686 mPermissionListeners.unregister(listener); 20687 } 20688 20689 public void onPermissionsChanged(int uid) { 20690 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20691 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20692 } 20693 } 20694 20695 private void handleOnPermissionsChanged(int uid) { 20696 final int count = mPermissionListeners.beginBroadcast(); 20697 try { 20698 for (int i = 0; i < count; i++) { 20699 IOnPermissionsChangeListener callback = mPermissionListeners 20700 .getBroadcastItem(i); 20701 try { 20702 callback.onPermissionsChanged(uid); 20703 } catch (RemoteException e) { 20704 Log.e(TAG, "Permission listener is dead", e); 20705 } 20706 } 20707 } finally { 20708 mPermissionListeners.finishBroadcast(); 20709 } 20710 } 20711 } 20712 20713 private class PackageManagerInternalImpl extends PackageManagerInternal { 20714 @Override 20715 public void setLocationPackagesProvider(PackagesProvider provider) { 20716 synchronized (mPackages) { 20717 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20718 } 20719 } 20720 20721 @Override 20722 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20723 synchronized (mPackages) { 20724 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20725 } 20726 } 20727 20728 @Override 20729 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20730 synchronized (mPackages) { 20731 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20732 } 20733 } 20734 20735 @Override 20736 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20737 synchronized (mPackages) { 20738 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20739 } 20740 } 20741 20742 @Override 20743 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20744 synchronized (mPackages) { 20745 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20746 } 20747 } 20748 20749 @Override 20750 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20751 synchronized (mPackages) { 20752 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20753 } 20754 } 20755 20756 @Override 20757 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20758 synchronized (mPackages) { 20759 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20760 packageName, userId); 20761 } 20762 } 20763 20764 @Override 20765 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20766 synchronized (mPackages) { 20767 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20768 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20769 packageName, userId); 20770 } 20771 } 20772 20773 @Override 20774 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20775 synchronized (mPackages) { 20776 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20777 packageName, userId); 20778 } 20779 } 20780 20781 @Override 20782 public void setKeepUninstalledPackages(final List<String> packageList) { 20783 Preconditions.checkNotNull(packageList); 20784 List<String> removedFromList = null; 20785 synchronized (mPackages) { 20786 if (mKeepUninstalledPackages != null) { 20787 final int packagesCount = mKeepUninstalledPackages.size(); 20788 for (int i = 0; i < packagesCount; i++) { 20789 String oldPackage = mKeepUninstalledPackages.get(i); 20790 if (packageList != null && packageList.contains(oldPackage)) { 20791 continue; 20792 } 20793 if (removedFromList == null) { 20794 removedFromList = new ArrayList<>(); 20795 } 20796 removedFromList.add(oldPackage); 20797 } 20798 } 20799 mKeepUninstalledPackages = new ArrayList<>(packageList); 20800 if (removedFromList != null) { 20801 final int removedCount = removedFromList.size(); 20802 for (int i = 0; i < removedCount; i++) { 20803 deletePackageIfUnusedLPr(removedFromList.get(i)); 20804 } 20805 } 20806 } 20807 } 20808 20809 @Override 20810 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20811 synchronized (mPackages) { 20812 // If we do not support permission review, done. 20813 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20814 return false; 20815 } 20816 20817 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20818 if (packageSetting == null) { 20819 return false; 20820 } 20821 20822 // Permission review applies only to apps not supporting the new permission model. 20823 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20824 return false; 20825 } 20826 20827 // Legacy apps have the permission and get user consent on launch. 20828 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20829 return permissionsState.isPermissionReviewRequired(userId); 20830 } 20831 } 20832 20833 @Override 20834 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20835 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20836 } 20837 20838 @Override 20839 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20840 int userId) { 20841 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20842 } 20843 20844 @Override 20845 public void setDeviceAndProfileOwnerPackages( 20846 int deviceOwnerUserId, String deviceOwnerPackage, 20847 SparseArray<String> profileOwnerPackages) { 20848 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20849 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20850 } 20851 20852 @Override 20853 public boolean canPackageBeWiped(int userId, String packageName) { 20854 return mProtectedPackages.canPackageBeWiped(userId, 20855 packageName); 20856 } 20857 } 20858 20859 @Override 20860 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20861 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20862 synchronized (mPackages) { 20863 final long identity = Binder.clearCallingIdentity(); 20864 try { 20865 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20866 packageNames, userId); 20867 } finally { 20868 Binder.restoreCallingIdentity(identity); 20869 } 20870 } 20871 } 20872 20873 private static void enforceSystemOrPhoneCaller(String tag) { 20874 int callingUid = Binder.getCallingUid(); 20875 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20876 throw new SecurityException( 20877 "Cannot call " + tag + " from UID " + callingUid); 20878 } 20879 } 20880 20881 boolean isHistoricalPackageUsageAvailable() { 20882 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20883 } 20884 20885 /** 20886 * Return a <b>copy</b> of the collection of packages known to the package manager. 20887 * @return A copy of the values of mPackages. 20888 */ 20889 Collection<PackageParser.Package> getPackages() { 20890 synchronized (mPackages) { 20891 return new ArrayList<>(mPackages.values()); 20892 } 20893 } 20894 20895 /** 20896 * Logs process start information (including base APK hash) to the security log. 20897 * @hide 20898 */ 20899 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20900 String apkFile, int pid) { 20901 if (!SecurityLog.isLoggingEnabled()) { 20902 return; 20903 } 20904 Bundle data = new Bundle(); 20905 data.putLong("startTimestamp", System.currentTimeMillis()); 20906 data.putString("processName", processName); 20907 data.putInt("uid", uid); 20908 data.putString("seinfo", seinfo); 20909 data.putString("apkFile", apkFile); 20910 data.putInt("pid", pid); 20911 Message msg = mProcessLoggingHandler.obtainMessage( 20912 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20913 msg.setData(data); 20914 mProcessLoggingHandler.sendMessage(msg); 20915 } 20916} 20917