PackageManagerService.java revision 6c915ead38db0a2a6393c40d4fbac959399439c5
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.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.logging.MetricsProto.MetricsEvent; 232import com.android.internal.os.IParcelFileDescriptorFactory; 233import com.android.internal.os.InstallerConnection.InstallerException; 234import com.android.internal.os.SomeArgs; 235import com.android.internal.os.Zygote; 236import com.android.internal.telephony.CarrierAppUtils; 237import com.android.internal.util.ArrayUtils; 238import com.android.internal.util.FastPrintWriter; 239import com.android.internal.util.FastXmlSerializer; 240import com.android.internal.util.IndentingPrintWriter; 241import com.android.internal.util.Preconditions; 242import com.android.internal.util.XmlUtils; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedInputStream; 268import java.io.BufferedOutputStream; 269import java.io.BufferedReader; 270import java.io.ByteArrayInputStream; 271import java.io.ByteArrayOutputStream; 272import java.io.File; 273import java.io.FileDescriptor; 274import java.io.FileInputStream; 275import java.io.FileNotFoundException; 276import java.io.FileOutputStream; 277import java.io.FileReader; 278import java.io.FilenameFilter; 279import java.io.IOException; 280import java.io.InputStream; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307import java.util.concurrent.atomic.AtomicLong; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = false; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 370 371 private static final boolean DISABLE_EPHEMERAL_APPS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 508 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 509 510 /** Special library name that skips shared libraries check during compilation. */ 511 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 512 513 final ServiceThread mHandlerThread; 514 515 final PackageHandler mHandler; 516 517 private final ProcessLoggingHandler mProcessLoggingHandler; 518 519 /** 520 * Messages for {@link #mHandler} that need to wait for system ready before 521 * being dispatched. 522 */ 523 private ArrayList<Message> mPostSystemReadyMessages; 524 525 final int mSdkVersion = Build.VERSION.SDK_INT; 526 527 final Context mContext; 528 final boolean mFactoryTest; 529 final boolean mOnlyCore; 530 final DisplayMetrics mMetrics; 531 final int mDefParseFlags; 532 final String[] mSeparateProcesses; 533 final boolean mIsUpgrade; 534 final boolean mIsPreNUpgrade; 535 536 /** The location for ASEC container files on internal storage. */ 537 final String mAsecInternalPath; 538 539 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 540 // LOCK HELD. Can be called with mInstallLock held. 541 @GuardedBy("mInstallLock") 542 final Installer mInstaller; 543 544 /** Directory where installed third-party apps stored */ 545 final File mAppInstallDir; 546 final File mEphemeralInstallDir; 547 548 /** 549 * Directory to which applications installed internally have their 550 * 32 bit native libraries copied. 551 */ 552 private File mAppLib32InstallDir; 553 554 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 555 // apps. 556 final File mDrmAppPrivateInstallDir; 557 558 // ---------------------------------------------------------------- 559 560 // Lock for state used when installing and doing other long running 561 // operations. Methods that must be called with this lock held have 562 // the suffix "LI". 563 final Object mInstallLock = new Object(); 564 565 // ---------------------------------------------------------------- 566 567 // Keys are String (package name), values are Package. This also serves 568 // as the lock for the global state. Methods that must be called with 569 // this lock held have the prefix "LP". 570 @GuardedBy("mPackages") 571 final ArrayMap<String, PackageParser.Package> mPackages = 572 new ArrayMap<String, PackageParser.Package>(); 573 574 final ArrayMap<String, Set<String>> mKnownCodebase = 575 new ArrayMap<String, Set<String>>(); 576 577 // Tracks available target package names -> overlay package paths. 578 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 579 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 580 581 /** 582 * Tracks new system packages [received in an OTA] that we expect to 583 * find updated user-installed versions. Keys are package name, values 584 * are package location. 585 */ 586 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 587 /** 588 * Tracks high priority intent filters for protected actions. During boot, certain 589 * filter actions are protected and should never be allowed to have a high priority 590 * intent filter for them. However, there is one, and only one exception -- the 591 * setup wizard. It must be able to define a high priority intent filter for these 592 * actions to ensure there are no escapes from the wizard. We need to delay processing 593 * of these during boot as we need to look at all of the system packages in order 594 * to know which component is the setup wizard. 595 */ 596 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 597 /** 598 * Whether or not processing protected filters should be deferred. 599 */ 600 private boolean mDeferProtectedFilters = true; 601 602 /** 603 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 604 */ 605 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 606 /** 607 * Whether or not system app permissions should be promoted from install to runtime. 608 */ 609 boolean mPromoteSystemApps; 610 611 @GuardedBy("mPackages") 612 final Settings mSettings; 613 614 /** 615 * Set of package names that are currently "frozen", which means active 616 * surgery is being done on the code/data for that package. The platform 617 * will refuse to launch frozen packages to avoid race conditions. 618 * 619 * @see PackageFreezer 620 */ 621 @GuardedBy("mPackages") 622 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 623 624 boolean mRestoredSettings; 625 626 // System configuration read by SystemConfig. 627 final int[] mGlobalGids; 628 final SparseArray<ArraySet<String>> mSystemPermissions; 629 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 630 631 // If mac_permissions.xml was found for seinfo labeling. 632 boolean mFoundPolicyFile; 633 634 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 635 636 public static final class SharedLibraryEntry { 637 public final String path; 638 public final String apk; 639 640 SharedLibraryEntry(String _path, String _apk) { 641 path = _path; 642 apk = _apk; 643 } 644 } 645 646 // Currently known shared libraries. 647 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 648 new ArrayMap<String, SharedLibraryEntry>(); 649 650 // All available activities, for your resolving pleasure. 651 final ActivityIntentResolver mActivities = 652 new ActivityIntentResolver(); 653 654 // All available receivers, for your resolving pleasure. 655 final ActivityIntentResolver mReceivers = 656 new ActivityIntentResolver(); 657 658 // All available services, for your resolving pleasure. 659 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 660 661 // All available providers, for your resolving pleasure. 662 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 663 664 // Mapping from provider base names (first directory in content URI codePath) 665 // to the provider information. 666 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 667 new ArrayMap<String, PackageParser.Provider>(); 668 669 // Mapping from instrumentation class names to info about them. 670 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 671 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 672 673 // Mapping from permission names to info about them. 674 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 675 new ArrayMap<String, PackageParser.PermissionGroup>(); 676 677 // Packages whose data we have transfered into another package, thus 678 // should no longer exist. 679 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 680 681 // Broadcast actions that are only available to the system. 682 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 683 684 /** List of packages waiting for verification. */ 685 final SparseArray<PackageVerificationState> mPendingVerification 686 = new SparseArray<PackageVerificationState>(); 687 688 /** Set of packages associated with each app op permission. */ 689 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 690 691 final PackageInstallerService mInstallerService; 692 693 private final PackageDexOptimizer mPackageDexOptimizer; 694 695 private AtomicInteger mNextMoveId = new AtomicInteger(); 696 private final MoveCallbacks mMoveCallbacks; 697 698 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 699 700 // Cache of users who need badging. 701 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 702 703 /** Token for keys in mPendingVerification. */ 704 private int mPendingVerificationToken = 0; 705 706 volatile boolean mSystemReady; 707 volatile boolean mSafeMode; 708 volatile boolean mHasSystemUidErrors; 709 710 ApplicationInfo mAndroidApplication; 711 final ActivityInfo mResolveActivity = new ActivityInfo(); 712 final ResolveInfo mResolveInfo = new ResolveInfo(); 713 ComponentName mResolveComponentName; 714 PackageParser.Package mPlatformPackage; 715 ComponentName mCustomResolverComponentName; 716 717 boolean mResolverReplaced = false; 718 719 private final @Nullable ComponentName mIntentFilterVerifierComponent; 720 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 721 722 private int mIntentFilterVerificationToken = 0; 723 724 /** Component that knows whether or not an ephemeral application exists */ 725 final ComponentName mEphemeralResolverComponent; 726 /** The service connection to the ephemeral resolver */ 727 final EphemeralResolverConnection mEphemeralResolverConnection; 728 729 /** Component used to install ephemeral applications */ 730 final ComponentName mEphemeralInstallerComponent; 731 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 732 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 733 734 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 735 = new SparseArray<IntentFilterVerificationState>(); 736 737 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 738 new DefaultPermissionGrantPolicy(this); 739 740 // List of packages names to keep cached, even if they are uninstalled for all users 741 private List<String> mKeepUninstalledPackages; 742 743 private UserManagerInternal mUserManagerInternal; 744 745 private static class IFVerificationParams { 746 PackageParser.Package pkg; 747 boolean replacing; 748 int userId; 749 int verifierUid; 750 751 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 752 int _userId, int _verifierUid) { 753 pkg = _pkg; 754 replacing = _replacing; 755 userId = _userId; 756 replacing = _replacing; 757 verifierUid = _verifierUid; 758 } 759 } 760 761 private interface IntentFilterVerifier<T extends IntentFilter> { 762 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 763 T filter, String packageName); 764 void startVerifications(int userId); 765 void receiveVerificationResponse(int verificationId); 766 } 767 768 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 769 private Context mContext; 770 private ComponentName mIntentFilterVerifierComponent; 771 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 772 773 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 774 mContext = context; 775 mIntentFilterVerifierComponent = verifierComponent; 776 } 777 778 private String getDefaultScheme() { 779 return IntentFilter.SCHEME_HTTPS; 780 } 781 782 @Override 783 public void startVerifications(int userId) { 784 // Launch verifications requests 785 int count = mCurrentIntentFilterVerifications.size(); 786 for (int n=0; n<count; n++) { 787 int verificationId = mCurrentIntentFilterVerifications.get(n); 788 final IntentFilterVerificationState ivs = 789 mIntentFilterVerificationStates.get(verificationId); 790 791 String packageName = ivs.getPackageName(); 792 793 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 794 final int filterCount = filters.size(); 795 ArraySet<String> domainsSet = new ArraySet<>(); 796 for (int m=0; m<filterCount; m++) { 797 PackageParser.ActivityIntentInfo filter = filters.get(m); 798 domainsSet.addAll(filter.getHostsList()); 799 } 800 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 801 synchronized (mPackages) { 802 if (mSettings.createIntentFilterVerificationIfNeededLPw( 803 packageName, domainsList) != null) { 804 scheduleWriteSettingsLocked(); 805 } 806 } 807 sendVerificationRequest(userId, verificationId, ivs); 808 } 809 mCurrentIntentFilterVerifications.clear(); 810 } 811 812 private void sendVerificationRequest(int userId, int verificationId, 813 IntentFilterVerificationState ivs) { 814 815 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 816 verificationIntent.putExtra( 817 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 818 verificationId); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 821 getDefaultScheme()); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 824 ivs.getHostsString()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 827 ivs.getPackageName()); 828 verificationIntent.setComponent(mIntentFilterVerifierComponent); 829 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 830 831 UserHandle user = new UserHandle(userId); 832 mContext.sendBroadcastAsUser(verificationIntent, user); 833 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 834 "Sending IntentFilter verification broadcast"); 835 } 836 837 public void receiveVerificationResponse(int verificationId) { 838 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 839 840 final boolean verified = ivs.isVerified(); 841 842 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 843 final int count = filters.size(); 844 if (DEBUG_DOMAIN_VERIFICATION) { 845 Slog.i(TAG, "Received verification response " + verificationId 846 + " for " + count + " filters, verified=" + verified); 847 } 848 for (int n=0; n<count; n++) { 849 PackageParser.ActivityIntentInfo filter = filters.get(n); 850 filter.setVerified(verified); 851 852 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 853 + " verified with result:" + verified + " and hosts:" 854 + ivs.getHostsString()); 855 } 856 857 mIntentFilterVerificationStates.remove(verificationId); 858 859 final String packageName = ivs.getPackageName(); 860 IntentFilterVerificationInfo ivi = null; 861 862 synchronized (mPackages) { 863 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 864 } 865 if (ivi == null) { 866 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 867 + verificationId + " packageName:" + packageName); 868 return; 869 } 870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 871 "Updating IntentFilterVerificationInfo for package " + packageName 872 +" verificationId:" + verificationId); 873 874 synchronized (mPackages) { 875 if (verified) { 876 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 877 } else { 878 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 879 } 880 scheduleWriteSettingsLocked(); 881 882 final int userId = ivs.getUserId(); 883 if (userId != UserHandle.USER_ALL) { 884 final int userStatus = 885 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 886 887 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 888 boolean needUpdate = false; 889 890 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 891 // already been set by the User thru the Disambiguation dialog 892 switch (userStatus) { 893 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 894 if (verified) { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 896 } else { 897 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 898 } 899 needUpdate = true; 900 break; 901 902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 903 if (verified) { 904 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 905 needUpdate = true; 906 } 907 break; 908 909 default: 910 // Nothing to do 911 } 912 913 if (needUpdate) { 914 mSettings.updateIntentFilterVerificationStatusLPw( 915 packageName, updatedStatus, userId); 916 scheduleWritePackageRestrictionsLocked(userId); 917 } 918 } 919 } 920 } 921 922 @Override 923 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 924 ActivityIntentInfo filter, String packageName) { 925 if (!hasValidDomains(filter)) { 926 return false; 927 } 928 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 929 if (ivs == null) { 930 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 931 packageName); 932 } 933 if (DEBUG_DOMAIN_VERIFICATION) { 934 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 935 } 936 ivs.addFilter(filter); 937 return true; 938 } 939 940 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 941 int userId, int verificationId, String packageName) { 942 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 943 verifierUid, userId, packageName); 944 ivs.setPendingState(); 945 synchronized (mPackages) { 946 mIntentFilterVerificationStates.append(verificationId, ivs); 947 mCurrentIntentFilterVerifications.add(verificationId); 948 } 949 return ivs; 950 } 951 } 952 953 private static boolean hasValidDomains(ActivityIntentInfo filter) { 954 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 955 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 956 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 957 } 958 959 // Set of pending broadcasts for aggregating enable/disable of components. 960 static class PendingPackageBroadcasts { 961 // for each user id, a map of <package name -> components within that package> 962 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 963 964 public PendingPackageBroadcasts() { 965 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 966 } 967 968 public ArrayList<String> get(int userId, String packageName) { 969 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 970 return packages.get(packageName); 971 } 972 973 public void put(int userId, String packageName, ArrayList<String> components) { 974 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 975 packages.put(packageName, components); 976 } 977 978 public void remove(int userId, String packageName) { 979 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 980 if (packages != null) { 981 packages.remove(packageName); 982 } 983 } 984 985 public void remove(int userId) { 986 mUidMap.remove(userId); 987 } 988 989 public int userIdCount() { 990 return mUidMap.size(); 991 } 992 993 public int userIdAt(int n) { 994 return mUidMap.keyAt(n); 995 } 996 997 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 998 return mUidMap.get(userId); 999 } 1000 1001 public int size() { 1002 // total number of pending broadcast entries across all userIds 1003 int num = 0; 1004 for (int i = 0; i< mUidMap.size(); i++) { 1005 num += mUidMap.valueAt(i).size(); 1006 } 1007 return num; 1008 } 1009 1010 public void clear() { 1011 mUidMap.clear(); 1012 } 1013 1014 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1015 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1016 if (map == null) { 1017 map = new ArrayMap<String, ArrayList<String>>(); 1018 mUidMap.put(userId, map); 1019 } 1020 return map; 1021 } 1022 } 1023 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1024 1025 // Service Connection to remote media container service to copy 1026 // package uri's from external media onto secure containers 1027 // or internal storage. 1028 private IMediaContainerService mContainerService = null; 1029 1030 static final int SEND_PENDING_BROADCAST = 1; 1031 static final int MCS_BOUND = 3; 1032 static final int END_COPY = 4; 1033 static final int INIT_COPY = 5; 1034 static final int MCS_UNBIND = 6; 1035 static final int START_CLEANING_PACKAGE = 7; 1036 static final int FIND_INSTALL_LOC = 8; 1037 static final int POST_INSTALL = 9; 1038 static final int MCS_RECONNECT = 10; 1039 static final int MCS_GIVE_UP = 11; 1040 static final int UPDATED_MEDIA_STATUS = 12; 1041 static final int WRITE_SETTINGS = 13; 1042 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1043 static final int PACKAGE_VERIFIED = 15; 1044 static final int CHECK_PENDING_VERIFICATION = 16; 1045 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1046 static final int INTENT_FILTER_VERIFIED = 18; 1047 1048 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1049 1050 // Delay time in millisecs 1051 static final int BROADCAST_DELAY = 10 * 1000; 1052 1053 static UserManagerService sUserManager; 1054 1055 // Stores a list of users whose package restrictions file needs to be updated 1056 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1057 1058 final private DefaultContainerConnection mDefContainerConn = 1059 new DefaultContainerConnection(); 1060 class DefaultContainerConnection implements ServiceConnection { 1061 public void onServiceConnected(ComponentName name, IBinder service) { 1062 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1063 IMediaContainerService imcs = 1064 IMediaContainerService.Stub.asInterface(service); 1065 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1066 } 1067 1068 public void onServiceDisconnected(ComponentName name) { 1069 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1070 } 1071 } 1072 1073 // Recordkeeping of restore-after-install operations that are currently in flight 1074 // between the Package Manager and the Backup Manager 1075 static class PostInstallData { 1076 public InstallArgs args; 1077 public PackageInstalledInfo res; 1078 1079 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1080 args = _a; 1081 res = _r; 1082 } 1083 } 1084 1085 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1086 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1087 1088 // XML tags for backup/restore of various bits of state 1089 private static final String TAG_PREFERRED_BACKUP = "pa"; 1090 private static final String TAG_DEFAULT_APPS = "da"; 1091 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1092 1093 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1094 private static final String TAG_ALL_GRANTS = "rt-grants"; 1095 private static final String TAG_GRANT = "grant"; 1096 private static final String ATTR_PACKAGE_NAME = "pkg"; 1097 1098 private static final String TAG_PERMISSION = "perm"; 1099 private static final String ATTR_PERMISSION_NAME = "name"; 1100 private static final String ATTR_IS_GRANTED = "g"; 1101 private static final String ATTR_USER_SET = "set"; 1102 private static final String ATTR_USER_FIXED = "fixed"; 1103 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1104 1105 // System/policy permission grants are not backed up 1106 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1107 FLAG_PERMISSION_POLICY_FIXED 1108 | FLAG_PERMISSION_SYSTEM_FIXED 1109 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1110 1111 // And we back up these user-adjusted states 1112 private static final int USER_RUNTIME_GRANT_MASK = 1113 FLAG_PERMISSION_USER_SET 1114 | FLAG_PERMISSION_USER_FIXED 1115 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1116 1117 final @Nullable String mRequiredVerifierPackage; 1118 final @NonNull String mRequiredInstallerPackage; 1119 final @Nullable String mSetupWizardPackage; 1120 final @NonNull String mServicesSystemSharedLibraryPackageName; 1121 final @NonNull String mSharedSystemSharedLibraryPackageName; 1122 1123 private final PackageUsage mPackageUsage = new PackageUsage(); 1124 1125 private class PackageUsage { 1126 private static final int WRITE_INTERVAL 1127 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1128 1129 private final Object mFileLock = new Object(); 1130 private final AtomicLong mLastWritten = new AtomicLong(0); 1131 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1132 1133 private boolean mIsHistoricalPackageUsageAvailable = true; 1134 1135 boolean isHistoricalPackageUsageAvailable() { 1136 return mIsHistoricalPackageUsageAvailable; 1137 } 1138 1139 void write(boolean force) { 1140 if (force) { 1141 writeInternal(); 1142 return; 1143 } 1144 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1145 && !DEBUG_DEXOPT) { 1146 return; 1147 } 1148 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1149 new Thread("PackageUsage_DiskWriter") { 1150 @Override 1151 public void run() { 1152 try { 1153 writeInternal(); 1154 } finally { 1155 mBackgroundWriteRunning.set(false); 1156 } 1157 } 1158 }.start(); 1159 } 1160 } 1161 1162 private void writeInternal() { 1163 synchronized (mPackages) { 1164 synchronized (mFileLock) { 1165 AtomicFile file = getFile(); 1166 FileOutputStream f = null; 1167 try { 1168 f = file.startWrite(); 1169 BufferedOutputStream out = new BufferedOutputStream(f); 1170 FileUtils.setPermissions(file.getBaseFile().getPath(), 1171 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1172 StringBuilder sb = new StringBuilder(); 1173 1174 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1175 sb.append('\n'); 1176 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1177 1178 for (PackageParser.Package pkg : mPackages.values()) { 1179 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1180 continue; 1181 } 1182 sb.setLength(0); 1183 sb.append(pkg.packageName); 1184 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1185 sb.append(' '); 1186 sb.append(usageTimeInMillis); 1187 } 1188 sb.append('\n'); 1189 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1190 } 1191 out.flush(); 1192 file.finishWrite(f); 1193 } catch (IOException e) { 1194 if (f != null) { 1195 file.failWrite(f); 1196 } 1197 Log.e(TAG, "Failed to write package usage times", e); 1198 } 1199 } 1200 } 1201 mLastWritten.set(SystemClock.elapsedRealtime()); 1202 } 1203 1204 void readLP() { 1205 synchronized (mFileLock) { 1206 AtomicFile file = getFile(); 1207 BufferedInputStream in = null; 1208 try { 1209 in = new BufferedInputStream(file.openRead()); 1210 StringBuffer sb = new StringBuffer(); 1211 1212 String firstLine = readLine(in, sb); 1213 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1214 readVersion1LP(in, sb); 1215 } else { 1216 readVersion0LP(in, sb, firstLine); 1217 } 1218 } catch (FileNotFoundException expected) { 1219 mIsHistoricalPackageUsageAvailable = false; 1220 } catch (IOException e) { 1221 Log.w(TAG, "Failed to read package usage times", e); 1222 } finally { 1223 IoUtils.closeQuietly(in); 1224 } 1225 } 1226 mLastWritten.set(SystemClock.elapsedRealtime()); 1227 } 1228 1229 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1230 throws IOException { 1231 // Initial version of the file had no version number and stored one 1232 // package-timestamp pair per line. 1233 // Note that the first line has already been read from the InputStream. 1234 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1235 String[] tokens = line.split(" "); 1236 if (tokens.length != 2) { 1237 throw new IOException("Failed to parse " + line + 1238 " as package-timestamp pair."); 1239 } 1240 1241 String packageName = tokens[0]; 1242 PackageParser.Package pkg = mPackages.get(packageName); 1243 if (pkg == null) { 1244 continue; 1245 } 1246 1247 long timestamp = parseAsLong(tokens[1]); 1248 for (int reason = 0; 1249 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1250 reason++) { 1251 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1252 } 1253 } 1254 } 1255 1256 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1257 // Version 1 of the file started with the corresponding version 1258 // number and then stored a package name and eight timestamps per line. 1259 String line; 1260 while ((line = readLine(in, sb)) != null) { 1261 String[] tokens = line.split(" "); 1262 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1263 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1264 } 1265 1266 String packageName = tokens[0]; 1267 PackageParser.Package pkg = mPackages.get(packageName); 1268 if (pkg == null) { 1269 continue; 1270 } 1271 1272 for (int reason = 0; 1273 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1274 reason++) { 1275 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1276 } 1277 } 1278 } 1279 1280 private long parseAsLong(String token) throws IOException { 1281 try { 1282 return Long.parseLong(token); 1283 } catch (NumberFormatException e) { 1284 throw new IOException("Failed to parse " + token + " as a long.", e); 1285 } 1286 } 1287 1288 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1289 return readToken(in, sb, '\n'); 1290 } 1291 1292 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1293 throws IOException { 1294 sb.setLength(0); 1295 while (true) { 1296 int ch = in.read(); 1297 if (ch == -1) { 1298 if (sb.length() == 0) { 1299 return null; 1300 } 1301 throw new IOException("Unexpected EOF"); 1302 } 1303 if (ch == endOfToken) { 1304 return sb.toString(); 1305 } 1306 sb.append((char)ch); 1307 } 1308 } 1309 1310 private AtomicFile getFile() { 1311 File dataDir = Environment.getDataDirectory(); 1312 File systemDir = new File(dataDir, "system"); 1313 File fname = new File(systemDir, "package-usage.list"); 1314 return new AtomicFile(fname); 1315 } 1316 1317 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1318 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1319 } 1320 1321 class PackageHandler extends Handler { 1322 private boolean mBound = false; 1323 final ArrayList<HandlerParams> mPendingInstalls = 1324 new ArrayList<HandlerParams>(); 1325 1326 private boolean connectToService() { 1327 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1328 " DefaultContainerService"); 1329 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1331 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1332 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1333 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1334 mBound = true; 1335 return true; 1336 } 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1338 return false; 1339 } 1340 1341 private void disconnectService() { 1342 mContainerService = null; 1343 mBound = false; 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1345 mContext.unbindService(mDefContainerConn); 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1347 } 1348 1349 PackageHandler(Looper looper) { 1350 super(looper); 1351 } 1352 1353 public void handleMessage(Message msg) { 1354 try { 1355 doHandleMessage(msg); 1356 } finally { 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 } 1359 } 1360 1361 void doHandleMessage(Message msg) { 1362 switch (msg.what) { 1363 case INIT_COPY: { 1364 HandlerParams params = (HandlerParams) msg.obj; 1365 int idx = mPendingInstalls.size(); 1366 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1367 // If a bind was already initiated we dont really 1368 // need to do anything. The pending install 1369 // will be processed later on. 1370 if (!mBound) { 1371 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1372 System.identityHashCode(mHandler)); 1373 // If this is the only one pending we might 1374 // have to bind to the service again. 1375 if (!connectToService()) { 1376 Slog.e(TAG, "Failed to bind to media container service"); 1377 params.serviceError(); 1378 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1379 System.identityHashCode(mHandler)); 1380 if (params.traceMethod != null) { 1381 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1382 params.traceCookie); 1383 } 1384 return; 1385 } else { 1386 // Once we bind to the service, the first 1387 // pending request will be processed. 1388 mPendingInstalls.add(idx, params); 1389 } 1390 } else { 1391 mPendingInstalls.add(idx, params); 1392 // Already bound to the service. Just make 1393 // sure we trigger off processing the first request. 1394 if (idx == 0) { 1395 mHandler.sendEmptyMessage(MCS_BOUND); 1396 } 1397 } 1398 break; 1399 } 1400 case MCS_BOUND: { 1401 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1402 if (msg.obj != null) { 1403 mContainerService = (IMediaContainerService) msg.obj; 1404 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1405 System.identityHashCode(mHandler)); 1406 } 1407 if (mContainerService == null) { 1408 if (!mBound) { 1409 // Something seriously wrong since we are not bound and we are not 1410 // waiting for connection. Bail out. 1411 Slog.e(TAG, "Cannot bind to media container service"); 1412 for (HandlerParams params : mPendingInstalls) { 1413 // Indicate service bind error 1414 params.serviceError(); 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1416 System.identityHashCode(params)); 1417 if (params.traceMethod != null) { 1418 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1419 params.traceMethod, params.traceCookie); 1420 } 1421 return; 1422 } 1423 mPendingInstalls.clear(); 1424 } else { 1425 Slog.w(TAG, "Waiting to connect to media container service"); 1426 } 1427 } else if (mPendingInstalls.size() > 0) { 1428 HandlerParams params = mPendingInstalls.get(0); 1429 if (params != null) { 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1431 System.identityHashCode(params)); 1432 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1433 if (params.startCopy()) { 1434 // We are done... look for more work or to 1435 // go idle. 1436 if (DEBUG_SD_INSTALL) Log.i(TAG, 1437 "Checking for more work or unbind..."); 1438 // Delete pending install 1439 if (mPendingInstalls.size() > 0) { 1440 mPendingInstalls.remove(0); 1441 } 1442 if (mPendingInstalls.size() == 0) { 1443 if (mBound) { 1444 if (DEBUG_SD_INSTALL) Log.i(TAG, 1445 "Posting delayed MCS_UNBIND"); 1446 removeMessages(MCS_UNBIND); 1447 Message ubmsg = obtainMessage(MCS_UNBIND); 1448 // Unbind after a little delay, to avoid 1449 // continual thrashing. 1450 sendMessageDelayed(ubmsg, 10000); 1451 } 1452 } else { 1453 // There are more pending requests in queue. 1454 // Just post MCS_BOUND message to trigger processing 1455 // of next pending install. 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, 1457 "Posting MCS_BOUND for next work"); 1458 mHandler.sendEmptyMessage(MCS_BOUND); 1459 } 1460 } 1461 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1462 } 1463 } else { 1464 // Should never happen ideally. 1465 Slog.w(TAG, "Empty queue"); 1466 } 1467 break; 1468 } 1469 case MCS_RECONNECT: { 1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1471 if (mPendingInstalls.size() > 0) { 1472 if (mBound) { 1473 disconnectService(); 1474 } 1475 if (!connectToService()) { 1476 Slog.e(TAG, "Failed to bind to media container service"); 1477 for (HandlerParams params : mPendingInstalls) { 1478 // Indicate service bind error 1479 params.serviceError(); 1480 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1481 System.identityHashCode(params)); 1482 } 1483 mPendingInstalls.clear(); 1484 } 1485 } 1486 break; 1487 } 1488 case MCS_UNBIND: { 1489 // If there is no actual work left, then time to unbind. 1490 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1491 1492 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1493 if (mBound) { 1494 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1495 1496 disconnectService(); 1497 } 1498 } else if (mPendingInstalls.size() > 0) { 1499 // There are more pending requests in queue. 1500 // Just post MCS_BOUND message to trigger processing 1501 // of next pending install. 1502 mHandler.sendEmptyMessage(MCS_BOUND); 1503 } 1504 1505 break; 1506 } 1507 case MCS_GIVE_UP: { 1508 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1509 HandlerParams params = mPendingInstalls.remove(0); 1510 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1511 System.identityHashCode(params)); 1512 break; 1513 } 1514 case SEND_PENDING_BROADCAST: { 1515 String packages[]; 1516 ArrayList<String> components[]; 1517 int size = 0; 1518 int uids[]; 1519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1520 synchronized (mPackages) { 1521 if (mPendingBroadcasts == null) { 1522 return; 1523 } 1524 size = mPendingBroadcasts.size(); 1525 if (size <= 0) { 1526 // Nothing to be done. Just return 1527 return; 1528 } 1529 packages = new String[size]; 1530 components = new ArrayList[size]; 1531 uids = new int[size]; 1532 int i = 0; // filling out the above arrays 1533 1534 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1535 int packageUserId = mPendingBroadcasts.userIdAt(n); 1536 Iterator<Map.Entry<String, ArrayList<String>>> it 1537 = mPendingBroadcasts.packagesForUserId(packageUserId) 1538 .entrySet().iterator(); 1539 while (it.hasNext() && i < size) { 1540 Map.Entry<String, ArrayList<String>> ent = it.next(); 1541 packages[i] = ent.getKey(); 1542 components[i] = ent.getValue(); 1543 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1544 uids[i] = (ps != null) 1545 ? UserHandle.getUid(packageUserId, ps.appId) 1546 : -1; 1547 i++; 1548 } 1549 } 1550 size = i; 1551 mPendingBroadcasts.clear(); 1552 } 1553 // Send broadcasts 1554 for (int i = 0; i < size; i++) { 1555 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1556 } 1557 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1558 break; 1559 } 1560 case START_CLEANING_PACKAGE: { 1561 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1562 final String packageName = (String)msg.obj; 1563 final int userId = msg.arg1; 1564 final boolean andCode = msg.arg2 != 0; 1565 synchronized (mPackages) { 1566 if (userId == UserHandle.USER_ALL) { 1567 int[] users = sUserManager.getUserIds(); 1568 for (int user : users) { 1569 mSettings.addPackageToCleanLPw( 1570 new PackageCleanItem(user, packageName, andCode)); 1571 } 1572 } else { 1573 mSettings.addPackageToCleanLPw( 1574 new PackageCleanItem(userId, packageName, andCode)); 1575 } 1576 } 1577 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1578 startCleaningPackages(); 1579 } break; 1580 case POST_INSTALL: { 1581 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1582 1583 PostInstallData data = mRunningInstalls.get(msg.arg1); 1584 final boolean didRestore = (msg.arg2 != 0); 1585 mRunningInstalls.delete(msg.arg1); 1586 1587 if (data != null) { 1588 InstallArgs args = data.args; 1589 PackageInstalledInfo parentRes = data.res; 1590 1591 final boolean grantPermissions = (args.installFlags 1592 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1593 final boolean killApp = (args.installFlags 1594 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1595 final String[] grantedPermissions = args.installGrantPermissions; 1596 1597 // Handle the parent package 1598 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1599 grantedPermissions, didRestore, args.installerPackageName, 1600 args.observer); 1601 1602 // Handle the child packages 1603 final int childCount = (parentRes.addedChildPackages != null) 1604 ? parentRes.addedChildPackages.size() : 0; 1605 for (int i = 0; i < childCount; i++) { 1606 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1607 handlePackagePostInstall(childRes, grantPermissions, killApp, 1608 grantedPermissions, false, args.installerPackageName, 1609 args.observer); 1610 } 1611 1612 // Log tracing if needed 1613 if (args.traceMethod != null) { 1614 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1615 args.traceCookie); 1616 } 1617 } else { 1618 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1619 } 1620 1621 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1622 } break; 1623 case UPDATED_MEDIA_STATUS: { 1624 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1625 boolean reportStatus = msg.arg1 == 1; 1626 boolean doGc = msg.arg2 == 1; 1627 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1628 if (doGc) { 1629 // Force a gc to clear up stale containers. 1630 Runtime.getRuntime().gc(); 1631 } 1632 if (msg.obj != null) { 1633 @SuppressWarnings("unchecked") 1634 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1635 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1636 // Unload containers 1637 unloadAllContainers(args); 1638 } 1639 if (reportStatus) { 1640 try { 1641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1642 PackageHelper.getMountService().finishMediaUpdate(); 1643 } catch (RemoteException e) { 1644 Log.e(TAG, "MountService not running?"); 1645 } 1646 } 1647 } break; 1648 case WRITE_SETTINGS: { 1649 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1650 synchronized (mPackages) { 1651 removeMessages(WRITE_SETTINGS); 1652 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1653 mSettings.writeLPr(); 1654 mDirtyUsers.clear(); 1655 } 1656 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1657 } break; 1658 case WRITE_PACKAGE_RESTRICTIONS: { 1659 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1660 synchronized (mPackages) { 1661 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1662 for (int userId : mDirtyUsers) { 1663 mSettings.writePackageRestrictionsLPr(userId); 1664 } 1665 mDirtyUsers.clear(); 1666 } 1667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1668 } break; 1669 case CHECK_PENDING_VERIFICATION: { 1670 final int verificationId = msg.arg1; 1671 final PackageVerificationState state = mPendingVerification.get(verificationId); 1672 1673 if ((state != null) && !state.timeoutExtended()) { 1674 final InstallArgs args = state.getInstallArgs(); 1675 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1676 1677 Slog.i(TAG, "Verification timed out for " + originUri); 1678 mPendingVerification.remove(verificationId); 1679 1680 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1681 1682 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1683 Slog.i(TAG, "Continuing with installation of " + originUri); 1684 state.setVerifierResponse(Binder.getCallingUid(), 1685 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1686 broadcastPackageVerified(verificationId, originUri, 1687 PackageManager.VERIFICATION_ALLOW, 1688 state.getInstallArgs().getUser()); 1689 try { 1690 ret = args.copyApk(mContainerService, true); 1691 } catch (RemoteException e) { 1692 Slog.e(TAG, "Could not contact the ContainerService"); 1693 } 1694 } else { 1695 broadcastPackageVerified(verificationId, originUri, 1696 PackageManager.VERIFICATION_REJECT, 1697 state.getInstallArgs().getUser()); 1698 } 1699 1700 Trace.asyncTraceEnd( 1701 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1702 1703 processPendingInstall(args, ret); 1704 mHandler.sendEmptyMessage(MCS_UNBIND); 1705 } 1706 break; 1707 } 1708 case PACKAGE_VERIFIED: { 1709 final int verificationId = msg.arg1; 1710 1711 final PackageVerificationState state = mPendingVerification.get(verificationId); 1712 if (state == null) { 1713 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1714 break; 1715 } 1716 1717 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1718 1719 state.setVerifierResponse(response.callerUid, response.code); 1720 1721 if (state.isVerificationComplete()) { 1722 mPendingVerification.remove(verificationId); 1723 1724 final InstallArgs args = state.getInstallArgs(); 1725 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1726 1727 int ret; 1728 if (state.isInstallAllowed()) { 1729 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1730 broadcastPackageVerified(verificationId, originUri, 1731 response.code, state.getInstallArgs().getUser()); 1732 try { 1733 ret = args.copyApk(mContainerService, true); 1734 } catch (RemoteException e) { 1735 Slog.e(TAG, "Could not contact the ContainerService"); 1736 } 1737 } else { 1738 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1739 } 1740 1741 Trace.asyncTraceEnd( 1742 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1743 1744 processPendingInstall(args, ret); 1745 mHandler.sendEmptyMessage(MCS_UNBIND); 1746 } 1747 1748 break; 1749 } 1750 case START_INTENT_FILTER_VERIFICATIONS: { 1751 IFVerificationParams params = (IFVerificationParams) msg.obj; 1752 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1753 params.replacing, params.pkg); 1754 break; 1755 } 1756 case INTENT_FILTER_VERIFIED: { 1757 final int verificationId = msg.arg1; 1758 1759 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1760 verificationId); 1761 if (state == null) { 1762 Slog.w(TAG, "Invalid IntentFilter verification token " 1763 + verificationId + " received"); 1764 break; 1765 } 1766 1767 final int userId = state.getUserId(); 1768 1769 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1770 "Processing IntentFilter verification with token:" 1771 + verificationId + " and userId:" + userId); 1772 1773 final IntentFilterVerificationResponse response = 1774 (IntentFilterVerificationResponse) msg.obj; 1775 1776 state.setVerifierResponse(response.callerUid, response.code); 1777 1778 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1779 "IntentFilter verification with token:" + verificationId 1780 + " and userId:" + userId 1781 + " is settings verifier response with response code:" 1782 + response.code); 1783 1784 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1786 + response.getFailedDomainsString()); 1787 } 1788 1789 if (state.isVerificationComplete()) { 1790 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1791 } else { 1792 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1793 "IntentFilter verification with token:" + verificationId 1794 + " was not said to be complete"); 1795 } 1796 1797 break; 1798 } 1799 } 1800 } 1801 } 1802 1803 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1804 boolean killApp, String[] grantedPermissions, 1805 boolean launchedForRestore, String installerPackage, 1806 IPackageInstallObserver2 installObserver) { 1807 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1808 // Send the removed broadcasts 1809 if (res.removedInfo != null) { 1810 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1811 } 1812 1813 // Now that we successfully installed the package, grant runtime 1814 // permissions if requested before broadcasting the install. 1815 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1816 >= Build.VERSION_CODES.M) { 1817 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1818 } 1819 1820 final boolean update = res.removedInfo != null 1821 && res.removedInfo.removedPackage != null; 1822 1823 // If this is the first time we have child packages for a disabled privileged 1824 // app that had no children, we grant requested runtime permissions to the new 1825 // children if the parent on the system image had them already granted. 1826 if (res.pkg.parentPackage != null) { 1827 synchronized (mPackages) { 1828 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1829 } 1830 } 1831 1832 synchronized (mPackages) { 1833 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1834 } 1835 1836 final String packageName = res.pkg.applicationInfo.packageName; 1837 Bundle extras = new Bundle(1); 1838 extras.putInt(Intent.EXTRA_UID, res.uid); 1839 1840 // Determine the set of users who are adding this package for 1841 // the first time vs. those who are seeing an update. 1842 int[] firstUsers = EMPTY_INT_ARRAY; 1843 int[] updateUsers = EMPTY_INT_ARRAY; 1844 if (res.origUsers == null || res.origUsers.length == 0) { 1845 firstUsers = res.newUsers; 1846 } else { 1847 for (int newUser : res.newUsers) { 1848 boolean isNew = true; 1849 for (int origUser : res.origUsers) { 1850 if (origUser == newUser) { 1851 isNew = false; 1852 break; 1853 } 1854 } 1855 if (isNew) { 1856 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1857 } else { 1858 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1859 } 1860 } 1861 } 1862 1863 // Send installed broadcasts if the install/update is not ephemeral 1864 if (!isEphemeral(res.pkg)) { 1865 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1866 1867 // Send added for users that see the package for the first time 1868 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1869 extras, 0 /*flags*/, null /*targetPackage*/, 1870 null /*finishedReceiver*/, firstUsers); 1871 1872 // Send added for users that don't see the package for the first time 1873 if (update) { 1874 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1875 } 1876 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1877 extras, 0 /*flags*/, null /*targetPackage*/, 1878 null /*finishedReceiver*/, updateUsers); 1879 1880 // Send replaced for users that don't see the package for the first time 1881 if (update) { 1882 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1883 packageName, extras, 0 /*flags*/, 1884 null /*targetPackage*/, null /*finishedReceiver*/, 1885 updateUsers); 1886 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1887 null /*package*/, null /*extras*/, 0 /*flags*/, 1888 packageName /*targetPackage*/, 1889 null /*finishedReceiver*/, updateUsers); 1890 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1891 // First-install and we did a restore, so we're responsible for the 1892 // first-launch broadcast. 1893 if (DEBUG_BACKUP) { 1894 Slog.i(TAG, "Post-restore of " + packageName 1895 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1896 } 1897 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1898 } 1899 1900 // Send broadcast package appeared if forward locked/external for all users 1901 // treat asec-hosted packages like removable media on upgrade 1902 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1903 if (DEBUG_INSTALL) { 1904 Slog.i(TAG, "upgrading pkg " + res.pkg 1905 + " is ASEC-hosted -> AVAILABLE"); 1906 } 1907 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1908 ArrayList<String> pkgList = new ArrayList<>(1); 1909 pkgList.add(packageName); 1910 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1911 } 1912 } 1913 1914 // Work that needs to happen on first install within each user 1915 if (firstUsers != null && firstUsers.length > 0) { 1916 synchronized (mPackages) { 1917 for (int userId : firstUsers) { 1918 // If this app is a browser and it's newly-installed for some 1919 // users, clear any default-browser state in those users. The 1920 // app's nature doesn't depend on the user, so we can just check 1921 // its browser nature in any user and generalize. 1922 if (packageIsBrowser(packageName, userId)) { 1923 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1924 } 1925 1926 // We may also need to apply pending (restored) runtime 1927 // permission grants within these users. 1928 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1929 } 1930 } 1931 } 1932 1933 // Log current value of "unknown sources" setting 1934 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1935 getUnknownSourcesSettings()); 1936 1937 // Force a gc to clear up things 1938 Runtime.getRuntime().gc(); 1939 1940 // Remove the replaced package's older resources safely now 1941 // We delete after a gc for applications on sdcard. 1942 if (res.removedInfo != null && res.removedInfo.args != null) { 1943 synchronized (mInstallLock) { 1944 res.removedInfo.args.doPostDeleteLI(true); 1945 } 1946 } 1947 } 1948 1949 // If someone is watching installs - notify them 1950 if (installObserver != null) { 1951 try { 1952 Bundle extras = extrasForInstallResult(res); 1953 installObserver.onPackageInstalled(res.name, res.returnCode, 1954 res.returnMsg, extras); 1955 } catch (RemoteException e) { 1956 Slog.i(TAG, "Observer no longer exists."); 1957 } 1958 } 1959 } 1960 1961 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1962 PackageParser.Package pkg) { 1963 if (pkg.parentPackage == null) { 1964 return; 1965 } 1966 if (pkg.requestedPermissions == null) { 1967 return; 1968 } 1969 final PackageSetting disabledSysParentPs = mSettings 1970 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1971 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1972 || !disabledSysParentPs.isPrivileged() 1973 || (disabledSysParentPs.childPackageNames != null 1974 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1975 return; 1976 } 1977 final int[] allUserIds = sUserManager.getUserIds(); 1978 final int permCount = pkg.requestedPermissions.size(); 1979 for (int i = 0; i < permCount; i++) { 1980 String permission = pkg.requestedPermissions.get(i); 1981 BasePermission bp = mSettings.mPermissions.get(permission); 1982 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1983 continue; 1984 } 1985 for (int userId : allUserIds) { 1986 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1987 permission, userId)) { 1988 grantRuntimePermission(pkg.packageName, permission, userId); 1989 } 1990 } 1991 } 1992 } 1993 1994 private StorageEventListener mStorageListener = new StorageEventListener() { 1995 @Override 1996 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1997 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1998 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1999 final String volumeUuid = vol.getFsUuid(); 2000 2001 // Clean up any users or apps that were removed or recreated 2002 // while this volume was missing 2003 reconcileUsers(volumeUuid); 2004 reconcileApps(volumeUuid); 2005 2006 // Clean up any install sessions that expired or were 2007 // cancelled while this volume was missing 2008 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2009 2010 loadPrivatePackages(vol); 2011 2012 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2013 unloadPrivatePackages(vol); 2014 } 2015 } 2016 2017 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2018 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2019 updateExternalMediaStatus(true, false); 2020 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2021 updateExternalMediaStatus(false, false); 2022 } 2023 } 2024 } 2025 2026 @Override 2027 public void onVolumeForgotten(String fsUuid) { 2028 if (TextUtils.isEmpty(fsUuid)) { 2029 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2030 return; 2031 } 2032 2033 // Remove any apps installed on the forgotten volume 2034 synchronized (mPackages) { 2035 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2036 for (PackageSetting ps : packages) { 2037 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2038 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2039 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2040 } 2041 2042 mSettings.onVolumeForgotten(fsUuid); 2043 mSettings.writeLPr(); 2044 } 2045 } 2046 }; 2047 2048 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2049 String[] grantedPermissions) { 2050 for (int userId : userIds) { 2051 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2052 } 2053 2054 // We could have touched GID membership, so flush out packages.list 2055 synchronized (mPackages) { 2056 mSettings.writePackageListLPr(); 2057 } 2058 } 2059 2060 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2061 String[] grantedPermissions) { 2062 SettingBase sb = (SettingBase) pkg.mExtras; 2063 if (sb == null) { 2064 return; 2065 } 2066 2067 PermissionsState permissionsState = sb.getPermissionsState(); 2068 2069 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2070 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2071 2072 for (String permission : pkg.requestedPermissions) { 2073 final BasePermission bp; 2074 synchronized (mPackages) { 2075 bp = mSettings.mPermissions.get(permission); 2076 } 2077 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2078 && (grantedPermissions == null 2079 || ArrayUtils.contains(grantedPermissions, permission))) { 2080 final int flags = permissionsState.getPermissionFlags(permission, userId); 2081 // Installer cannot change immutable permissions. 2082 if ((flags & immutableFlags) == 0) { 2083 grantRuntimePermission(pkg.packageName, permission, userId); 2084 } 2085 } 2086 } 2087 } 2088 2089 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2090 Bundle extras = null; 2091 switch (res.returnCode) { 2092 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2093 extras = new Bundle(); 2094 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2095 res.origPermission); 2096 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2097 res.origPackage); 2098 break; 2099 } 2100 case PackageManager.INSTALL_SUCCEEDED: { 2101 extras = new Bundle(); 2102 extras.putBoolean(Intent.EXTRA_REPLACING, 2103 res.removedInfo != null && res.removedInfo.removedPackage != null); 2104 break; 2105 } 2106 } 2107 return extras; 2108 } 2109 2110 void scheduleWriteSettingsLocked() { 2111 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2112 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2113 } 2114 } 2115 2116 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2117 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2118 scheduleWritePackageRestrictionsLocked(userId); 2119 } 2120 2121 void scheduleWritePackageRestrictionsLocked(int userId) { 2122 final int[] userIds = (userId == UserHandle.USER_ALL) 2123 ? sUserManager.getUserIds() : new int[]{userId}; 2124 for (int nextUserId : userIds) { 2125 if (!sUserManager.exists(nextUserId)) return; 2126 mDirtyUsers.add(nextUserId); 2127 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2128 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2129 } 2130 } 2131 } 2132 2133 public static PackageManagerService main(Context context, Installer installer, 2134 boolean factoryTest, boolean onlyCore) { 2135 // Self-check for initial settings. 2136 PackageManagerServiceCompilerMapping.checkProperties(); 2137 2138 PackageManagerService m = new PackageManagerService(context, installer, 2139 factoryTest, onlyCore); 2140 m.enableSystemUserPackages(); 2141 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2142 // disabled after already being started. 2143 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2144 UserHandle.USER_SYSTEM); 2145 ServiceManager.addService("package", m); 2146 return m; 2147 } 2148 2149 private void enableSystemUserPackages() { 2150 if (!UserManager.isSplitSystemUser()) { 2151 return; 2152 } 2153 // For system user, enable apps based on the following conditions: 2154 // - app is whitelisted or belong to one of these groups: 2155 // -- system app which has no launcher icons 2156 // -- system app which has INTERACT_ACROSS_USERS permission 2157 // -- system IME app 2158 // - app is not in the blacklist 2159 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2160 Set<String> enableApps = new ArraySet<>(); 2161 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2162 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2163 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2164 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2165 enableApps.addAll(wlApps); 2166 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2167 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2168 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2169 enableApps.removeAll(blApps); 2170 Log.i(TAG, "Applications installed for system user: " + enableApps); 2171 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2172 UserHandle.SYSTEM); 2173 final int allAppsSize = allAps.size(); 2174 synchronized (mPackages) { 2175 for (int i = 0; i < allAppsSize; i++) { 2176 String pName = allAps.get(i); 2177 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2178 // Should not happen, but we shouldn't be failing if it does 2179 if (pkgSetting == null) { 2180 continue; 2181 } 2182 boolean install = enableApps.contains(pName); 2183 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2184 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2185 + " for system user"); 2186 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2187 } 2188 } 2189 } 2190 } 2191 2192 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2193 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2194 Context.DISPLAY_SERVICE); 2195 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2196 } 2197 2198 public PackageManagerService(Context context, Installer installer, 2199 boolean factoryTest, boolean onlyCore) { 2200 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2201 SystemClock.uptimeMillis()); 2202 2203 if (mSdkVersion <= 0) { 2204 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2205 } 2206 2207 mContext = context; 2208 mFactoryTest = factoryTest; 2209 mOnlyCore = onlyCore; 2210 mMetrics = new DisplayMetrics(); 2211 mSettings = new Settings(mPackages); 2212 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2213 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2214 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2215 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2216 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2217 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2218 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2219 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2220 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2221 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2222 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2223 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2224 2225 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2226 if (separateProcesses != null && separateProcesses.length() > 0) { 2227 if ("*".equals(separateProcesses)) { 2228 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2229 mSeparateProcesses = null; 2230 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2231 } else { 2232 mDefParseFlags = 0; 2233 mSeparateProcesses = separateProcesses.split(","); 2234 Slog.w(TAG, "Running with debug.separate_processes: " 2235 + separateProcesses); 2236 } 2237 } else { 2238 mDefParseFlags = 0; 2239 mSeparateProcesses = null; 2240 } 2241 2242 mInstaller = installer; 2243 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2244 "*dexopt*"); 2245 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2246 2247 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2248 FgThread.get().getLooper()); 2249 2250 getDefaultDisplayMetrics(context, mMetrics); 2251 2252 SystemConfig systemConfig = SystemConfig.getInstance(); 2253 mGlobalGids = systemConfig.getGlobalGids(); 2254 mSystemPermissions = systemConfig.getSystemPermissions(); 2255 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2256 2257 synchronized (mInstallLock) { 2258 // writer 2259 synchronized (mPackages) { 2260 mHandlerThread = new ServiceThread(TAG, 2261 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2262 mHandlerThread.start(); 2263 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2264 mProcessLoggingHandler = new ProcessLoggingHandler(); 2265 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2266 2267 File dataDir = Environment.getDataDirectory(); 2268 mAppInstallDir = new File(dataDir, "app"); 2269 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2270 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2271 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2272 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2273 2274 sUserManager = new UserManagerService(context, this, mPackages); 2275 2276 // Propagate permission configuration in to package manager. 2277 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2278 = systemConfig.getPermissions(); 2279 for (int i=0; i<permConfig.size(); i++) { 2280 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2281 BasePermission bp = mSettings.mPermissions.get(perm.name); 2282 if (bp == null) { 2283 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2284 mSettings.mPermissions.put(perm.name, bp); 2285 } 2286 if (perm.gids != null) { 2287 bp.setGids(perm.gids, perm.perUser); 2288 } 2289 } 2290 2291 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2292 for (int i=0; i<libConfig.size(); i++) { 2293 mSharedLibraries.put(libConfig.keyAt(i), 2294 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2295 } 2296 2297 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2298 2299 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2300 2301 String customResolverActivity = Resources.getSystem().getString( 2302 R.string.config_customResolverActivity); 2303 if (TextUtils.isEmpty(customResolverActivity)) { 2304 customResolverActivity = null; 2305 } else { 2306 mCustomResolverComponentName = ComponentName.unflattenFromString( 2307 customResolverActivity); 2308 } 2309 2310 long startTime = SystemClock.uptimeMillis(); 2311 2312 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2313 startTime); 2314 2315 // Set flag to monitor and not change apk file paths when 2316 // scanning install directories. 2317 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2318 2319 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2320 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2321 2322 if (bootClassPath == null) { 2323 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2324 } 2325 2326 if (systemServerClassPath == null) { 2327 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2328 } 2329 2330 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2331 final String[] dexCodeInstructionSets = 2332 getDexCodeInstructionSets( 2333 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2334 2335 /** 2336 * Ensure all external libraries have had dexopt run on them. 2337 */ 2338 if (mSharedLibraries.size() > 0) { 2339 // NOTE: For now, we're compiling these system "shared libraries" 2340 // (and framework jars) into all available architectures. It's possible 2341 // to compile them only when we come across an app that uses them (there's 2342 // already logic for that in scanPackageLI) but that adds some complexity. 2343 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2344 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2345 final String lib = libEntry.path; 2346 if (lib == null) { 2347 continue; 2348 } 2349 2350 try { 2351 // Shared libraries do not have profiles so we perform a full 2352 // AOT compilation (if needed). 2353 int dexoptNeeded = DexFile.getDexOptNeeded( 2354 lib, dexCodeInstructionSet, 2355 getCompilerFilterForReason(REASON_SHARED_APK), 2356 false /* newProfile */); 2357 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2358 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2359 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2360 getCompilerFilterForReason(REASON_SHARED_APK), 2361 StorageManager.UUID_PRIVATE_INTERNAL, 2362 SKIP_SHARED_LIBRARY_CHECK); 2363 } 2364 } catch (FileNotFoundException e) { 2365 Slog.w(TAG, "Library not found: " + lib); 2366 } catch (IOException | InstallerException e) { 2367 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2368 + e.getMessage()); 2369 } 2370 } 2371 } 2372 } 2373 2374 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2375 2376 final VersionInfo ver = mSettings.getInternalVersion(); 2377 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2378 2379 // when upgrading from pre-M, promote system app permissions from install to runtime 2380 mPromoteSystemApps = 2381 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2382 2383 // save off the names of pre-existing system packages prior to scanning; we don't 2384 // want to automatically grant runtime permissions for new system apps 2385 if (mPromoteSystemApps) { 2386 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2387 while (pkgSettingIter.hasNext()) { 2388 PackageSetting ps = pkgSettingIter.next(); 2389 if (isSystemApp(ps)) { 2390 mExistingSystemPackages.add(ps.name); 2391 } 2392 } 2393 } 2394 2395 // When upgrading from pre-N, we need to handle package extraction like first boot, 2396 // as there is no profiling data available. 2397 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2398 mSettings.setNWorkDone(); 2399 2400 // Collect vendor overlay packages. 2401 // (Do this before scanning any apps.) 2402 // For security and version matching reason, only consider 2403 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2404 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2405 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2406 | PackageParser.PARSE_IS_SYSTEM 2407 | PackageParser.PARSE_IS_SYSTEM_DIR 2408 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2409 2410 // Find base frameworks (resource packages without code). 2411 scanDirTracedLI(frameworkDir, mDefParseFlags 2412 | PackageParser.PARSE_IS_SYSTEM 2413 | PackageParser.PARSE_IS_SYSTEM_DIR 2414 | PackageParser.PARSE_IS_PRIVILEGED, 2415 scanFlags | SCAN_NO_DEX, 0); 2416 2417 // Collected privileged system packages. 2418 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2419 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2420 | PackageParser.PARSE_IS_SYSTEM 2421 | PackageParser.PARSE_IS_SYSTEM_DIR 2422 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2423 2424 // Collect ordinary system packages. 2425 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2426 scanDirTracedLI(systemAppDir, mDefParseFlags 2427 | PackageParser.PARSE_IS_SYSTEM 2428 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2429 2430 // Collect all vendor packages. 2431 File vendorAppDir = new File("/vendor/app"); 2432 try { 2433 vendorAppDir = vendorAppDir.getCanonicalFile(); 2434 } catch (IOException e) { 2435 // failed to look up canonical path, continue with original one 2436 } 2437 scanDirTracedLI(vendorAppDir, mDefParseFlags 2438 | PackageParser.PARSE_IS_SYSTEM 2439 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2440 2441 // Collect all OEM packages. 2442 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2443 scanDirTracedLI(oemAppDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2446 2447 // Prune any system packages that no longer exist. 2448 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2449 if (!mOnlyCore) { 2450 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2451 while (psit.hasNext()) { 2452 PackageSetting ps = psit.next(); 2453 2454 /* 2455 * If this is not a system app, it can't be a 2456 * disable system app. 2457 */ 2458 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2459 continue; 2460 } 2461 2462 /* 2463 * If the package is scanned, it's not erased. 2464 */ 2465 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2466 if (scannedPkg != null) { 2467 /* 2468 * If the system app is both scanned and in the 2469 * disabled packages list, then it must have been 2470 * added via OTA. Remove it from the currently 2471 * scanned package so the previously user-installed 2472 * application can be scanned. 2473 */ 2474 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2475 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2476 + ps.name + "; removing system app. Last known codePath=" 2477 + ps.codePathString + ", installStatus=" + ps.installStatus 2478 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2479 + scannedPkg.mVersionCode); 2480 removePackageLI(scannedPkg, true); 2481 mExpectingBetter.put(ps.name, ps.codePath); 2482 } 2483 2484 continue; 2485 } 2486 2487 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2488 psit.remove(); 2489 logCriticalInfo(Log.WARN, "System package " + ps.name 2490 + " no longer exists; it's data will be wiped"); 2491 // Actual deletion of code and data will be handled by later 2492 // reconciliation step 2493 } else { 2494 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2495 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2496 possiblyDeletedUpdatedSystemApps.add(ps.name); 2497 } 2498 } 2499 } 2500 } 2501 2502 //look for any incomplete package installations 2503 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2504 for (int i = 0; i < deletePkgsList.size(); i++) { 2505 // Actual deletion of code and data will be handled by later 2506 // reconciliation step 2507 final String packageName = deletePkgsList.get(i).name; 2508 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2509 synchronized (mPackages) { 2510 mSettings.removePackageLPw(packageName); 2511 } 2512 } 2513 2514 //delete tmp files 2515 deleteTempPackageFiles(); 2516 2517 // Remove any shared userIDs that have no associated packages 2518 mSettings.pruneSharedUsersLPw(); 2519 2520 if (!mOnlyCore) { 2521 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2522 SystemClock.uptimeMillis()); 2523 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2524 2525 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2526 | PackageParser.PARSE_FORWARD_LOCK, 2527 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2528 2529 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2530 | PackageParser.PARSE_IS_EPHEMERAL, 2531 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2532 2533 /** 2534 * Remove disable package settings for any updated system 2535 * apps that were removed via an OTA. If they're not a 2536 * previously-updated app, remove them completely. 2537 * Otherwise, just revoke their system-level permissions. 2538 */ 2539 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2540 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2541 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2542 2543 String msg; 2544 if (deletedPkg == null) { 2545 msg = "Updated system package " + deletedAppName 2546 + " no longer exists; it's data will be wiped"; 2547 // Actual deletion of code and data will be handled by later 2548 // reconciliation step 2549 } else { 2550 msg = "Updated system app + " + deletedAppName 2551 + " no longer present; removing system privileges for " 2552 + deletedAppName; 2553 2554 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2555 2556 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2557 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2558 } 2559 logCriticalInfo(Log.WARN, msg); 2560 } 2561 2562 /** 2563 * Make sure all system apps that we expected to appear on 2564 * the userdata partition actually showed up. If they never 2565 * appeared, crawl back and revive the system version. 2566 */ 2567 for (int i = 0; i < mExpectingBetter.size(); i++) { 2568 final String packageName = mExpectingBetter.keyAt(i); 2569 if (!mPackages.containsKey(packageName)) { 2570 final File scanFile = mExpectingBetter.valueAt(i); 2571 2572 logCriticalInfo(Log.WARN, "Expected better " + packageName 2573 + " but never showed up; reverting to system"); 2574 2575 int reparseFlags = mDefParseFlags; 2576 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2577 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2578 | PackageParser.PARSE_IS_SYSTEM_DIR 2579 | PackageParser.PARSE_IS_PRIVILEGED; 2580 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2581 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2582 | PackageParser.PARSE_IS_SYSTEM_DIR; 2583 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2584 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2585 | PackageParser.PARSE_IS_SYSTEM_DIR; 2586 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2587 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2588 | PackageParser.PARSE_IS_SYSTEM_DIR; 2589 } else { 2590 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2591 continue; 2592 } 2593 2594 mSettings.enableSystemPackageLPw(packageName); 2595 2596 try { 2597 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2598 } catch (PackageManagerException e) { 2599 Slog.e(TAG, "Failed to parse original system package: " 2600 + e.getMessage()); 2601 } 2602 } 2603 } 2604 } 2605 mExpectingBetter.clear(); 2606 2607 // Resolve protected action filters. Only the setup wizard is allowed to 2608 // have a high priority filter for these actions. 2609 mSetupWizardPackage = getSetupWizardPackageName(); 2610 if (mProtectedFilters.size() > 0) { 2611 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2612 Slog.i(TAG, "No setup wizard;" 2613 + " All protected intents capped to priority 0"); 2614 } 2615 for (ActivityIntentInfo filter : mProtectedFilters) { 2616 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2617 if (DEBUG_FILTERS) { 2618 Slog.i(TAG, "Found setup wizard;" 2619 + " allow priority " + filter.getPriority() + ";" 2620 + " package: " + filter.activity.info.packageName 2621 + " activity: " + filter.activity.className 2622 + " priority: " + filter.getPriority()); 2623 } 2624 // skip setup wizard; allow it to keep the high priority filter 2625 continue; 2626 } 2627 Slog.w(TAG, "Protected action; cap priority to 0;" 2628 + " package: " + filter.activity.info.packageName 2629 + " activity: " + filter.activity.className 2630 + " origPrio: " + filter.getPriority()); 2631 filter.setPriority(0); 2632 } 2633 } 2634 mDeferProtectedFilters = false; 2635 mProtectedFilters.clear(); 2636 2637 // Now that we know all of the shared libraries, update all clients to have 2638 // the correct library paths. 2639 updateAllSharedLibrariesLPw(); 2640 2641 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2642 // NOTE: We ignore potential failures here during a system scan (like 2643 // the rest of the commands above) because there's precious little we 2644 // can do about it. A settings error is reported, though. 2645 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2646 false /* boot complete */); 2647 } 2648 2649 // Now that we know all the packages we are keeping, 2650 // read and update their last usage times. 2651 mPackageUsage.readLP(); 2652 2653 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2654 SystemClock.uptimeMillis()); 2655 Slog.i(TAG, "Time to scan packages: " 2656 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2657 + " seconds"); 2658 2659 // If the platform SDK has changed since the last time we booted, 2660 // we need to re-grant app permission to catch any new ones that 2661 // appear. This is really a hack, and means that apps can in some 2662 // cases get permissions that the user didn't initially explicitly 2663 // allow... it would be nice to have some better way to handle 2664 // this situation. 2665 int updateFlags = UPDATE_PERMISSIONS_ALL; 2666 if (ver.sdkVersion != mSdkVersion) { 2667 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2668 + mSdkVersion + "; regranting permissions for internal storage"); 2669 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2670 } 2671 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2672 ver.sdkVersion = mSdkVersion; 2673 2674 // If this is the first boot or an update from pre-M, and it is a normal 2675 // boot, then we need to initialize the default preferred apps across 2676 // all defined users. 2677 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2678 for (UserInfo user : sUserManager.getUsers(true)) { 2679 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2680 applyFactoryDefaultBrowserLPw(user.id); 2681 primeDomainVerificationsLPw(user.id); 2682 } 2683 } 2684 2685 // Prepare storage for system user really early during boot, 2686 // since core system apps like SettingsProvider and SystemUI 2687 // can't wait for user to start 2688 final int storageFlags; 2689 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2690 storageFlags = StorageManager.FLAG_STORAGE_DE; 2691 } else { 2692 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2693 } 2694 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2695 storageFlags); 2696 2697 // If this is first boot after an OTA, and a normal boot, then 2698 // we need to clear code cache directories. 2699 if (mIsUpgrade && !onlyCore) { 2700 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2701 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2702 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2703 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2704 // No apps are running this early, so no need to freeze 2705 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2706 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2707 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2708 } 2709 clearAppProfilesLIF(ps.pkg); 2710 } 2711 ver.fingerprint = Build.FINGERPRINT; 2712 } 2713 2714 checkDefaultBrowser(); 2715 2716 // clear only after permissions and other defaults have been updated 2717 mExistingSystemPackages.clear(); 2718 mPromoteSystemApps = false; 2719 2720 // All the changes are done during package scanning. 2721 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2722 2723 // can downgrade to reader 2724 mSettings.writeLPr(); 2725 2726 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2727 SystemClock.uptimeMillis()); 2728 2729 if (!mOnlyCore) { 2730 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2731 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2732 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2733 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2734 mIntentFilterVerifierComponent); 2735 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2736 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2737 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2738 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2739 } else { 2740 mRequiredVerifierPackage = null; 2741 mRequiredInstallerPackage = null; 2742 mIntentFilterVerifierComponent = null; 2743 mIntentFilterVerifier = null; 2744 mServicesSystemSharedLibraryPackageName = null; 2745 mSharedSystemSharedLibraryPackageName = null; 2746 } 2747 2748 mInstallerService = new PackageInstallerService(context, this); 2749 2750 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2751 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2752 // both the installer and resolver must be present to enable ephemeral 2753 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2754 if (DEBUG_EPHEMERAL) { 2755 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2756 + " installer:" + ephemeralInstallerComponent); 2757 } 2758 mEphemeralResolverComponent = ephemeralResolverComponent; 2759 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2760 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2761 mEphemeralResolverConnection = 2762 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2763 } else { 2764 if (DEBUG_EPHEMERAL) { 2765 final String missingComponent = 2766 (ephemeralResolverComponent == null) 2767 ? (ephemeralInstallerComponent == null) 2768 ? "resolver and installer" 2769 : "resolver" 2770 : "installer"; 2771 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2772 } 2773 mEphemeralResolverComponent = null; 2774 mEphemeralInstallerComponent = null; 2775 mEphemeralResolverConnection = null; 2776 } 2777 2778 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2779 } // synchronized (mPackages) 2780 } // synchronized (mInstallLock) 2781 2782 // Now after opening every single application zip, make sure they 2783 // are all flushed. Not really needed, but keeps things nice and 2784 // tidy. 2785 Runtime.getRuntime().gc(); 2786 2787 // The initial scanning above does many calls into installd while 2788 // holding the mPackages lock, but we're mostly interested in yelling 2789 // once we have a booted system. 2790 mInstaller.setWarnIfHeld(mPackages); 2791 2792 // Expose private service for system components to use. 2793 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2794 } 2795 2796 @Override 2797 public boolean isFirstBoot() { 2798 return !mRestoredSettings; 2799 } 2800 2801 @Override 2802 public boolean isOnlyCoreApps() { 2803 return mOnlyCore; 2804 } 2805 2806 @Override 2807 public boolean isUpgrade() { 2808 return mIsUpgrade; 2809 } 2810 2811 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2812 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2813 2814 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2815 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2816 UserHandle.USER_SYSTEM); 2817 if (matches.size() == 1) { 2818 return matches.get(0).getComponentInfo().packageName; 2819 } else { 2820 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2821 return null; 2822 } 2823 } 2824 2825 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2826 synchronized (mPackages) { 2827 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2828 if (libraryEntry == null) { 2829 throw new IllegalStateException("Missing required shared library:" + libraryName); 2830 } 2831 return libraryEntry.apk; 2832 } 2833 } 2834 2835 private @NonNull String getRequiredInstallerLPr() { 2836 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2837 intent.addCategory(Intent.CATEGORY_DEFAULT); 2838 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2839 2840 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2841 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2842 UserHandle.USER_SYSTEM); 2843 if (matches.size() == 1) { 2844 ResolveInfo resolveInfo = matches.get(0); 2845 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2846 throw new RuntimeException("The installer must be a privileged app"); 2847 } 2848 return matches.get(0).getComponentInfo().packageName; 2849 } else { 2850 throw new RuntimeException("There must be exactly one installer; found " + matches); 2851 } 2852 } 2853 2854 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2855 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2856 2857 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2858 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2859 UserHandle.USER_SYSTEM); 2860 ResolveInfo best = null; 2861 final int N = matches.size(); 2862 for (int i = 0; i < N; i++) { 2863 final ResolveInfo cur = matches.get(i); 2864 final String packageName = cur.getComponentInfo().packageName; 2865 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2866 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2867 continue; 2868 } 2869 2870 if (best == null || cur.priority > best.priority) { 2871 best = cur; 2872 } 2873 } 2874 2875 if (best != null) { 2876 return best.getComponentInfo().getComponentName(); 2877 } else { 2878 throw new RuntimeException("There must be at least one intent filter verifier"); 2879 } 2880 } 2881 2882 private @Nullable ComponentName getEphemeralResolverLPr() { 2883 final String[] packageArray = 2884 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2885 if (packageArray.length == 0) { 2886 if (DEBUG_EPHEMERAL) { 2887 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2888 } 2889 return null; 2890 } 2891 2892 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2893 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2894 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2895 UserHandle.USER_SYSTEM); 2896 2897 final int N = resolvers.size(); 2898 if (N == 0) { 2899 if (DEBUG_EPHEMERAL) { 2900 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2901 } 2902 return null; 2903 } 2904 2905 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2906 for (int i = 0; i < N; i++) { 2907 final ResolveInfo info = resolvers.get(i); 2908 2909 if (info.serviceInfo == null) { 2910 continue; 2911 } 2912 2913 final String packageName = info.serviceInfo.packageName; 2914 if (!possiblePackages.contains(packageName)) { 2915 if (DEBUG_EPHEMERAL) { 2916 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2917 + " pkg: " + packageName + ", info:" + info); 2918 } 2919 continue; 2920 } 2921 2922 if (DEBUG_EPHEMERAL) { 2923 Slog.v(TAG, "Ephemeral resolver found;" 2924 + " pkg: " + packageName + ", info:" + info); 2925 } 2926 return new ComponentName(packageName, info.serviceInfo.name); 2927 } 2928 if (DEBUG_EPHEMERAL) { 2929 Slog.v(TAG, "Ephemeral resolver NOT found"); 2930 } 2931 return null; 2932 } 2933 2934 private @Nullable ComponentName getEphemeralInstallerLPr() { 2935 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2936 intent.addCategory(Intent.CATEGORY_DEFAULT); 2937 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2938 2939 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2940 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2941 UserHandle.USER_SYSTEM); 2942 if (matches.size() == 0) { 2943 return null; 2944 } else if (matches.size() == 1) { 2945 return matches.get(0).getComponentInfo().getComponentName(); 2946 } else { 2947 throw new RuntimeException( 2948 "There must be at most one ephemeral installer; found " + matches); 2949 } 2950 } 2951 2952 private void primeDomainVerificationsLPw(int userId) { 2953 if (DEBUG_DOMAIN_VERIFICATION) { 2954 Slog.d(TAG, "Priming domain verifications in user " + userId); 2955 } 2956 2957 SystemConfig systemConfig = SystemConfig.getInstance(); 2958 ArraySet<String> packages = systemConfig.getLinkedApps(); 2959 ArraySet<String> domains = new ArraySet<String>(); 2960 2961 for (String packageName : packages) { 2962 PackageParser.Package pkg = mPackages.get(packageName); 2963 if (pkg != null) { 2964 if (!pkg.isSystemApp()) { 2965 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2966 continue; 2967 } 2968 2969 domains.clear(); 2970 for (PackageParser.Activity a : pkg.activities) { 2971 for (ActivityIntentInfo filter : a.intents) { 2972 if (hasValidDomains(filter)) { 2973 domains.addAll(filter.getHostsList()); 2974 } 2975 } 2976 } 2977 2978 if (domains.size() > 0) { 2979 if (DEBUG_DOMAIN_VERIFICATION) { 2980 Slog.v(TAG, " + " + packageName); 2981 } 2982 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2983 // state w.r.t. the formal app-linkage "no verification attempted" state; 2984 // and then 'always' in the per-user state actually used for intent resolution. 2985 final IntentFilterVerificationInfo ivi; 2986 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2987 new ArrayList<String>(domains)); 2988 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2989 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2990 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2991 } else { 2992 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2993 + "' does not handle web links"); 2994 } 2995 } else { 2996 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2997 } 2998 } 2999 3000 scheduleWritePackageRestrictionsLocked(userId); 3001 scheduleWriteSettingsLocked(); 3002 } 3003 3004 private void applyFactoryDefaultBrowserLPw(int userId) { 3005 // The default browser app's package name is stored in a string resource, 3006 // with a product-specific overlay used for vendor customization. 3007 String browserPkg = mContext.getResources().getString( 3008 com.android.internal.R.string.default_browser); 3009 if (!TextUtils.isEmpty(browserPkg)) { 3010 // non-empty string => required to be a known package 3011 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3012 if (ps == null) { 3013 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3014 browserPkg = null; 3015 } else { 3016 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3017 } 3018 } 3019 3020 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3021 // default. If there's more than one, just leave everything alone. 3022 if (browserPkg == null) { 3023 calculateDefaultBrowserLPw(userId); 3024 } 3025 } 3026 3027 private void calculateDefaultBrowserLPw(int userId) { 3028 List<String> allBrowsers = resolveAllBrowserApps(userId); 3029 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3030 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3031 } 3032 3033 private List<String> resolveAllBrowserApps(int userId) { 3034 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3035 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3036 PackageManager.MATCH_ALL, userId); 3037 3038 final int count = list.size(); 3039 List<String> result = new ArrayList<String>(count); 3040 for (int i=0; i<count; i++) { 3041 ResolveInfo info = list.get(i); 3042 if (info.activityInfo == null 3043 || !info.handleAllWebDataURI 3044 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3045 || result.contains(info.activityInfo.packageName)) { 3046 continue; 3047 } 3048 result.add(info.activityInfo.packageName); 3049 } 3050 3051 return result; 3052 } 3053 3054 private boolean packageIsBrowser(String packageName, int userId) { 3055 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3056 PackageManager.MATCH_ALL, userId); 3057 final int N = list.size(); 3058 for (int i = 0; i < N; i++) { 3059 ResolveInfo info = list.get(i); 3060 if (packageName.equals(info.activityInfo.packageName)) { 3061 return true; 3062 } 3063 } 3064 return false; 3065 } 3066 3067 private void checkDefaultBrowser() { 3068 final int myUserId = UserHandle.myUserId(); 3069 final String packageName = getDefaultBrowserPackageName(myUserId); 3070 if (packageName != null) { 3071 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3072 if (info == null) { 3073 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3074 synchronized (mPackages) { 3075 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3076 } 3077 } 3078 } 3079 } 3080 3081 @Override 3082 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3083 throws RemoteException { 3084 try { 3085 return super.onTransact(code, data, reply, flags); 3086 } catch (RuntimeException e) { 3087 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3088 Slog.wtf(TAG, "Package Manager Crash", e); 3089 } 3090 throw e; 3091 } 3092 } 3093 3094 static int[] appendInts(int[] cur, int[] add) { 3095 if (add == null) return cur; 3096 if (cur == null) return add; 3097 final int N = add.length; 3098 for (int i=0; i<N; i++) { 3099 cur = appendInt(cur, add[i]); 3100 } 3101 return cur; 3102 } 3103 3104 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3105 if (!sUserManager.exists(userId)) return null; 3106 if (ps == null) { 3107 return null; 3108 } 3109 final PackageParser.Package p = ps.pkg; 3110 if (p == null) { 3111 return null; 3112 } 3113 3114 final PermissionsState permissionsState = ps.getPermissionsState(); 3115 3116 final int[] gids = permissionsState.computeGids(userId); 3117 final Set<String> permissions = permissionsState.getPermissions(userId); 3118 final PackageUserState state = ps.readUserState(userId); 3119 3120 return PackageParser.generatePackageInfo(p, gids, flags, 3121 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3122 } 3123 3124 @Override 3125 public void checkPackageStartable(String packageName, int userId) { 3126 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3127 3128 synchronized (mPackages) { 3129 final PackageSetting ps = mSettings.mPackages.get(packageName); 3130 if (ps == null) { 3131 throw new SecurityException("Package " + packageName + " was not found!"); 3132 } 3133 3134 if (!ps.getInstalled(userId)) { 3135 throw new SecurityException( 3136 "Package " + packageName + " was not installed for user " + userId + "!"); 3137 } 3138 3139 if (mSafeMode && !ps.isSystem()) { 3140 throw new SecurityException("Package " + packageName + " not a system app!"); 3141 } 3142 3143 if (mFrozenPackages.contains(packageName)) { 3144 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3145 } 3146 3147 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3148 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3149 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3150 } 3151 } 3152 } 3153 3154 @Override 3155 public boolean isPackageAvailable(String packageName, int userId) { 3156 if (!sUserManager.exists(userId)) return false; 3157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3158 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3159 synchronized (mPackages) { 3160 PackageParser.Package p = mPackages.get(packageName); 3161 if (p != null) { 3162 final PackageSetting ps = (PackageSetting) p.mExtras; 3163 if (ps != null) { 3164 final PackageUserState state = ps.readUserState(userId); 3165 if (state != null) { 3166 return PackageParser.isAvailable(state); 3167 } 3168 } 3169 } 3170 } 3171 return false; 3172 } 3173 3174 @Override 3175 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3176 if (!sUserManager.exists(userId)) return null; 3177 flags = updateFlagsForPackage(flags, userId, packageName); 3178 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3179 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3180 // reader 3181 synchronized (mPackages) { 3182 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3183 PackageParser.Package p = null; 3184 if (matchFactoryOnly) { 3185 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3186 if (ps != null) { 3187 return generatePackageInfo(ps, flags, userId); 3188 } 3189 } 3190 if (p == null) { 3191 p = mPackages.get(packageName); 3192 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3193 return null; 3194 } 3195 } 3196 if (DEBUG_PACKAGE_INFO) 3197 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3198 if (p != null) { 3199 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3200 } 3201 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3202 final PackageSetting ps = mSettings.mPackages.get(packageName); 3203 return generatePackageInfo(ps, flags, userId); 3204 } 3205 } 3206 return null; 3207 } 3208 3209 @Override 3210 public String[] currentToCanonicalPackageNames(String[] names) { 3211 String[] out = new String[names.length]; 3212 // reader 3213 synchronized (mPackages) { 3214 for (int i=names.length-1; i>=0; i--) { 3215 PackageSetting ps = mSettings.mPackages.get(names[i]); 3216 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3217 } 3218 } 3219 return out; 3220 } 3221 3222 @Override 3223 public String[] canonicalToCurrentPackageNames(String[] names) { 3224 String[] out = new String[names.length]; 3225 // reader 3226 synchronized (mPackages) { 3227 for (int i=names.length-1; i>=0; i--) { 3228 String cur = mSettings.mRenamedPackages.get(names[i]); 3229 out[i] = cur != null ? cur : names[i]; 3230 } 3231 } 3232 return out; 3233 } 3234 3235 @Override 3236 public int getPackageUid(String packageName, int flags, int userId) { 3237 if (!sUserManager.exists(userId)) return -1; 3238 flags = updateFlagsForPackage(flags, userId, packageName); 3239 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3240 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3241 3242 // reader 3243 synchronized (mPackages) { 3244 final PackageParser.Package p = mPackages.get(packageName); 3245 if (p != null && p.isMatch(flags)) { 3246 return UserHandle.getUid(userId, p.applicationInfo.uid); 3247 } 3248 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3249 final PackageSetting ps = mSettings.mPackages.get(packageName); 3250 if (ps != null && ps.isMatch(flags)) { 3251 return UserHandle.getUid(userId, ps.appId); 3252 } 3253 } 3254 } 3255 3256 return -1; 3257 } 3258 3259 @Override 3260 public int[] getPackageGids(String packageName, int flags, int userId) { 3261 if (!sUserManager.exists(userId)) return null; 3262 flags = updateFlagsForPackage(flags, userId, packageName); 3263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3264 false /* requireFullPermission */, false /* checkShell */, 3265 "getPackageGids"); 3266 3267 // reader 3268 synchronized (mPackages) { 3269 final PackageParser.Package p = mPackages.get(packageName); 3270 if (p != null && p.isMatch(flags)) { 3271 PackageSetting ps = (PackageSetting) p.mExtras; 3272 return ps.getPermissionsState().computeGids(userId); 3273 } 3274 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3275 final PackageSetting ps = mSettings.mPackages.get(packageName); 3276 if (ps != null && ps.isMatch(flags)) { 3277 return ps.getPermissionsState().computeGids(userId); 3278 } 3279 } 3280 } 3281 3282 return null; 3283 } 3284 3285 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3286 if (bp.perm != null) { 3287 return PackageParser.generatePermissionInfo(bp.perm, flags); 3288 } 3289 PermissionInfo pi = new PermissionInfo(); 3290 pi.name = bp.name; 3291 pi.packageName = bp.sourcePackage; 3292 pi.nonLocalizedLabel = bp.name; 3293 pi.protectionLevel = bp.protectionLevel; 3294 return pi; 3295 } 3296 3297 @Override 3298 public PermissionInfo getPermissionInfo(String name, int flags) { 3299 // reader 3300 synchronized (mPackages) { 3301 final BasePermission p = mSettings.mPermissions.get(name); 3302 if (p != null) { 3303 return generatePermissionInfo(p, flags); 3304 } 3305 return null; 3306 } 3307 } 3308 3309 @Override 3310 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3311 int flags) { 3312 // reader 3313 synchronized (mPackages) { 3314 if (group != null && !mPermissionGroups.containsKey(group)) { 3315 // This is thrown as NameNotFoundException 3316 return null; 3317 } 3318 3319 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3320 for (BasePermission p : mSettings.mPermissions.values()) { 3321 if (group == null) { 3322 if (p.perm == null || p.perm.info.group == null) { 3323 out.add(generatePermissionInfo(p, flags)); 3324 } 3325 } else { 3326 if (p.perm != null && group.equals(p.perm.info.group)) { 3327 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3328 } 3329 } 3330 } 3331 return new ParceledListSlice<>(out); 3332 } 3333 } 3334 3335 @Override 3336 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3337 // reader 3338 synchronized (mPackages) { 3339 return PackageParser.generatePermissionGroupInfo( 3340 mPermissionGroups.get(name), flags); 3341 } 3342 } 3343 3344 @Override 3345 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3346 // reader 3347 synchronized (mPackages) { 3348 final int N = mPermissionGroups.size(); 3349 ArrayList<PermissionGroupInfo> out 3350 = new ArrayList<PermissionGroupInfo>(N); 3351 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3352 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3353 } 3354 return new ParceledListSlice<>(out); 3355 } 3356 } 3357 3358 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3359 int userId) { 3360 if (!sUserManager.exists(userId)) return null; 3361 PackageSetting ps = mSettings.mPackages.get(packageName); 3362 if (ps != null) { 3363 if (ps.pkg == null) { 3364 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3365 if (pInfo != null) { 3366 return pInfo.applicationInfo; 3367 } 3368 return null; 3369 } 3370 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3371 ps.readUserState(userId), userId); 3372 } 3373 return null; 3374 } 3375 3376 @Override 3377 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3378 if (!sUserManager.exists(userId)) return null; 3379 flags = updateFlagsForApplication(flags, userId, packageName); 3380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3381 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3382 // writer 3383 synchronized (mPackages) { 3384 PackageParser.Package p = mPackages.get(packageName); 3385 if (DEBUG_PACKAGE_INFO) Log.v( 3386 TAG, "getApplicationInfo " + packageName 3387 + ": " + p); 3388 if (p != null) { 3389 PackageSetting ps = mSettings.mPackages.get(packageName); 3390 if (ps == null) return null; 3391 // Note: isEnabledLP() does not apply here - always return info 3392 return PackageParser.generateApplicationInfo( 3393 p, flags, ps.readUserState(userId), userId); 3394 } 3395 if ("android".equals(packageName)||"system".equals(packageName)) { 3396 return mAndroidApplication; 3397 } 3398 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3399 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3400 } 3401 } 3402 return null; 3403 } 3404 3405 @Override 3406 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3407 final IPackageDataObserver observer) { 3408 mContext.enforceCallingOrSelfPermission( 3409 android.Manifest.permission.CLEAR_APP_CACHE, null); 3410 // Queue up an async operation since clearing cache may take a little while. 3411 mHandler.post(new Runnable() { 3412 public void run() { 3413 mHandler.removeCallbacks(this); 3414 boolean success = true; 3415 synchronized (mInstallLock) { 3416 try { 3417 mInstaller.freeCache(volumeUuid, freeStorageSize); 3418 } catch (InstallerException e) { 3419 Slog.w(TAG, "Couldn't clear application caches: " + e); 3420 success = false; 3421 } 3422 } 3423 if (observer != null) { 3424 try { 3425 observer.onRemoveCompleted(null, success); 3426 } catch (RemoteException e) { 3427 Slog.w(TAG, "RemoveException when invoking call back"); 3428 } 3429 } 3430 } 3431 }); 3432 } 3433 3434 @Override 3435 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3436 final IntentSender pi) { 3437 mContext.enforceCallingOrSelfPermission( 3438 android.Manifest.permission.CLEAR_APP_CACHE, null); 3439 // Queue up an async operation since clearing cache may take a little while. 3440 mHandler.post(new Runnable() { 3441 public void run() { 3442 mHandler.removeCallbacks(this); 3443 boolean success = true; 3444 synchronized (mInstallLock) { 3445 try { 3446 mInstaller.freeCache(volumeUuid, freeStorageSize); 3447 } catch (InstallerException e) { 3448 Slog.w(TAG, "Couldn't clear application caches: " + e); 3449 success = false; 3450 } 3451 } 3452 if(pi != null) { 3453 try { 3454 // Callback via pending intent 3455 int code = success ? 1 : 0; 3456 pi.sendIntent(null, code, null, 3457 null, null); 3458 } catch (SendIntentException e1) { 3459 Slog.i(TAG, "Failed to send pending intent"); 3460 } 3461 } 3462 } 3463 }); 3464 } 3465 3466 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3467 synchronized (mInstallLock) { 3468 try { 3469 mInstaller.freeCache(volumeUuid, freeStorageSize); 3470 } catch (InstallerException e) { 3471 throw new IOException("Failed to free enough space", e); 3472 } 3473 } 3474 } 3475 3476 /** 3477 * Update given flags based on encryption status of current user. 3478 */ 3479 private int updateFlags(int flags, int userId) { 3480 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3481 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3482 // Caller expressed an explicit opinion about what encryption 3483 // aware/unaware components they want to see, so fall through and 3484 // give them what they want 3485 } else { 3486 // Caller expressed no opinion, so match based on user state 3487 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3488 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3489 } else { 3490 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3491 } 3492 } 3493 return flags; 3494 } 3495 3496 private UserManagerInternal getUserManagerInternal() { 3497 if (mUserManagerInternal == null) { 3498 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3499 } 3500 return mUserManagerInternal; 3501 } 3502 3503 /** 3504 * Update given flags when being used to request {@link PackageInfo}. 3505 */ 3506 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3507 boolean triaged = true; 3508 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3509 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3510 // Caller is asking for component details, so they'd better be 3511 // asking for specific encryption matching behavior, or be triaged 3512 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3513 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3514 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3515 triaged = false; 3516 } 3517 } 3518 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3519 | PackageManager.MATCH_SYSTEM_ONLY 3520 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3521 triaged = false; 3522 } 3523 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3524 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3525 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3526 } 3527 return updateFlags(flags, userId); 3528 } 3529 3530 /** 3531 * Update given flags when being used to request {@link ApplicationInfo}. 3532 */ 3533 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3534 return updateFlagsForPackage(flags, userId, cookie); 3535 } 3536 3537 /** 3538 * Update given flags when being used to request {@link ComponentInfo}. 3539 */ 3540 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3541 if (cookie instanceof Intent) { 3542 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3543 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3544 } 3545 } 3546 3547 boolean triaged = true; 3548 // Caller is asking for component details, so they'd better be 3549 // asking for specific encryption matching behavior, or be triaged 3550 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3551 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3552 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3553 triaged = false; 3554 } 3555 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3556 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3557 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3558 } 3559 3560 return updateFlags(flags, userId); 3561 } 3562 3563 /** 3564 * Update given flags when being used to request {@link ResolveInfo}. 3565 */ 3566 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3567 // Safe mode means we shouldn't match any third-party components 3568 if (mSafeMode) { 3569 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3570 } 3571 3572 return updateFlagsForComponent(flags, userId, cookie); 3573 } 3574 3575 @Override 3576 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3577 if (!sUserManager.exists(userId)) return null; 3578 flags = updateFlagsForComponent(flags, userId, component); 3579 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3580 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3581 synchronized (mPackages) { 3582 PackageParser.Activity a = mActivities.mActivities.get(component); 3583 3584 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3585 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3586 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3587 if (ps == null) return null; 3588 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3589 userId); 3590 } 3591 if (mResolveComponentName.equals(component)) { 3592 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3593 new PackageUserState(), userId); 3594 } 3595 } 3596 return null; 3597 } 3598 3599 @Override 3600 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3601 String resolvedType) { 3602 synchronized (mPackages) { 3603 if (component.equals(mResolveComponentName)) { 3604 // The resolver supports EVERYTHING! 3605 return true; 3606 } 3607 PackageParser.Activity a = mActivities.mActivities.get(component); 3608 if (a == null) { 3609 return false; 3610 } 3611 for (int i=0; i<a.intents.size(); i++) { 3612 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3613 intent.getData(), intent.getCategories(), TAG) >= 0) { 3614 return true; 3615 } 3616 } 3617 return false; 3618 } 3619 } 3620 3621 @Override 3622 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3623 if (!sUserManager.exists(userId)) return null; 3624 flags = updateFlagsForComponent(flags, userId, component); 3625 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3626 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3627 synchronized (mPackages) { 3628 PackageParser.Activity a = mReceivers.mActivities.get(component); 3629 if (DEBUG_PACKAGE_INFO) Log.v( 3630 TAG, "getReceiverInfo " + component + ": " + a); 3631 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3632 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3633 if (ps == null) return null; 3634 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3635 userId); 3636 } 3637 } 3638 return null; 3639 } 3640 3641 @Override 3642 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3643 if (!sUserManager.exists(userId)) return null; 3644 flags = updateFlagsForComponent(flags, userId, component); 3645 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3646 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3647 synchronized (mPackages) { 3648 PackageParser.Service s = mServices.mServices.get(component); 3649 if (DEBUG_PACKAGE_INFO) Log.v( 3650 TAG, "getServiceInfo " + component + ": " + s); 3651 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3652 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3653 if (ps == null) return null; 3654 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3655 userId); 3656 } 3657 } 3658 return null; 3659 } 3660 3661 @Override 3662 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3663 if (!sUserManager.exists(userId)) return null; 3664 flags = updateFlagsForComponent(flags, userId, component); 3665 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3666 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3667 synchronized (mPackages) { 3668 PackageParser.Provider p = mProviders.mProviders.get(component); 3669 if (DEBUG_PACKAGE_INFO) Log.v( 3670 TAG, "getProviderInfo " + component + ": " + p); 3671 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3672 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3673 if (ps == null) return null; 3674 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3675 userId); 3676 } 3677 } 3678 return null; 3679 } 3680 3681 @Override 3682 public String[] getSystemSharedLibraryNames() { 3683 Set<String> libSet; 3684 synchronized (mPackages) { 3685 libSet = mSharedLibraries.keySet(); 3686 int size = libSet.size(); 3687 if (size > 0) { 3688 String[] libs = new String[size]; 3689 libSet.toArray(libs); 3690 return libs; 3691 } 3692 } 3693 return null; 3694 } 3695 3696 @Override 3697 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3698 synchronized (mPackages) { 3699 return mServicesSystemSharedLibraryPackageName; 3700 } 3701 } 3702 3703 @Override 3704 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3705 synchronized (mPackages) { 3706 return mSharedSystemSharedLibraryPackageName; 3707 } 3708 } 3709 3710 @Override 3711 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3712 synchronized (mPackages) { 3713 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3714 3715 final FeatureInfo fi = new FeatureInfo(); 3716 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3717 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3718 res.add(fi); 3719 3720 return new ParceledListSlice<>(res); 3721 } 3722 } 3723 3724 @Override 3725 public boolean hasSystemFeature(String name, int version) { 3726 synchronized (mPackages) { 3727 final FeatureInfo feat = mAvailableFeatures.get(name); 3728 if (feat == null) { 3729 return false; 3730 } else { 3731 return feat.version >= version; 3732 } 3733 } 3734 } 3735 3736 @Override 3737 public int checkPermission(String permName, String pkgName, int userId) { 3738 if (!sUserManager.exists(userId)) { 3739 return PackageManager.PERMISSION_DENIED; 3740 } 3741 3742 synchronized (mPackages) { 3743 final PackageParser.Package p = mPackages.get(pkgName); 3744 if (p != null && p.mExtras != null) { 3745 final PackageSetting ps = (PackageSetting) p.mExtras; 3746 final PermissionsState permissionsState = ps.getPermissionsState(); 3747 if (permissionsState.hasPermission(permName, userId)) { 3748 return PackageManager.PERMISSION_GRANTED; 3749 } 3750 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3751 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3752 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3753 return PackageManager.PERMISSION_GRANTED; 3754 } 3755 } 3756 } 3757 3758 return PackageManager.PERMISSION_DENIED; 3759 } 3760 3761 @Override 3762 public int checkUidPermission(String permName, int uid) { 3763 final int userId = UserHandle.getUserId(uid); 3764 3765 if (!sUserManager.exists(userId)) { 3766 return PackageManager.PERMISSION_DENIED; 3767 } 3768 3769 synchronized (mPackages) { 3770 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3771 if (obj != null) { 3772 final SettingBase ps = (SettingBase) obj; 3773 final PermissionsState permissionsState = ps.getPermissionsState(); 3774 if (permissionsState.hasPermission(permName, userId)) { 3775 return PackageManager.PERMISSION_GRANTED; 3776 } 3777 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3778 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3779 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3780 return PackageManager.PERMISSION_GRANTED; 3781 } 3782 } else { 3783 ArraySet<String> perms = mSystemPermissions.get(uid); 3784 if (perms != null) { 3785 if (perms.contains(permName)) { 3786 return PackageManager.PERMISSION_GRANTED; 3787 } 3788 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3789 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3790 return PackageManager.PERMISSION_GRANTED; 3791 } 3792 } 3793 } 3794 } 3795 3796 return PackageManager.PERMISSION_DENIED; 3797 } 3798 3799 @Override 3800 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3801 if (UserHandle.getCallingUserId() != userId) { 3802 mContext.enforceCallingPermission( 3803 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3804 "isPermissionRevokedByPolicy for user " + userId); 3805 } 3806 3807 if (checkPermission(permission, packageName, userId) 3808 == PackageManager.PERMISSION_GRANTED) { 3809 return false; 3810 } 3811 3812 final long identity = Binder.clearCallingIdentity(); 3813 try { 3814 final int flags = getPermissionFlags(permission, packageName, userId); 3815 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3816 } finally { 3817 Binder.restoreCallingIdentity(identity); 3818 } 3819 } 3820 3821 @Override 3822 public String getPermissionControllerPackageName() { 3823 synchronized (mPackages) { 3824 return mRequiredInstallerPackage; 3825 } 3826 } 3827 3828 /** 3829 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3830 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3831 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3832 * @param message the message to log on security exception 3833 */ 3834 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3835 boolean checkShell, String message) { 3836 if (userId < 0) { 3837 throw new IllegalArgumentException("Invalid userId " + userId); 3838 } 3839 if (checkShell) { 3840 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3841 } 3842 if (userId == UserHandle.getUserId(callingUid)) return; 3843 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3844 if (requireFullPermission) { 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3847 } else { 3848 try { 3849 mContext.enforceCallingOrSelfPermission( 3850 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3851 } catch (SecurityException se) { 3852 mContext.enforceCallingOrSelfPermission( 3853 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3854 } 3855 } 3856 } 3857 } 3858 3859 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3860 if (callingUid == Process.SHELL_UID) { 3861 if (userHandle >= 0 3862 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3863 throw new SecurityException("Shell does not have permission to access user " 3864 + userHandle); 3865 } else if (userHandle < 0) { 3866 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3867 + Debug.getCallers(3)); 3868 } 3869 } 3870 } 3871 3872 private BasePermission findPermissionTreeLP(String permName) { 3873 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3874 if (permName.startsWith(bp.name) && 3875 permName.length() > bp.name.length() && 3876 permName.charAt(bp.name.length()) == '.') { 3877 return bp; 3878 } 3879 } 3880 return null; 3881 } 3882 3883 private BasePermission checkPermissionTreeLP(String permName) { 3884 if (permName != null) { 3885 BasePermission bp = findPermissionTreeLP(permName); 3886 if (bp != null) { 3887 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3888 return bp; 3889 } 3890 throw new SecurityException("Calling uid " 3891 + Binder.getCallingUid() 3892 + " is not allowed to add to permission tree " 3893 + bp.name + " owned by uid " + bp.uid); 3894 } 3895 } 3896 throw new SecurityException("No permission tree found for " + permName); 3897 } 3898 3899 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3900 if (s1 == null) { 3901 return s2 == null; 3902 } 3903 if (s2 == null) { 3904 return false; 3905 } 3906 if (s1.getClass() != s2.getClass()) { 3907 return false; 3908 } 3909 return s1.equals(s2); 3910 } 3911 3912 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3913 if (pi1.icon != pi2.icon) return false; 3914 if (pi1.logo != pi2.logo) return false; 3915 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3916 if (!compareStrings(pi1.name, pi2.name)) return false; 3917 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3918 // We'll take care of setting this one. 3919 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3920 // These are not currently stored in settings. 3921 //if (!compareStrings(pi1.group, pi2.group)) return false; 3922 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3923 //if (pi1.labelRes != pi2.labelRes) return false; 3924 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3925 return true; 3926 } 3927 3928 int permissionInfoFootprint(PermissionInfo info) { 3929 int size = info.name.length(); 3930 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3931 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3932 return size; 3933 } 3934 3935 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3936 int size = 0; 3937 for (BasePermission perm : mSettings.mPermissions.values()) { 3938 if (perm.uid == tree.uid) { 3939 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3940 } 3941 } 3942 return size; 3943 } 3944 3945 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3946 // We calculate the max size of permissions defined by this uid and throw 3947 // if that plus the size of 'info' would exceed our stated maximum. 3948 if (tree.uid != Process.SYSTEM_UID) { 3949 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3950 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3951 throw new SecurityException("Permission tree size cap exceeded"); 3952 } 3953 } 3954 } 3955 3956 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3957 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3958 throw new SecurityException("Label must be specified in permission"); 3959 } 3960 BasePermission tree = checkPermissionTreeLP(info.name); 3961 BasePermission bp = mSettings.mPermissions.get(info.name); 3962 boolean added = bp == null; 3963 boolean changed = true; 3964 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3965 if (added) { 3966 enforcePermissionCapLocked(info, tree); 3967 bp = new BasePermission(info.name, tree.sourcePackage, 3968 BasePermission.TYPE_DYNAMIC); 3969 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3970 throw new SecurityException( 3971 "Not allowed to modify non-dynamic permission " 3972 + info.name); 3973 } else { 3974 if (bp.protectionLevel == fixedLevel 3975 && bp.perm.owner.equals(tree.perm.owner) 3976 && bp.uid == tree.uid 3977 && comparePermissionInfos(bp.perm.info, info)) { 3978 changed = false; 3979 } 3980 } 3981 bp.protectionLevel = fixedLevel; 3982 info = new PermissionInfo(info); 3983 info.protectionLevel = fixedLevel; 3984 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3985 bp.perm.info.packageName = tree.perm.info.packageName; 3986 bp.uid = tree.uid; 3987 if (added) { 3988 mSettings.mPermissions.put(info.name, bp); 3989 } 3990 if (changed) { 3991 if (!async) { 3992 mSettings.writeLPr(); 3993 } else { 3994 scheduleWriteSettingsLocked(); 3995 } 3996 } 3997 return added; 3998 } 3999 4000 @Override 4001 public boolean addPermission(PermissionInfo info) { 4002 synchronized (mPackages) { 4003 return addPermissionLocked(info, false); 4004 } 4005 } 4006 4007 @Override 4008 public boolean addPermissionAsync(PermissionInfo info) { 4009 synchronized (mPackages) { 4010 return addPermissionLocked(info, true); 4011 } 4012 } 4013 4014 @Override 4015 public void removePermission(String name) { 4016 synchronized (mPackages) { 4017 checkPermissionTreeLP(name); 4018 BasePermission bp = mSettings.mPermissions.get(name); 4019 if (bp != null) { 4020 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4021 throw new SecurityException( 4022 "Not allowed to modify non-dynamic permission " 4023 + name); 4024 } 4025 mSettings.mPermissions.remove(name); 4026 mSettings.writeLPr(); 4027 } 4028 } 4029 } 4030 4031 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4032 BasePermission bp) { 4033 int index = pkg.requestedPermissions.indexOf(bp.name); 4034 if (index == -1) { 4035 throw new SecurityException("Package " + pkg.packageName 4036 + " has not requested permission " + bp.name); 4037 } 4038 if (!bp.isRuntime() && !bp.isDevelopment()) { 4039 throw new SecurityException("Permission " + bp.name 4040 + " is not a changeable permission type"); 4041 } 4042 } 4043 4044 @Override 4045 public void grantRuntimePermission(String packageName, String name, final int userId) { 4046 if (!sUserManager.exists(userId)) { 4047 Log.e(TAG, "No such user:" + userId); 4048 return; 4049 } 4050 4051 mContext.enforceCallingOrSelfPermission( 4052 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4053 "grantRuntimePermission"); 4054 4055 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4056 true /* requireFullPermission */, true /* checkShell */, 4057 "grantRuntimePermission"); 4058 4059 final int uid; 4060 final SettingBase sb; 4061 4062 synchronized (mPackages) { 4063 final PackageParser.Package pkg = mPackages.get(packageName); 4064 if (pkg == null) { 4065 throw new IllegalArgumentException("Unknown package: " + packageName); 4066 } 4067 4068 final BasePermission bp = mSettings.mPermissions.get(name); 4069 if (bp == null) { 4070 throw new IllegalArgumentException("Unknown permission: " + name); 4071 } 4072 4073 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4074 4075 // If a permission review is required for legacy apps we represent 4076 // their permissions as always granted runtime ones since we need 4077 // to keep the review required permission flag per user while an 4078 // install permission's state is shared across all users. 4079 if (Build.PERMISSIONS_REVIEW_REQUIRED 4080 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4081 && bp.isRuntime()) { 4082 return; 4083 } 4084 4085 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4086 sb = (SettingBase) pkg.mExtras; 4087 if (sb == null) { 4088 throw new IllegalArgumentException("Unknown package: " + packageName); 4089 } 4090 4091 final PermissionsState permissionsState = sb.getPermissionsState(); 4092 4093 final int flags = permissionsState.getPermissionFlags(name, userId); 4094 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4095 throw new SecurityException("Cannot grant system fixed permission " 4096 + name + " for package " + packageName); 4097 } 4098 4099 if (bp.isDevelopment()) { 4100 // Development permissions must be handled specially, since they are not 4101 // normal runtime permissions. For now they apply to all users. 4102 if (permissionsState.grantInstallPermission(bp) != 4103 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4104 scheduleWriteSettingsLocked(); 4105 } 4106 return; 4107 } 4108 4109 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4110 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4111 return; 4112 } 4113 4114 final int result = permissionsState.grantRuntimePermission(bp, userId); 4115 switch (result) { 4116 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4117 return; 4118 } 4119 4120 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4121 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4122 mHandler.post(new Runnable() { 4123 @Override 4124 public void run() { 4125 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4126 } 4127 }); 4128 } 4129 break; 4130 } 4131 4132 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4133 4134 // Not critical if that is lost - app has to request again. 4135 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4136 } 4137 4138 // Only need to do this if user is initialized. Otherwise it's a new user 4139 // and there are no processes running as the user yet and there's no need 4140 // to make an expensive call to remount processes for the changed permissions. 4141 if (READ_EXTERNAL_STORAGE.equals(name) 4142 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4143 final long token = Binder.clearCallingIdentity(); 4144 try { 4145 if (sUserManager.isInitialized(userId)) { 4146 MountServiceInternal mountServiceInternal = LocalServices.getService( 4147 MountServiceInternal.class); 4148 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4149 } 4150 } finally { 4151 Binder.restoreCallingIdentity(token); 4152 } 4153 } 4154 } 4155 4156 @Override 4157 public void revokeRuntimePermission(String packageName, String name, int userId) { 4158 if (!sUserManager.exists(userId)) { 4159 Log.e(TAG, "No such user:" + userId); 4160 return; 4161 } 4162 4163 mContext.enforceCallingOrSelfPermission( 4164 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4165 "revokeRuntimePermission"); 4166 4167 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4168 true /* requireFullPermission */, true /* checkShell */, 4169 "revokeRuntimePermission"); 4170 4171 final int appId; 4172 4173 synchronized (mPackages) { 4174 final PackageParser.Package pkg = mPackages.get(packageName); 4175 if (pkg == null) { 4176 throw new IllegalArgumentException("Unknown package: " + packageName); 4177 } 4178 4179 final BasePermission bp = mSettings.mPermissions.get(name); 4180 if (bp == null) { 4181 throw new IllegalArgumentException("Unknown permission: " + name); 4182 } 4183 4184 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4185 4186 // If a permission review is required for legacy apps we represent 4187 // their permissions as always granted runtime ones since we need 4188 // to keep the review required permission flag per user while an 4189 // install permission's state is shared across all users. 4190 if (Build.PERMISSIONS_REVIEW_REQUIRED 4191 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4192 && bp.isRuntime()) { 4193 return; 4194 } 4195 4196 SettingBase sb = (SettingBase) pkg.mExtras; 4197 if (sb == null) { 4198 throw new IllegalArgumentException("Unknown package: " + packageName); 4199 } 4200 4201 final PermissionsState permissionsState = sb.getPermissionsState(); 4202 4203 final int flags = permissionsState.getPermissionFlags(name, userId); 4204 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4205 throw new SecurityException("Cannot revoke system fixed permission " 4206 + name + " for package " + packageName); 4207 } 4208 4209 if (bp.isDevelopment()) { 4210 // Development permissions must be handled specially, since they are not 4211 // normal runtime permissions. For now they apply to all users. 4212 if (permissionsState.revokeInstallPermission(bp) != 4213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4214 scheduleWriteSettingsLocked(); 4215 } 4216 return; 4217 } 4218 4219 if (permissionsState.revokeRuntimePermission(bp, userId) == 4220 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4221 return; 4222 } 4223 4224 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4225 4226 // Critical, after this call app should never have the permission. 4227 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4228 4229 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4230 } 4231 4232 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4233 } 4234 4235 @Override 4236 public void resetRuntimePermissions() { 4237 mContext.enforceCallingOrSelfPermission( 4238 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4239 "revokeRuntimePermission"); 4240 4241 int callingUid = Binder.getCallingUid(); 4242 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4243 mContext.enforceCallingOrSelfPermission( 4244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4245 "resetRuntimePermissions"); 4246 } 4247 4248 synchronized (mPackages) { 4249 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4250 for (int userId : UserManagerService.getInstance().getUserIds()) { 4251 final int packageCount = mPackages.size(); 4252 for (int i = 0; i < packageCount; i++) { 4253 PackageParser.Package pkg = mPackages.valueAt(i); 4254 if (!(pkg.mExtras instanceof PackageSetting)) { 4255 continue; 4256 } 4257 PackageSetting ps = (PackageSetting) pkg.mExtras; 4258 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4259 } 4260 } 4261 } 4262 } 4263 4264 @Override 4265 public int getPermissionFlags(String name, String packageName, int userId) { 4266 if (!sUserManager.exists(userId)) { 4267 return 0; 4268 } 4269 4270 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4271 4272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4273 true /* requireFullPermission */, false /* checkShell */, 4274 "getPermissionFlags"); 4275 4276 synchronized (mPackages) { 4277 final PackageParser.Package pkg = mPackages.get(packageName); 4278 if (pkg == null) { 4279 throw new IllegalArgumentException("Unknown package: " + packageName); 4280 } 4281 4282 final BasePermission bp = mSettings.mPermissions.get(name); 4283 if (bp == null) { 4284 throw new IllegalArgumentException("Unknown permission: " + name); 4285 } 4286 4287 SettingBase sb = (SettingBase) pkg.mExtras; 4288 if (sb == null) { 4289 throw new IllegalArgumentException("Unknown package: " + packageName); 4290 } 4291 4292 PermissionsState permissionsState = sb.getPermissionsState(); 4293 return permissionsState.getPermissionFlags(name, userId); 4294 } 4295 } 4296 4297 @Override 4298 public void updatePermissionFlags(String name, String packageName, int flagMask, 4299 int flagValues, int userId) { 4300 if (!sUserManager.exists(userId)) { 4301 return; 4302 } 4303 4304 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4305 4306 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4307 true /* requireFullPermission */, true /* checkShell */, 4308 "updatePermissionFlags"); 4309 4310 // Only the system can change these flags and nothing else. 4311 if (getCallingUid() != Process.SYSTEM_UID) { 4312 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4313 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4314 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4315 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4316 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4317 } 4318 4319 synchronized (mPackages) { 4320 final PackageParser.Package pkg = mPackages.get(packageName); 4321 if (pkg == null) { 4322 throw new IllegalArgumentException("Unknown package: " + packageName); 4323 } 4324 4325 final BasePermission bp = mSettings.mPermissions.get(name); 4326 if (bp == null) { 4327 throw new IllegalArgumentException("Unknown permission: " + name); 4328 } 4329 4330 SettingBase sb = (SettingBase) pkg.mExtras; 4331 if (sb == null) { 4332 throw new IllegalArgumentException("Unknown package: " + packageName); 4333 } 4334 4335 PermissionsState permissionsState = sb.getPermissionsState(); 4336 4337 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4338 4339 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4340 // Install and runtime permissions are stored in different places, 4341 // so figure out what permission changed and persist the change. 4342 if (permissionsState.getInstallPermissionState(name) != null) { 4343 scheduleWriteSettingsLocked(); 4344 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4345 || hadState) { 4346 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4347 } 4348 } 4349 } 4350 } 4351 4352 /** 4353 * Update the permission flags for all packages and runtime permissions of a user in order 4354 * to allow device or profile owner to remove POLICY_FIXED. 4355 */ 4356 @Override 4357 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4358 if (!sUserManager.exists(userId)) { 4359 return; 4360 } 4361 4362 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4363 4364 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4365 true /* requireFullPermission */, true /* checkShell */, 4366 "updatePermissionFlagsForAllApps"); 4367 4368 // Only the system can change system fixed flags. 4369 if (getCallingUid() != Process.SYSTEM_UID) { 4370 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4371 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4372 } 4373 4374 synchronized (mPackages) { 4375 boolean changed = false; 4376 final int packageCount = mPackages.size(); 4377 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4378 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4379 SettingBase sb = (SettingBase) pkg.mExtras; 4380 if (sb == null) { 4381 continue; 4382 } 4383 PermissionsState permissionsState = sb.getPermissionsState(); 4384 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4385 userId, flagMask, flagValues); 4386 } 4387 if (changed) { 4388 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4389 } 4390 } 4391 } 4392 4393 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4394 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4395 != PackageManager.PERMISSION_GRANTED 4396 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4397 != PackageManager.PERMISSION_GRANTED) { 4398 throw new SecurityException(message + " requires " 4399 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4400 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4401 } 4402 } 4403 4404 @Override 4405 public boolean shouldShowRequestPermissionRationale(String permissionName, 4406 String packageName, int userId) { 4407 if (UserHandle.getCallingUserId() != userId) { 4408 mContext.enforceCallingPermission( 4409 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4410 "canShowRequestPermissionRationale for user " + userId); 4411 } 4412 4413 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4414 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4415 return false; 4416 } 4417 4418 if (checkPermission(permissionName, packageName, userId) 4419 == PackageManager.PERMISSION_GRANTED) { 4420 return false; 4421 } 4422 4423 final int flags; 4424 4425 final long identity = Binder.clearCallingIdentity(); 4426 try { 4427 flags = getPermissionFlags(permissionName, 4428 packageName, userId); 4429 } finally { 4430 Binder.restoreCallingIdentity(identity); 4431 } 4432 4433 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4434 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4435 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4436 4437 if ((flags & fixedFlags) != 0) { 4438 return false; 4439 } 4440 4441 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4442 } 4443 4444 @Override 4445 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4446 mContext.enforceCallingOrSelfPermission( 4447 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4448 "addOnPermissionsChangeListener"); 4449 4450 synchronized (mPackages) { 4451 mOnPermissionChangeListeners.addListenerLocked(listener); 4452 } 4453 } 4454 4455 @Override 4456 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4457 synchronized (mPackages) { 4458 mOnPermissionChangeListeners.removeListenerLocked(listener); 4459 } 4460 } 4461 4462 @Override 4463 public boolean isProtectedBroadcast(String actionName) { 4464 synchronized (mPackages) { 4465 if (mProtectedBroadcasts.contains(actionName)) { 4466 return true; 4467 } else if (actionName != null) { 4468 // TODO: remove these terrible hacks 4469 if (actionName.startsWith("android.net.netmon.lingerExpired") 4470 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4471 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4472 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4473 return true; 4474 } 4475 } 4476 } 4477 return false; 4478 } 4479 4480 @Override 4481 public int checkSignatures(String pkg1, String pkg2) { 4482 synchronized (mPackages) { 4483 final PackageParser.Package p1 = mPackages.get(pkg1); 4484 final PackageParser.Package p2 = mPackages.get(pkg2); 4485 if (p1 == null || p1.mExtras == null 4486 || p2 == null || p2.mExtras == null) { 4487 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4488 } 4489 return compareSignatures(p1.mSignatures, p2.mSignatures); 4490 } 4491 } 4492 4493 @Override 4494 public int checkUidSignatures(int uid1, int uid2) { 4495 // Map to base uids. 4496 uid1 = UserHandle.getAppId(uid1); 4497 uid2 = UserHandle.getAppId(uid2); 4498 // reader 4499 synchronized (mPackages) { 4500 Signature[] s1; 4501 Signature[] s2; 4502 Object obj = mSettings.getUserIdLPr(uid1); 4503 if (obj != null) { 4504 if (obj instanceof SharedUserSetting) { 4505 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4506 } else if (obj instanceof PackageSetting) { 4507 s1 = ((PackageSetting)obj).signatures.mSignatures; 4508 } else { 4509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4510 } 4511 } else { 4512 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4513 } 4514 obj = mSettings.getUserIdLPr(uid2); 4515 if (obj != null) { 4516 if (obj instanceof SharedUserSetting) { 4517 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4518 } else if (obj instanceof PackageSetting) { 4519 s2 = ((PackageSetting)obj).signatures.mSignatures; 4520 } else { 4521 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4522 } 4523 } else { 4524 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4525 } 4526 return compareSignatures(s1, s2); 4527 } 4528 } 4529 4530 /** 4531 * This method should typically only be used when granting or revoking 4532 * permissions, since the app may immediately restart after this call. 4533 * <p> 4534 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4535 * guard your work against the app being relaunched. 4536 */ 4537 private void killUid(int appId, int userId, String reason) { 4538 final long identity = Binder.clearCallingIdentity(); 4539 try { 4540 IActivityManager am = ActivityManagerNative.getDefault(); 4541 if (am != null) { 4542 try { 4543 am.killUid(appId, userId, reason); 4544 } catch (RemoteException e) { 4545 /* ignore - same process */ 4546 } 4547 } 4548 } finally { 4549 Binder.restoreCallingIdentity(identity); 4550 } 4551 } 4552 4553 /** 4554 * Compares two sets of signatures. Returns: 4555 * <br /> 4556 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4557 * <br /> 4558 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4559 * <br /> 4560 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4561 * <br /> 4562 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4563 * <br /> 4564 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4565 */ 4566 static int compareSignatures(Signature[] s1, Signature[] s2) { 4567 if (s1 == null) { 4568 return s2 == null 4569 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4570 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4571 } 4572 4573 if (s2 == null) { 4574 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4575 } 4576 4577 if (s1.length != s2.length) { 4578 return PackageManager.SIGNATURE_NO_MATCH; 4579 } 4580 4581 // Since both signature sets are of size 1, we can compare without HashSets. 4582 if (s1.length == 1) { 4583 return s1[0].equals(s2[0]) ? 4584 PackageManager.SIGNATURE_MATCH : 4585 PackageManager.SIGNATURE_NO_MATCH; 4586 } 4587 4588 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4589 for (Signature sig : s1) { 4590 set1.add(sig); 4591 } 4592 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4593 for (Signature sig : s2) { 4594 set2.add(sig); 4595 } 4596 // Make sure s2 contains all signatures in s1. 4597 if (set1.equals(set2)) { 4598 return PackageManager.SIGNATURE_MATCH; 4599 } 4600 return PackageManager.SIGNATURE_NO_MATCH; 4601 } 4602 4603 /** 4604 * If the database version for this type of package (internal storage or 4605 * external storage) is less than the version where package signatures 4606 * were updated, return true. 4607 */ 4608 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4609 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4610 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4611 } 4612 4613 /** 4614 * Used for backward compatibility to make sure any packages with 4615 * certificate chains get upgraded to the new style. {@code existingSigs} 4616 * will be in the old format (since they were stored on disk from before the 4617 * system upgrade) and {@code scannedSigs} will be in the newer format. 4618 */ 4619 private int compareSignaturesCompat(PackageSignatures existingSigs, 4620 PackageParser.Package scannedPkg) { 4621 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4622 return PackageManager.SIGNATURE_NO_MATCH; 4623 } 4624 4625 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4626 for (Signature sig : existingSigs.mSignatures) { 4627 existingSet.add(sig); 4628 } 4629 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4630 for (Signature sig : scannedPkg.mSignatures) { 4631 try { 4632 Signature[] chainSignatures = sig.getChainSignatures(); 4633 for (Signature chainSig : chainSignatures) { 4634 scannedCompatSet.add(chainSig); 4635 } 4636 } catch (CertificateEncodingException e) { 4637 scannedCompatSet.add(sig); 4638 } 4639 } 4640 /* 4641 * Make sure the expanded scanned set contains all signatures in the 4642 * existing one. 4643 */ 4644 if (scannedCompatSet.equals(existingSet)) { 4645 // Migrate the old signatures to the new scheme. 4646 existingSigs.assignSignatures(scannedPkg.mSignatures); 4647 // The new KeySets will be re-added later in the scanning process. 4648 synchronized (mPackages) { 4649 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4650 } 4651 return PackageManager.SIGNATURE_MATCH; 4652 } 4653 return PackageManager.SIGNATURE_NO_MATCH; 4654 } 4655 4656 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4657 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4658 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4659 } 4660 4661 private int compareSignaturesRecover(PackageSignatures existingSigs, 4662 PackageParser.Package scannedPkg) { 4663 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4664 return PackageManager.SIGNATURE_NO_MATCH; 4665 } 4666 4667 String msg = null; 4668 try { 4669 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4670 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4671 + scannedPkg.packageName); 4672 return PackageManager.SIGNATURE_MATCH; 4673 } 4674 } catch (CertificateException e) { 4675 msg = e.getMessage(); 4676 } 4677 4678 logCriticalInfo(Log.INFO, 4679 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4680 return PackageManager.SIGNATURE_NO_MATCH; 4681 } 4682 4683 @Override 4684 public List<String> getAllPackages() { 4685 synchronized (mPackages) { 4686 return new ArrayList<String>(mPackages.keySet()); 4687 } 4688 } 4689 4690 @Override 4691 public String[] getPackagesForUid(int uid) { 4692 uid = UserHandle.getAppId(uid); 4693 // reader 4694 synchronized (mPackages) { 4695 Object obj = mSettings.getUserIdLPr(uid); 4696 if (obj instanceof SharedUserSetting) { 4697 final SharedUserSetting sus = (SharedUserSetting) obj; 4698 final int N = sus.packages.size(); 4699 final String[] res = new String[N]; 4700 final Iterator<PackageSetting> it = sus.packages.iterator(); 4701 int i = 0; 4702 while (it.hasNext()) { 4703 res[i++] = it.next().name; 4704 } 4705 return res; 4706 } else if (obj instanceof PackageSetting) { 4707 final PackageSetting ps = (PackageSetting) obj; 4708 return new String[] { ps.name }; 4709 } 4710 } 4711 return null; 4712 } 4713 4714 @Override 4715 public String getNameForUid(int uid) { 4716 // reader 4717 synchronized (mPackages) { 4718 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4719 if (obj instanceof SharedUserSetting) { 4720 final SharedUserSetting sus = (SharedUserSetting) obj; 4721 return sus.name + ":" + sus.userId; 4722 } else if (obj instanceof PackageSetting) { 4723 final PackageSetting ps = (PackageSetting) obj; 4724 return ps.name; 4725 } 4726 } 4727 return null; 4728 } 4729 4730 @Override 4731 public int getUidForSharedUser(String sharedUserName) { 4732 if(sharedUserName == null) { 4733 return -1; 4734 } 4735 // reader 4736 synchronized (mPackages) { 4737 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4738 if (suid == null) { 4739 return -1; 4740 } 4741 return suid.userId; 4742 } 4743 } 4744 4745 @Override 4746 public int getFlagsForUid(int uid) { 4747 synchronized (mPackages) { 4748 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4749 if (obj instanceof SharedUserSetting) { 4750 final SharedUserSetting sus = (SharedUserSetting) obj; 4751 return sus.pkgFlags; 4752 } else if (obj instanceof PackageSetting) { 4753 final PackageSetting ps = (PackageSetting) obj; 4754 return ps.pkgFlags; 4755 } 4756 } 4757 return 0; 4758 } 4759 4760 @Override 4761 public int getPrivateFlagsForUid(int uid) { 4762 synchronized (mPackages) { 4763 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4764 if (obj instanceof SharedUserSetting) { 4765 final SharedUserSetting sus = (SharedUserSetting) obj; 4766 return sus.pkgPrivateFlags; 4767 } else if (obj instanceof PackageSetting) { 4768 final PackageSetting ps = (PackageSetting) obj; 4769 return ps.pkgPrivateFlags; 4770 } 4771 } 4772 return 0; 4773 } 4774 4775 @Override 4776 public boolean isUidPrivileged(int uid) { 4777 uid = UserHandle.getAppId(uid); 4778 // reader 4779 synchronized (mPackages) { 4780 Object obj = mSettings.getUserIdLPr(uid); 4781 if (obj instanceof SharedUserSetting) { 4782 final SharedUserSetting sus = (SharedUserSetting) obj; 4783 final Iterator<PackageSetting> it = sus.packages.iterator(); 4784 while (it.hasNext()) { 4785 if (it.next().isPrivileged()) { 4786 return true; 4787 } 4788 } 4789 } else if (obj instanceof PackageSetting) { 4790 final PackageSetting ps = (PackageSetting) obj; 4791 return ps.isPrivileged(); 4792 } 4793 } 4794 return false; 4795 } 4796 4797 @Override 4798 public String[] getAppOpPermissionPackages(String permissionName) { 4799 synchronized (mPackages) { 4800 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4801 if (pkgs == null) { 4802 return null; 4803 } 4804 return pkgs.toArray(new String[pkgs.size()]); 4805 } 4806 } 4807 4808 @Override 4809 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4810 int flags, int userId) { 4811 try { 4812 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4813 4814 if (!sUserManager.exists(userId)) return null; 4815 flags = updateFlagsForResolve(flags, userId, intent); 4816 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4817 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4818 4819 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4820 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4821 flags, userId); 4822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4823 4824 final ResolveInfo bestChoice = 4825 chooseBestActivity(intent, resolvedType, flags, query, userId); 4826 4827 if (isEphemeralAllowed(intent, query, userId)) { 4828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4829 final EphemeralResolveInfo ai = 4830 getEphemeralResolveInfo(intent, resolvedType, userId); 4831 if (ai != null) { 4832 if (DEBUG_EPHEMERAL) { 4833 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4834 } 4835 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4836 bestChoice.ephemeralResolveInfo = ai; 4837 } 4838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4839 } 4840 return bestChoice; 4841 } finally { 4842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4843 } 4844 } 4845 4846 @Override 4847 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4848 IntentFilter filter, int match, ComponentName activity) { 4849 final int userId = UserHandle.getCallingUserId(); 4850 if (DEBUG_PREFERRED) { 4851 Log.v(TAG, "setLastChosenActivity intent=" + intent 4852 + " resolvedType=" + resolvedType 4853 + " flags=" + flags 4854 + " filter=" + filter 4855 + " match=" + match 4856 + " activity=" + activity); 4857 filter.dump(new PrintStreamPrinter(System.out), " "); 4858 } 4859 intent.setComponent(null); 4860 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4861 userId); 4862 // Find any earlier preferred or last chosen entries and nuke them 4863 findPreferredActivity(intent, resolvedType, 4864 flags, query, 0, false, true, false, userId); 4865 // Add the new activity as the last chosen for this filter 4866 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4867 "Setting last chosen"); 4868 } 4869 4870 @Override 4871 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4872 final int userId = UserHandle.getCallingUserId(); 4873 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4874 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4875 userId); 4876 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4877 false, false, false, userId); 4878 } 4879 4880 4881 private boolean isEphemeralAllowed( 4882 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4883 // Short circuit and return early if possible. 4884 if (DISABLE_EPHEMERAL_APPS) { 4885 return false; 4886 } 4887 final int callingUser = UserHandle.getCallingUserId(); 4888 if (callingUser != UserHandle.USER_SYSTEM) { 4889 return false; 4890 } 4891 if (mEphemeralResolverConnection == null) { 4892 return false; 4893 } 4894 if (intent.getComponent() != null) { 4895 return false; 4896 } 4897 if (intent.getPackage() != null) { 4898 return false; 4899 } 4900 final boolean isWebUri = hasWebURI(intent); 4901 if (!isWebUri) { 4902 return false; 4903 } 4904 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4905 synchronized (mPackages) { 4906 final int count = resolvedActivites.size(); 4907 for (int n = 0; n < count; n++) { 4908 ResolveInfo info = resolvedActivites.get(n); 4909 String packageName = info.activityInfo.packageName; 4910 PackageSetting ps = mSettings.mPackages.get(packageName); 4911 if (ps != null) { 4912 // Try to get the status from User settings first 4913 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4914 int status = (int) (packedStatus >> 32); 4915 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4916 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4917 if (DEBUG_EPHEMERAL) { 4918 Slog.v(TAG, "DENY ephemeral apps;" 4919 + " pkg: " + packageName + ", status: " + status); 4920 } 4921 return false; 4922 } 4923 } 4924 } 4925 } 4926 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4927 return true; 4928 } 4929 4930 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4931 int userId) { 4932 MessageDigest digest = null; 4933 try { 4934 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4935 } catch (NoSuchAlgorithmException e) { 4936 // If we can't create a digest, ignore ephemeral apps. 4937 return null; 4938 } 4939 4940 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4941 final byte[] digestBytes = digest.digest(hostBytes); 4942 int shaPrefix = 4943 digestBytes[0] << 24 4944 | digestBytes[1] << 16 4945 | digestBytes[2] << 8 4946 | digestBytes[3] << 0; 4947 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4948 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4949 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4950 // No hash prefix match; there are no ephemeral apps for this domain. 4951 return null; 4952 } 4953 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4954 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4955 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4956 continue; 4957 } 4958 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4959 // No filters; this should never happen. 4960 if (filters.isEmpty()) { 4961 continue; 4962 } 4963 // We have a domain match; resolve the filters to see if anything matches. 4964 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4965 for (int j = filters.size() - 1; j >= 0; --j) { 4966 final EphemeralResolveIntentInfo intentInfo = 4967 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4968 ephemeralResolver.addFilter(intentInfo); 4969 } 4970 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4971 intent, resolvedType, false /*defaultOnly*/, userId); 4972 if (!matchedResolveInfoList.isEmpty()) { 4973 return matchedResolveInfoList.get(0); 4974 } 4975 } 4976 // Hash or filter mis-match; no ephemeral apps for this domain. 4977 return null; 4978 } 4979 4980 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4981 int flags, List<ResolveInfo> query, int userId) { 4982 if (query != null) { 4983 final int N = query.size(); 4984 if (N == 1) { 4985 return query.get(0); 4986 } else if (N > 1) { 4987 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4988 // If there is more than one activity with the same priority, 4989 // then let the user decide between them. 4990 ResolveInfo r0 = query.get(0); 4991 ResolveInfo r1 = query.get(1); 4992 if (DEBUG_INTENT_MATCHING || debug) { 4993 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4994 + r1.activityInfo.name + "=" + r1.priority); 4995 } 4996 // If the first activity has a higher priority, or a different 4997 // default, then it is always desirable to pick it. 4998 if (r0.priority != r1.priority 4999 || r0.preferredOrder != r1.preferredOrder 5000 || r0.isDefault != r1.isDefault) { 5001 return query.get(0); 5002 } 5003 // If we have saved a preference for a preferred activity for 5004 // this Intent, use that. 5005 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5006 flags, query, r0.priority, true, false, debug, userId); 5007 if (ri != null) { 5008 return ri; 5009 } 5010 ri = new ResolveInfo(mResolveInfo); 5011 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5012 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5013 ri.activityInfo.applicationInfo = new ApplicationInfo( 5014 ri.activityInfo.applicationInfo); 5015 if (userId != 0) { 5016 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5017 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5018 } 5019 // Make sure that the resolver is displayable in car mode 5020 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5021 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5022 return ri; 5023 } 5024 } 5025 return null; 5026 } 5027 5028 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5029 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5030 final int N = query.size(); 5031 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5032 .get(userId); 5033 // Get the list of persistent preferred activities that handle the intent 5034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5035 List<PersistentPreferredActivity> pprefs = ppir != null 5036 ? ppir.queryIntent(intent, resolvedType, 5037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5038 : null; 5039 if (pprefs != null && pprefs.size() > 0) { 5040 final int M = pprefs.size(); 5041 for (int i=0; i<M; i++) { 5042 final PersistentPreferredActivity ppa = pprefs.get(i); 5043 if (DEBUG_PREFERRED || debug) { 5044 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5045 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5046 + "\n component=" + ppa.mComponent); 5047 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5048 } 5049 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5050 flags | MATCH_DISABLED_COMPONENTS, userId); 5051 if (DEBUG_PREFERRED || debug) { 5052 Slog.v(TAG, "Found persistent preferred activity:"); 5053 if (ai != null) { 5054 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5055 } else { 5056 Slog.v(TAG, " null"); 5057 } 5058 } 5059 if (ai == null) { 5060 // This previously registered persistent preferred activity 5061 // component is no longer known. Ignore it and do NOT remove it. 5062 continue; 5063 } 5064 for (int j=0; j<N; j++) { 5065 final ResolveInfo ri = query.get(j); 5066 if (!ri.activityInfo.applicationInfo.packageName 5067 .equals(ai.applicationInfo.packageName)) { 5068 continue; 5069 } 5070 if (!ri.activityInfo.name.equals(ai.name)) { 5071 continue; 5072 } 5073 // Found a persistent preference that can handle the intent. 5074 if (DEBUG_PREFERRED || debug) { 5075 Slog.v(TAG, "Returning persistent preferred activity: " + 5076 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5077 } 5078 return ri; 5079 } 5080 } 5081 } 5082 return null; 5083 } 5084 5085 // TODO: handle preferred activities missing while user has amnesia 5086 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5087 List<ResolveInfo> query, int priority, boolean always, 5088 boolean removeMatches, boolean debug, int userId) { 5089 if (!sUserManager.exists(userId)) return null; 5090 flags = updateFlagsForResolve(flags, userId, intent); 5091 // writer 5092 synchronized (mPackages) { 5093 if (intent.getSelector() != null) { 5094 intent = intent.getSelector(); 5095 } 5096 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5097 5098 // Try to find a matching persistent preferred activity. 5099 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5100 debug, userId); 5101 5102 // If a persistent preferred activity matched, use it. 5103 if (pri != null) { 5104 return pri; 5105 } 5106 5107 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5108 // Get the list of preferred activities that handle the intent 5109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5110 List<PreferredActivity> prefs = pir != null 5111 ? pir.queryIntent(intent, resolvedType, 5112 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5113 : null; 5114 if (prefs != null && prefs.size() > 0) { 5115 boolean changed = false; 5116 try { 5117 // First figure out how good the original match set is. 5118 // We will only allow preferred activities that came 5119 // from the same match quality. 5120 int match = 0; 5121 5122 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5123 5124 final int N = query.size(); 5125 for (int j=0; j<N; j++) { 5126 final ResolveInfo ri = query.get(j); 5127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5128 + ": 0x" + Integer.toHexString(match)); 5129 if (ri.match > match) { 5130 match = ri.match; 5131 } 5132 } 5133 5134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5135 + Integer.toHexString(match)); 5136 5137 match &= IntentFilter.MATCH_CATEGORY_MASK; 5138 final int M = prefs.size(); 5139 for (int i=0; i<M; i++) { 5140 final PreferredActivity pa = prefs.get(i); 5141 if (DEBUG_PREFERRED || debug) { 5142 Slog.v(TAG, "Checking PreferredActivity ds=" 5143 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5144 + "\n component=" + pa.mPref.mComponent); 5145 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5146 } 5147 if (pa.mPref.mMatch != match) { 5148 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5149 + Integer.toHexString(pa.mPref.mMatch)); 5150 continue; 5151 } 5152 // If it's not an "always" type preferred activity and that's what we're 5153 // looking for, skip it. 5154 if (always && !pa.mPref.mAlways) { 5155 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5156 continue; 5157 } 5158 final ActivityInfo ai = getActivityInfo( 5159 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5160 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5161 userId); 5162 if (DEBUG_PREFERRED || debug) { 5163 Slog.v(TAG, "Found preferred activity:"); 5164 if (ai != null) { 5165 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5166 } else { 5167 Slog.v(TAG, " null"); 5168 } 5169 } 5170 if (ai == null) { 5171 // This previously registered preferred activity 5172 // component is no longer known. Most likely an update 5173 // to the app was installed and in the new version this 5174 // component no longer exists. Clean it up by removing 5175 // it from the preferred activities list, and skip it. 5176 Slog.w(TAG, "Removing dangling preferred activity: " 5177 + pa.mPref.mComponent); 5178 pir.removeFilter(pa); 5179 changed = true; 5180 continue; 5181 } 5182 for (int j=0; j<N; j++) { 5183 final ResolveInfo ri = query.get(j); 5184 if (!ri.activityInfo.applicationInfo.packageName 5185 .equals(ai.applicationInfo.packageName)) { 5186 continue; 5187 } 5188 if (!ri.activityInfo.name.equals(ai.name)) { 5189 continue; 5190 } 5191 5192 if (removeMatches) { 5193 pir.removeFilter(pa); 5194 changed = true; 5195 if (DEBUG_PREFERRED) { 5196 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5197 } 5198 break; 5199 } 5200 5201 // Okay we found a previously set preferred or last chosen app. 5202 // If the result set is different from when this 5203 // was created, we need to clear it and re-ask the 5204 // user their preference, if we're looking for an "always" type entry. 5205 if (always && !pa.mPref.sameSet(query)) { 5206 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5207 + intent + " type " + resolvedType); 5208 if (DEBUG_PREFERRED) { 5209 Slog.v(TAG, "Removing preferred activity since set changed " 5210 + pa.mPref.mComponent); 5211 } 5212 pir.removeFilter(pa); 5213 // Re-add the filter as a "last chosen" entry (!always) 5214 PreferredActivity lastChosen = new PreferredActivity( 5215 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5216 pir.addFilter(lastChosen); 5217 changed = true; 5218 return null; 5219 } 5220 5221 // Yay! Either the set matched or we're looking for the last chosen 5222 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5223 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5224 return ri; 5225 } 5226 } 5227 } finally { 5228 if (changed) { 5229 if (DEBUG_PREFERRED) { 5230 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5231 } 5232 scheduleWritePackageRestrictionsLocked(userId); 5233 } 5234 } 5235 } 5236 } 5237 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5238 return null; 5239 } 5240 5241 /* 5242 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5243 */ 5244 @Override 5245 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5246 int targetUserId) { 5247 mContext.enforceCallingOrSelfPermission( 5248 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5249 List<CrossProfileIntentFilter> matches = 5250 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5251 if (matches != null) { 5252 int size = matches.size(); 5253 for (int i = 0; i < size; i++) { 5254 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5255 } 5256 } 5257 if (hasWebURI(intent)) { 5258 // cross-profile app linking works only towards the parent. 5259 final UserInfo parent = getProfileParent(sourceUserId); 5260 synchronized(mPackages) { 5261 int flags = updateFlagsForResolve(0, parent.id, intent); 5262 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5263 intent, resolvedType, flags, sourceUserId, parent.id); 5264 return xpDomainInfo != null; 5265 } 5266 } 5267 return false; 5268 } 5269 5270 private UserInfo getProfileParent(int userId) { 5271 final long identity = Binder.clearCallingIdentity(); 5272 try { 5273 return sUserManager.getProfileParent(userId); 5274 } finally { 5275 Binder.restoreCallingIdentity(identity); 5276 } 5277 } 5278 5279 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5280 String resolvedType, int userId) { 5281 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5282 if (resolver != null) { 5283 return resolver.queryIntent(intent, resolvedType, false, userId); 5284 } 5285 return null; 5286 } 5287 5288 @Override 5289 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5290 String resolvedType, int flags, int userId) { 5291 try { 5292 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5293 5294 return new ParceledListSlice<>( 5295 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5296 } finally { 5297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5298 } 5299 } 5300 5301 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5302 String resolvedType, int flags, int userId) { 5303 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5304 flags = updateFlagsForResolve(flags, userId, intent); 5305 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5306 false /* requireFullPermission */, false /* checkShell */, 5307 "query intent activities"); 5308 ComponentName comp = intent.getComponent(); 5309 if (comp == null) { 5310 if (intent.getSelector() != null) { 5311 intent = intent.getSelector(); 5312 comp = intent.getComponent(); 5313 } 5314 } 5315 5316 if (comp != null) { 5317 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5318 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5319 if (ai != null) { 5320 final ResolveInfo ri = new ResolveInfo(); 5321 ri.activityInfo = ai; 5322 list.add(ri); 5323 } 5324 return list; 5325 } 5326 5327 // reader 5328 synchronized (mPackages) { 5329 final String pkgName = intent.getPackage(); 5330 if (pkgName == null) { 5331 List<CrossProfileIntentFilter> matchingFilters = 5332 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5333 // Check for results that need to skip the current profile. 5334 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5335 resolvedType, flags, userId); 5336 if (xpResolveInfo != null) { 5337 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5338 result.add(xpResolveInfo); 5339 return filterIfNotSystemUser(result, userId); 5340 } 5341 5342 // Check for results in the current profile. 5343 List<ResolveInfo> result = mActivities.queryIntent( 5344 intent, resolvedType, flags, userId); 5345 result = filterIfNotSystemUser(result, userId); 5346 5347 // Check for cross profile results. 5348 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5349 xpResolveInfo = queryCrossProfileIntents( 5350 matchingFilters, intent, resolvedType, flags, userId, 5351 hasNonNegativePriorityResult); 5352 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5353 boolean isVisibleToUser = filterIfNotSystemUser( 5354 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5355 if (isVisibleToUser) { 5356 result.add(xpResolveInfo); 5357 Collections.sort(result, mResolvePrioritySorter); 5358 } 5359 } 5360 if (hasWebURI(intent)) { 5361 CrossProfileDomainInfo xpDomainInfo = null; 5362 final UserInfo parent = getProfileParent(userId); 5363 if (parent != null) { 5364 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5365 flags, userId, parent.id); 5366 } 5367 if (xpDomainInfo != null) { 5368 if (xpResolveInfo != null) { 5369 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5370 // in the result. 5371 result.remove(xpResolveInfo); 5372 } 5373 if (result.size() == 0) { 5374 result.add(xpDomainInfo.resolveInfo); 5375 return result; 5376 } 5377 } else if (result.size() <= 1) { 5378 return result; 5379 } 5380 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5381 xpDomainInfo, userId); 5382 Collections.sort(result, mResolvePrioritySorter); 5383 } 5384 return result; 5385 } 5386 final PackageParser.Package pkg = mPackages.get(pkgName); 5387 if (pkg != null) { 5388 return filterIfNotSystemUser( 5389 mActivities.queryIntentForPackage( 5390 intent, resolvedType, flags, pkg.activities, userId), 5391 userId); 5392 } 5393 return new ArrayList<ResolveInfo>(); 5394 } 5395 } 5396 5397 private static class CrossProfileDomainInfo { 5398 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5399 ResolveInfo resolveInfo; 5400 /* Best domain verification status of the activities found in the other profile */ 5401 int bestDomainVerificationStatus; 5402 } 5403 5404 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5405 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5406 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5407 sourceUserId)) { 5408 return null; 5409 } 5410 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5411 resolvedType, flags, parentUserId); 5412 5413 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5414 return null; 5415 } 5416 CrossProfileDomainInfo result = null; 5417 int size = resultTargetUser.size(); 5418 for (int i = 0; i < size; i++) { 5419 ResolveInfo riTargetUser = resultTargetUser.get(i); 5420 // Intent filter verification is only for filters that specify a host. So don't return 5421 // those that handle all web uris. 5422 if (riTargetUser.handleAllWebDataURI) { 5423 continue; 5424 } 5425 String packageName = riTargetUser.activityInfo.packageName; 5426 PackageSetting ps = mSettings.mPackages.get(packageName); 5427 if (ps == null) { 5428 continue; 5429 } 5430 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5431 int status = (int)(verificationState >> 32); 5432 if (result == null) { 5433 result = new CrossProfileDomainInfo(); 5434 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5435 sourceUserId, parentUserId); 5436 result.bestDomainVerificationStatus = status; 5437 } else { 5438 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5439 result.bestDomainVerificationStatus); 5440 } 5441 } 5442 // Don't consider matches with status NEVER across profiles. 5443 if (result != null && result.bestDomainVerificationStatus 5444 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5445 return null; 5446 } 5447 return result; 5448 } 5449 5450 /** 5451 * Verification statuses are ordered from the worse to the best, except for 5452 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5453 */ 5454 private int bestDomainVerificationStatus(int status1, int status2) { 5455 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5456 return status2; 5457 } 5458 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5459 return status1; 5460 } 5461 return (int) MathUtils.max(status1, status2); 5462 } 5463 5464 private boolean isUserEnabled(int userId) { 5465 long callingId = Binder.clearCallingIdentity(); 5466 try { 5467 UserInfo userInfo = sUserManager.getUserInfo(userId); 5468 return userInfo != null && userInfo.isEnabled(); 5469 } finally { 5470 Binder.restoreCallingIdentity(callingId); 5471 } 5472 } 5473 5474 /** 5475 * Filter out activities with systemUserOnly flag set, when current user is not System. 5476 * 5477 * @return filtered list 5478 */ 5479 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5480 if (userId == UserHandle.USER_SYSTEM) { 5481 return resolveInfos; 5482 } 5483 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5484 ResolveInfo info = resolveInfos.get(i); 5485 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5486 resolveInfos.remove(i); 5487 } 5488 } 5489 return resolveInfos; 5490 } 5491 5492 /** 5493 * @param resolveInfos list of resolve infos in descending priority order 5494 * @return if the list contains a resolve info with non-negative priority 5495 */ 5496 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5497 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5498 } 5499 5500 private static boolean hasWebURI(Intent intent) { 5501 if (intent.getData() == null) { 5502 return false; 5503 } 5504 final String scheme = intent.getScheme(); 5505 if (TextUtils.isEmpty(scheme)) { 5506 return false; 5507 } 5508 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5509 } 5510 5511 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5512 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5513 int userId) { 5514 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5515 5516 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5517 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5518 candidates.size()); 5519 } 5520 5521 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5522 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5523 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5524 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5525 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5526 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5527 5528 synchronized (mPackages) { 5529 final int count = candidates.size(); 5530 // First, try to use linked apps. Partition the candidates into four lists: 5531 // one for the final results, one for the "do not use ever", one for "undefined status" 5532 // and finally one for "browser app type". 5533 for (int n=0; n<count; n++) { 5534 ResolveInfo info = candidates.get(n); 5535 String packageName = info.activityInfo.packageName; 5536 PackageSetting ps = mSettings.mPackages.get(packageName); 5537 if (ps != null) { 5538 // Add to the special match all list (Browser use case) 5539 if (info.handleAllWebDataURI) { 5540 matchAllList.add(info); 5541 continue; 5542 } 5543 // Try to get the status from User settings first 5544 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5545 int status = (int)(packedStatus >> 32); 5546 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5547 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5548 if (DEBUG_DOMAIN_VERIFICATION) { 5549 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5550 + " : linkgen=" + linkGeneration); 5551 } 5552 // Use link-enabled generation as preferredOrder, i.e. 5553 // prefer newly-enabled over earlier-enabled. 5554 info.preferredOrder = linkGeneration; 5555 alwaysList.add(info); 5556 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5557 if (DEBUG_DOMAIN_VERIFICATION) { 5558 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5559 } 5560 neverList.add(info); 5561 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5562 if (DEBUG_DOMAIN_VERIFICATION) { 5563 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5564 } 5565 alwaysAskList.add(info); 5566 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5567 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5568 if (DEBUG_DOMAIN_VERIFICATION) { 5569 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5570 } 5571 undefinedList.add(info); 5572 } 5573 } 5574 } 5575 5576 // We'll want to include browser possibilities in a few cases 5577 boolean includeBrowser = false; 5578 5579 // First try to add the "always" resolution(s) for the current user, if any 5580 if (alwaysList.size() > 0) { 5581 result.addAll(alwaysList); 5582 } else { 5583 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5584 result.addAll(undefinedList); 5585 // Maybe add one for the other profile. 5586 if (xpDomainInfo != null && ( 5587 xpDomainInfo.bestDomainVerificationStatus 5588 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5589 result.add(xpDomainInfo.resolveInfo); 5590 } 5591 includeBrowser = true; 5592 } 5593 5594 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5595 // If there were 'always' entries their preferred order has been set, so we also 5596 // back that off to make the alternatives equivalent 5597 if (alwaysAskList.size() > 0) { 5598 for (ResolveInfo i : result) { 5599 i.preferredOrder = 0; 5600 } 5601 result.addAll(alwaysAskList); 5602 includeBrowser = true; 5603 } 5604 5605 if (includeBrowser) { 5606 // Also add browsers (all of them or only the default one) 5607 if (DEBUG_DOMAIN_VERIFICATION) { 5608 Slog.v(TAG, " ...including browsers in candidate set"); 5609 } 5610 if ((matchFlags & MATCH_ALL) != 0) { 5611 result.addAll(matchAllList); 5612 } else { 5613 // Browser/generic handling case. If there's a default browser, go straight 5614 // to that (but only if there is no other higher-priority match). 5615 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5616 int maxMatchPrio = 0; 5617 ResolveInfo defaultBrowserMatch = null; 5618 final int numCandidates = matchAllList.size(); 5619 for (int n = 0; n < numCandidates; n++) { 5620 ResolveInfo info = matchAllList.get(n); 5621 // track the highest overall match priority... 5622 if (info.priority > maxMatchPrio) { 5623 maxMatchPrio = info.priority; 5624 } 5625 // ...and the highest-priority default browser match 5626 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5627 if (defaultBrowserMatch == null 5628 || (defaultBrowserMatch.priority < info.priority)) { 5629 if (debug) { 5630 Slog.v(TAG, "Considering default browser match " + info); 5631 } 5632 defaultBrowserMatch = info; 5633 } 5634 } 5635 } 5636 if (defaultBrowserMatch != null 5637 && defaultBrowserMatch.priority >= maxMatchPrio 5638 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5639 { 5640 if (debug) { 5641 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5642 } 5643 result.add(defaultBrowserMatch); 5644 } else { 5645 result.addAll(matchAllList); 5646 } 5647 } 5648 5649 // If there is nothing selected, add all candidates and remove the ones that the user 5650 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5651 if (result.size() == 0) { 5652 result.addAll(candidates); 5653 result.removeAll(neverList); 5654 } 5655 } 5656 } 5657 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5658 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5659 result.size()); 5660 for (ResolveInfo info : result) { 5661 Slog.v(TAG, " + " + info.activityInfo); 5662 } 5663 } 5664 return result; 5665 } 5666 5667 // Returns a packed value as a long: 5668 // 5669 // high 'int'-sized word: link status: undefined/ask/never/always. 5670 // low 'int'-sized word: relative priority among 'always' results. 5671 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5672 long result = ps.getDomainVerificationStatusForUser(userId); 5673 // if none available, get the master status 5674 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5675 if (ps.getIntentFilterVerificationInfo() != null) { 5676 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5677 } 5678 } 5679 return result; 5680 } 5681 5682 private ResolveInfo querySkipCurrentProfileIntents( 5683 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5684 int flags, int sourceUserId) { 5685 if (matchingFilters != null) { 5686 int size = matchingFilters.size(); 5687 for (int i = 0; i < size; i ++) { 5688 CrossProfileIntentFilter filter = matchingFilters.get(i); 5689 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5690 // Checking if there are activities in the target user that can handle the 5691 // intent. 5692 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5693 resolvedType, flags, sourceUserId); 5694 if (resolveInfo != null) { 5695 return resolveInfo; 5696 } 5697 } 5698 } 5699 } 5700 return null; 5701 } 5702 5703 // Return matching ResolveInfo in target user if any. 5704 private ResolveInfo queryCrossProfileIntents( 5705 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5706 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5707 if (matchingFilters != null) { 5708 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5709 // match the same intent. For performance reasons, it is better not to 5710 // run queryIntent twice for the same userId 5711 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5712 int size = matchingFilters.size(); 5713 for (int i = 0; i < size; i++) { 5714 CrossProfileIntentFilter filter = matchingFilters.get(i); 5715 int targetUserId = filter.getTargetUserId(); 5716 boolean skipCurrentProfile = 5717 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5718 boolean skipCurrentProfileIfNoMatchFound = 5719 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5720 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5721 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5722 // Checking if there are activities in the target user that can handle the 5723 // intent. 5724 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5725 resolvedType, flags, sourceUserId); 5726 if (resolveInfo != null) return resolveInfo; 5727 alreadyTriedUserIds.put(targetUserId, true); 5728 } 5729 } 5730 } 5731 return null; 5732 } 5733 5734 /** 5735 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5736 * will forward the intent to the filter's target user. 5737 * Otherwise, returns null. 5738 */ 5739 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5740 String resolvedType, int flags, int sourceUserId) { 5741 int targetUserId = filter.getTargetUserId(); 5742 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5743 resolvedType, flags, targetUserId); 5744 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5745 // If all the matches in the target profile are suspended, return null. 5746 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5747 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5748 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5749 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5750 targetUserId); 5751 } 5752 } 5753 } 5754 return null; 5755 } 5756 5757 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5758 int sourceUserId, int targetUserId) { 5759 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5760 long ident = Binder.clearCallingIdentity(); 5761 boolean targetIsProfile; 5762 try { 5763 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5764 } finally { 5765 Binder.restoreCallingIdentity(ident); 5766 } 5767 String className; 5768 if (targetIsProfile) { 5769 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5770 } else { 5771 className = FORWARD_INTENT_TO_PARENT; 5772 } 5773 ComponentName forwardingActivityComponentName = new ComponentName( 5774 mAndroidApplication.packageName, className); 5775 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5776 sourceUserId); 5777 if (!targetIsProfile) { 5778 forwardingActivityInfo.showUserIcon = targetUserId; 5779 forwardingResolveInfo.noResourceId = true; 5780 } 5781 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5782 forwardingResolveInfo.priority = 0; 5783 forwardingResolveInfo.preferredOrder = 0; 5784 forwardingResolveInfo.match = 0; 5785 forwardingResolveInfo.isDefault = true; 5786 forwardingResolveInfo.filter = filter; 5787 forwardingResolveInfo.targetUserId = targetUserId; 5788 return forwardingResolveInfo; 5789 } 5790 5791 @Override 5792 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5793 Intent[] specifics, String[] specificTypes, Intent intent, 5794 String resolvedType, int flags, int userId) { 5795 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5796 specificTypes, intent, resolvedType, flags, userId)); 5797 } 5798 5799 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5800 Intent[] specifics, String[] specificTypes, Intent intent, 5801 String resolvedType, int flags, int userId) { 5802 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5803 flags = updateFlagsForResolve(flags, userId, intent); 5804 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5805 false /* requireFullPermission */, false /* checkShell */, 5806 "query intent activity options"); 5807 final String resultsAction = intent.getAction(); 5808 5809 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5810 | PackageManager.GET_RESOLVED_FILTER, userId); 5811 5812 if (DEBUG_INTENT_MATCHING) { 5813 Log.v(TAG, "Query " + intent + ": " + results); 5814 } 5815 5816 int specificsPos = 0; 5817 int N; 5818 5819 // todo: note that the algorithm used here is O(N^2). This 5820 // isn't a problem in our current environment, but if we start running 5821 // into situations where we have more than 5 or 10 matches then this 5822 // should probably be changed to something smarter... 5823 5824 // First we go through and resolve each of the specific items 5825 // that were supplied, taking care of removing any corresponding 5826 // duplicate items in the generic resolve list. 5827 if (specifics != null) { 5828 for (int i=0; i<specifics.length; i++) { 5829 final Intent sintent = specifics[i]; 5830 if (sintent == null) { 5831 continue; 5832 } 5833 5834 if (DEBUG_INTENT_MATCHING) { 5835 Log.v(TAG, "Specific #" + i + ": " + sintent); 5836 } 5837 5838 String action = sintent.getAction(); 5839 if (resultsAction != null && resultsAction.equals(action)) { 5840 // If this action was explicitly requested, then don't 5841 // remove things that have it. 5842 action = null; 5843 } 5844 5845 ResolveInfo ri = null; 5846 ActivityInfo ai = null; 5847 5848 ComponentName comp = sintent.getComponent(); 5849 if (comp == null) { 5850 ri = resolveIntent( 5851 sintent, 5852 specificTypes != null ? specificTypes[i] : null, 5853 flags, userId); 5854 if (ri == null) { 5855 continue; 5856 } 5857 if (ri == mResolveInfo) { 5858 // ACK! Must do something better with this. 5859 } 5860 ai = ri.activityInfo; 5861 comp = new ComponentName(ai.applicationInfo.packageName, 5862 ai.name); 5863 } else { 5864 ai = getActivityInfo(comp, flags, userId); 5865 if (ai == null) { 5866 continue; 5867 } 5868 } 5869 5870 // Look for any generic query activities that are duplicates 5871 // of this specific one, and remove them from the results. 5872 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5873 N = results.size(); 5874 int j; 5875 for (j=specificsPos; j<N; j++) { 5876 ResolveInfo sri = results.get(j); 5877 if ((sri.activityInfo.name.equals(comp.getClassName()) 5878 && sri.activityInfo.applicationInfo.packageName.equals( 5879 comp.getPackageName())) 5880 || (action != null && sri.filter.matchAction(action))) { 5881 results.remove(j); 5882 if (DEBUG_INTENT_MATCHING) Log.v( 5883 TAG, "Removing duplicate item from " + j 5884 + " due to specific " + specificsPos); 5885 if (ri == null) { 5886 ri = sri; 5887 } 5888 j--; 5889 N--; 5890 } 5891 } 5892 5893 // Add this specific item to its proper place. 5894 if (ri == null) { 5895 ri = new ResolveInfo(); 5896 ri.activityInfo = ai; 5897 } 5898 results.add(specificsPos, ri); 5899 ri.specificIndex = i; 5900 specificsPos++; 5901 } 5902 } 5903 5904 // Now we go through the remaining generic results and remove any 5905 // duplicate actions that are found here. 5906 N = results.size(); 5907 for (int i=specificsPos; i<N-1; i++) { 5908 final ResolveInfo rii = results.get(i); 5909 if (rii.filter == null) { 5910 continue; 5911 } 5912 5913 // Iterate over all of the actions of this result's intent 5914 // filter... typically this should be just one. 5915 final Iterator<String> it = rii.filter.actionsIterator(); 5916 if (it == null) { 5917 continue; 5918 } 5919 while (it.hasNext()) { 5920 final String action = it.next(); 5921 if (resultsAction != null && resultsAction.equals(action)) { 5922 // If this action was explicitly requested, then don't 5923 // remove things that have it. 5924 continue; 5925 } 5926 for (int j=i+1; j<N; j++) { 5927 final ResolveInfo rij = results.get(j); 5928 if (rij.filter != null && rij.filter.hasAction(action)) { 5929 results.remove(j); 5930 if (DEBUG_INTENT_MATCHING) Log.v( 5931 TAG, "Removing duplicate item from " + j 5932 + " due to action " + action + " at " + i); 5933 j--; 5934 N--; 5935 } 5936 } 5937 } 5938 5939 // If the caller didn't request filter information, drop it now 5940 // so we don't have to marshall/unmarshall it. 5941 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5942 rii.filter = null; 5943 } 5944 } 5945 5946 // Filter out the caller activity if so requested. 5947 if (caller != null) { 5948 N = results.size(); 5949 for (int i=0; i<N; i++) { 5950 ActivityInfo ainfo = results.get(i).activityInfo; 5951 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5952 && caller.getClassName().equals(ainfo.name)) { 5953 results.remove(i); 5954 break; 5955 } 5956 } 5957 } 5958 5959 // If the caller didn't request filter information, 5960 // drop them now so we don't have to 5961 // marshall/unmarshall it. 5962 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5963 N = results.size(); 5964 for (int i=0; i<N; i++) { 5965 results.get(i).filter = null; 5966 } 5967 } 5968 5969 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5970 return results; 5971 } 5972 5973 @Override 5974 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5975 String resolvedType, int flags, int userId) { 5976 return new ParceledListSlice<>( 5977 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5978 } 5979 5980 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5981 String resolvedType, int flags, int userId) { 5982 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5983 flags = updateFlagsForResolve(flags, userId, intent); 5984 ComponentName comp = intent.getComponent(); 5985 if (comp == null) { 5986 if (intent.getSelector() != null) { 5987 intent = intent.getSelector(); 5988 comp = intent.getComponent(); 5989 } 5990 } 5991 if (comp != null) { 5992 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5993 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5994 if (ai != null) { 5995 ResolveInfo ri = new ResolveInfo(); 5996 ri.activityInfo = ai; 5997 list.add(ri); 5998 } 5999 return list; 6000 } 6001 6002 // reader 6003 synchronized (mPackages) { 6004 String pkgName = intent.getPackage(); 6005 if (pkgName == null) { 6006 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6007 } 6008 final PackageParser.Package pkg = mPackages.get(pkgName); 6009 if (pkg != null) { 6010 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6011 userId); 6012 } 6013 return Collections.emptyList(); 6014 } 6015 } 6016 6017 @Override 6018 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6019 if (!sUserManager.exists(userId)) return null; 6020 flags = updateFlagsForResolve(flags, userId, intent); 6021 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6022 if (query != null) { 6023 if (query.size() >= 1) { 6024 // If there is more than one service with the same priority, 6025 // just arbitrarily pick the first one. 6026 return query.get(0); 6027 } 6028 } 6029 return null; 6030 } 6031 6032 @Override 6033 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6034 String resolvedType, int flags, int userId) { 6035 return new ParceledListSlice<>( 6036 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6037 } 6038 6039 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6040 String resolvedType, int flags, int userId) { 6041 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6042 flags = updateFlagsForResolve(flags, userId, intent); 6043 ComponentName comp = intent.getComponent(); 6044 if (comp == null) { 6045 if (intent.getSelector() != null) { 6046 intent = intent.getSelector(); 6047 comp = intent.getComponent(); 6048 } 6049 } 6050 if (comp != null) { 6051 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6052 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6053 if (si != null) { 6054 final ResolveInfo ri = new ResolveInfo(); 6055 ri.serviceInfo = si; 6056 list.add(ri); 6057 } 6058 return list; 6059 } 6060 6061 // reader 6062 synchronized (mPackages) { 6063 String pkgName = intent.getPackage(); 6064 if (pkgName == null) { 6065 return mServices.queryIntent(intent, resolvedType, flags, userId); 6066 } 6067 final PackageParser.Package pkg = mPackages.get(pkgName); 6068 if (pkg != null) { 6069 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6070 userId); 6071 } 6072 return Collections.emptyList(); 6073 } 6074 } 6075 6076 @Override 6077 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6078 String resolvedType, int flags, int userId) { 6079 return new ParceledListSlice<>( 6080 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6081 } 6082 6083 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6084 Intent intent, String resolvedType, int flags, int userId) { 6085 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6086 flags = updateFlagsForResolve(flags, userId, intent); 6087 ComponentName comp = intent.getComponent(); 6088 if (comp == null) { 6089 if (intent.getSelector() != null) { 6090 intent = intent.getSelector(); 6091 comp = intent.getComponent(); 6092 } 6093 } 6094 if (comp != null) { 6095 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6096 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6097 if (pi != null) { 6098 final ResolveInfo ri = new ResolveInfo(); 6099 ri.providerInfo = pi; 6100 list.add(ri); 6101 } 6102 return list; 6103 } 6104 6105 // reader 6106 synchronized (mPackages) { 6107 String pkgName = intent.getPackage(); 6108 if (pkgName == null) { 6109 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6110 } 6111 final PackageParser.Package pkg = mPackages.get(pkgName); 6112 if (pkg != null) { 6113 return mProviders.queryIntentForPackage( 6114 intent, resolvedType, flags, pkg.providers, userId); 6115 } 6116 return Collections.emptyList(); 6117 } 6118 } 6119 6120 @Override 6121 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6122 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6123 flags = updateFlagsForPackage(flags, userId, null); 6124 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6126 true /* requireFullPermission */, false /* checkShell */, 6127 "get installed packages"); 6128 6129 // writer 6130 synchronized (mPackages) { 6131 ArrayList<PackageInfo> list; 6132 if (listUninstalled) { 6133 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6134 for (PackageSetting ps : mSettings.mPackages.values()) { 6135 final PackageInfo pi; 6136 if (ps.pkg != null) { 6137 pi = generatePackageInfo(ps, flags, userId); 6138 } else { 6139 pi = generatePackageInfo(ps, flags, userId); 6140 } 6141 if (pi != null) { 6142 list.add(pi); 6143 } 6144 } 6145 } else { 6146 list = new ArrayList<PackageInfo>(mPackages.size()); 6147 for (PackageParser.Package p : mPackages.values()) { 6148 final PackageInfo pi = 6149 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6150 if (pi != null) { 6151 list.add(pi); 6152 } 6153 } 6154 } 6155 6156 return new ParceledListSlice<PackageInfo>(list); 6157 } 6158 } 6159 6160 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6161 String[] permissions, boolean[] tmp, int flags, int userId) { 6162 int numMatch = 0; 6163 final PermissionsState permissionsState = ps.getPermissionsState(); 6164 for (int i=0; i<permissions.length; i++) { 6165 final String permission = permissions[i]; 6166 if (permissionsState.hasPermission(permission, userId)) { 6167 tmp[i] = true; 6168 numMatch++; 6169 } else { 6170 tmp[i] = false; 6171 } 6172 } 6173 if (numMatch == 0) { 6174 return; 6175 } 6176 final PackageInfo pi; 6177 if (ps.pkg != null) { 6178 pi = generatePackageInfo(ps, flags, userId); 6179 } else { 6180 pi = generatePackageInfo(ps, flags, userId); 6181 } 6182 // The above might return null in cases of uninstalled apps or install-state 6183 // skew across users/profiles. 6184 if (pi != null) { 6185 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6186 if (numMatch == permissions.length) { 6187 pi.requestedPermissions = permissions; 6188 } else { 6189 pi.requestedPermissions = new String[numMatch]; 6190 numMatch = 0; 6191 for (int i=0; i<permissions.length; i++) { 6192 if (tmp[i]) { 6193 pi.requestedPermissions[numMatch] = permissions[i]; 6194 numMatch++; 6195 } 6196 } 6197 } 6198 } 6199 list.add(pi); 6200 } 6201 } 6202 6203 @Override 6204 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6205 String[] permissions, int flags, int userId) { 6206 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6207 flags = updateFlagsForPackage(flags, userId, permissions); 6208 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6209 6210 // writer 6211 synchronized (mPackages) { 6212 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6213 boolean[] tmpBools = new boolean[permissions.length]; 6214 if (listUninstalled) { 6215 for (PackageSetting ps : mSettings.mPackages.values()) { 6216 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6217 } 6218 } else { 6219 for (PackageParser.Package pkg : mPackages.values()) { 6220 PackageSetting ps = (PackageSetting)pkg.mExtras; 6221 if (ps != null) { 6222 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6223 userId); 6224 } 6225 } 6226 } 6227 6228 return new ParceledListSlice<PackageInfo>(list); 6229 } 6230 } 6231 6232 @Override 6233 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6234 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6235 flags = updateFlagsForApplication(flags, userId, null); 6236 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6237 6238 // writer 6239 synchronized (mPackages) { 6240 ArrayList<ApplicationInfo> list; 6241 if (listUninstalled) { 6242 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6243 for (PackageSetting ps : mSettings.mPackages.values()) { 6244 ApplicationInfo ai; 6245 if (ps.pkg != null) { 6246 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6247 ps.readUserState(userId), userId); 6248 } else { 6249 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6250 } 6251 if (ai != null) { 6252 list.add(ai); 6253 } 6254 } 6255 } else { 6256 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6257 for (PackageParser.Package p : mPackages.values()) { 6258 if (p.mExtras != null) { 6259 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6260 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6261 if (ai != null) { 6262 list.add(ai); 6263 } 6264 } 6265 } 6266 } 6267 6268 return new ParceledListSlice<ApplicationInfo>(list); 6269 } 6270 } 6271 6272 @Override 6273 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6274 if (DISABLE_EPHEMERAL_APPS) { 6275 return null; 6276 } 6277 6278 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6279 "getEphemeralApplications"); 6280 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6281 true /* requireFullPermission */, false /* checkShell */, 6282 "getEphemeralApplications"); 6283 synchronized (mPackages) { 6284 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6285 .getEphemeralApplicationsLPw(userId); 6286 if (ephemeralApps != null) { 6287 return new ParceledListSlice<>(ephemeralApps); 6288 } 6289 } 6290 return null; 6291 } 6292 6293 @Override 6294 public boolean isEphemeralApplication(String packageName, int userId) { 6295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6296 true /* requireFullPermission */, false /* checkShell */, 6297 "isEphemeral"); 6298 if (DISABLE_EPHEMERAL_APPS) { 6299 return false; 6300 } 6301 6302 if (!isCallerSameApp(packageName)) { 6303 return false; 6304 } 6305 synchronized (mPackages) { 6306 PackageParser.Package pkg = mPackages.get(packageName); 6307 if (pkg != null) { 6308 return pkg.applicationInfo.isEphemeralApp(); 6309 } 6310 } 6311 return false; 6312 } 6313 6314 @Override 6315 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6316 if (DISABLE_EPHEMERAL_APPS) { 6317 return null; 6318 } 6319 6320 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6321 true /* requireFullPermission */, false /* checkShell */, 6322 "getCookie"); 6323 if (!isCallerSameApp(packageName)) { 6324 return null; 6325 } 6326 synchronized (mPackages) { 6327 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6328 packageName, userId); 6329 } 6330 } 6331 6332 @Override 6333 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6334 if (DISABLE_EPHEMERAL_APPS) { 6335 return true; 6336 } 6337 6338 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6339 true /* requireFullPermission */, true /* checkShell */, 6340 "setCookie"); 6341 if (!isCallerSameApp(packageName)) { 6342 return false; 6343 } 6344 synchronized (mPackages) { 6345 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6346 packageName, cookie, userId); 6347 } 6348 } 6349 6350 @Override 6351 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6352 if (DISABLE_EPHEMERAL_APPS) { 6353 return null; 6354 } 6355 6356 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6357 "getEphemeralApplicationIcon"); 6358 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6359 true /* requireFullPermission */, false /* checkShell */, 6360 "getEphemeralApplicationIcon"); 6361 synchronized (mPackages) { 6362 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6363 packageName, userId); 6364 } 6365 } 6366 6367 private boolean isCallerSameApp(String packageName) { 6368 PackageParser.Package pkg = mPackages.get(packageName); 6369 return pkg != null 6370 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6371 } 6372 6373 @Override 6374 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6375 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6376 } 6377 6378 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6379 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6380 6381 // reader 6382 synchronized (mPackages) { 6383 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6384 final int userId = UserHandle.getCallingUserId(); 6385 while (i.hasNext()) { 6386 final PackageParser.Package p = i.next(); 6387 if (p.applicationInfo == null) continue; 6388 6389 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6390 && !p.applicationInfo.isDirectBootAware(); 6391 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6392 && p.applicationInfo.isDirectBootAware(); 6393 6394 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6395 && (!mSafeMode || isSystemApp(p)) 6396 && (matchesUnaware || matchesAware)) { 6397 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6398 if (ps != null) { 6399 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6400 ps.readUserState(userId), userId); 6401 if (ai != null) { 6402 finalList.add(ai); 6403 } 6404 } 6405 } 6406 } 6407 } 6408 6409 return finalList; 6410 } 6411 6412 @Override 6413 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6414 if (!sUserManager.exists(userId)) return null; 6415 flags = updateFlagsForComponent(flags, userId, name); 6416 // reader 6417 synchronized (mPackages) { 6418 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6419 PackageSetting ps = provider != null 6420 ? mSettings.mPackages.get(provider.owner.packageName) 6421 : null; 6422 return ps != null 6423 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6424 ? PackageParser.generateProviderInfo(provider, flags, 6425 ps.readUserState(userId), userId) 6426 : null; 6427 } 6428 } 6429 6430 /** 6431 * @deprecated 6432 */ 6433 @Deprecated 6434 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6435 // reader 6436 synchronized (mPackages) { 6437 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6438 .entrySet().iterator(); 6439 final int userId = UserHandle.getCallingUserId(); 6440 while (i.hasNext()) { 6441 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6442 PackageParser.Provider p = entry.getValue(); 6443 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6444 6445 if (ps != null && p.syncable 6446 && (!mSafeMode || (p.info.applicationInfo.flags 6447 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6448 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6449 ps.readUserState(userId), userId); 6450 if (info != null) { 6451 outNames.add(entry.getKey()); 6452 outInfo.add(info); 6453 } 6454 } 6455 } 6456 } 6457 } 6458 6459 @Override 6460 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6461 int uid, int flags) { 6462 final int userId = processName != null ? UserHandle.getUserId(uid) 6463 : UserHandle.getCallingUserId(); 6464 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6465 flags = updateFlagsForComponent(flags, userId, processName); 6466 6467 ArrayList<ProviderInfo> finalList = null; 6468 // reader 6469 synchronized (mPackages) { 6470 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6471 while (i.hasNext()) { 6472 final PackageParser.Provider p = i.next(); 6473 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6474 if (ps != null && p.info.authority != null 6475 && (processName == null 6476 || (p.info.processName.equals(processName) 6477 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6478 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6479 if (finalList == null) { 6480 finalList = new ArrayList<ProviderInfo>(3); 6481 } 6482 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6483 ps.readUserState(userId), userId); 6484 if (info != null) { 6485 finalList.add(info); 6486 } 6487 } 6488 } 6489 } 6490 6491 if (finalList != null) { 6492 Collections.sort(finalList, mProviderInitOrderSorter); 6493 return new ParceledListSlice<ProviderInfo>(finalList); 6494 } 6495 6496 return ParceledListSlice.emptyList(); 6497 } 6498 6499 @Override 6500 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6501 // reader 6502 synchronized (mPackages) { 6503 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6504 return PackageParser.generateInstrumentationInfo(i, flags); 6505 } 6506 } 6507 6508 @Override 6509 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6510 String targetPackage, int flags) { 6511 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6512 } 6513 6514 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6515 int flags) { 6516 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6517 6518 // reader 6519 synchronized (mPackages) { 6520 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6521 while (i.hasNext()) { 6522 final PackageParser.Instrumentation p = i.next(); 6523 if (targetPackage == null 6524 || targetPackage.equals(p.info.targetPackage)) { 6525 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6526 flags); 6527 if (ii != null) { 6528 finalList.add(ii); 6529 } 6530 } 6531 } 6532 } 6533 6534 return finalList; 6535 } 6536 6537 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6538 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6539 if (overlays == null) { 6540 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6541 return; 6542 } 6543 for (PackageParser.Package opkg : overlays.values()) { 6544 // Not much to do if idmap fails: we already logged the error 6545 // and we certainly don't want to abort installation of pkg simply 6546 // because an overlay didn't fit properly. For these reasons, 6547 // ignore the return value of createIdmapForPackagePairLI. 6548 createIdmapForPackagePairLI(pkg, opkg); 6549 } 6550 } 6551 6552 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6553 PackageParser.Package opkg) { 6554 if (!opkg.mTrustedOverlay) { 6555 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6556 opkg.baseCodePath + ": overlay not trusted"); 6557 return false; 6558 } 6559 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6560 if (overlaySet == null) { 6561 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6562 opkg.baseCodePath + " but target package has no known overlays"); 6563 return false; 6564 } 6565 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6566 // TODO: generate idmap for split APKs 6567 try { 6568 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6569 } catch (InstallerException e) { 6570 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6571 + opkg.baseCodePath); 6572 return false; 6573 } 6574 PackageParser.Package[] overlayArray = 6575 overlaySet.values().toArray(new PackageParser.Package[0]); 6576 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6577 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6578 return p1.mOverlayPriority - p2.mOverlayPriority; 6579 } 6580 }; 6581 Arrays.sort(overlayArray, cmp); 6582 6583 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6584 int i = 0; 6585 for (PackageParser.Package p : overlayArray) { 6586 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6587 } 6588 return true; 6589 } 6590 6591 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6593 try { 6594 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6595 } finally { 6596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6597 } 6598 } 6599 6600 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6601 final File[] files = dir.listFiles(); 6602 if (ArrayUtils.isEmpty(files)) { 6603 Log.d(TAG, "No files in app dir " + dir); 6604 return; 6605 } 6606 6607 if (DEBUG_PACKAGE_SCANNING) { 6608 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6609 + " flags=0x" + Integer.toHexString(parseFlags)); 6610 } 6611 6612 for (File file : files) { 6613 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6614 && !PackageInstallerService.isStageName(file.getName()); 6615 if (!isPackage) { 6616 // Ignore entries which are not packages 6617 continue; 6618 } 6619 try { 6620 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6621 scanFlags, currentTime, null); 6622 } catch (PackageManagerException e) { 6623 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6624 6625 // Delete invalid userdata apps 6626 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6627 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6628 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6629 removeCodePathLI(file); 6630 } 6631 } 6632 } 6633 } 6634 6635 private static File getSettingsProblemFile() { 6636 File dataDir = Environment.getDataDirectory(); 6637 File systemDir = new File(dataDir, "system"); 6638 File fname = new File(systemDir, "uiderrors.txt"); 6639 return fname; 6640 } 6641 6642 static void reportSettingsProblem(int priority, String msg) { 6643 logCriticalInfo(priority, msg); 6644 } 6645 6646 static void logCriticalInfo(int priority, String msg) { 6647 Slog.println(priority, TAG, msg); 6648 EventLogTags.writePmCriticalInfo(msg); 6649 try { 6650 File fname = getSettingsProblemFile(); 6651 FileOutputStream out = new FileOutputStream(fname, true); 6652 PrintWriter pw = new FastPrintWriter(out); 6653 SimpleDateFormat formatter = new SimpleDateFormat(); 6654 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6655 pw.println(dateString + ": " + msg); 6656 pw.close(); 6657 FileUtils.setPermissions( 6658 fname.toString(), 6659 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6660 -1, -1); 6661 } catch (java.io.IOException e) { 6662 } 6663 } 6664 6665 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6666 final int policyFlags) throws PackageManagerException { 6667 if (ps != null 6668 && ps.codePath.equals(srcFile) 6669 && ps.timeStamp == srcFile.lastModified() 6670 && !isCompatSignatureUpdateNeeded(pkg) 6671 && !isRecoverSignatureUpdateNeeded(pkg)) { 6672 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6673 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6674 ArraySet<PublicKey> signingKs; 6675 synchronized (mPackages) { 6676 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6677 } 6678 if (ps.signatures.mSignatures != null 6679 && ps.signatures.mSignatures.length != 0 6680 && signingKs != null) { 6681 // Optimization: reuse the existing cached certificates 6682 // if the package appears to be unchanged. 6683 pkg.mSignatures = ps.signatures.mSignatures; 6684 pkg.mSigningKeys = signingKs; 6685 return; 6686 } 6687 6688 Slog.w(TAG, "PackageSetting for " + ps.name 6689 + " is missing signatures. Collecting certs again to recover them."); 6690 } else { 6691 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6692 } 6693 6694 try { 6695 PackageParser.collectCertificates(pkg, policyFlags); 6696 } catch (PackageParserException e) { 6697 throw PackageManagerException.from(e); 6698 } 6699 } 6700 6701 /** 6702 * Traces a package scan. 6703 * @see #scanPackageLI(File, int, int, long, UserHandle) 6704 */ 6705 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6706 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6708 try { 6709 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6710 } finally { 6711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6712 } 6713 } 6714 6715 /** 6716 * Scans a package and returns the newly parsed package. 6717 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6718 */ 6719 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6720 long currentTime, UserHandle user) throws PackageManagerException { 6721 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6722 PackageParser pp = new PackageParser(); 6723 pp.setSeparateProcesses(mSeparateProcesses); 6724 pp.setOnlyCoreApps(mOnlyCore); 6725 pp.setDisplayMetrics(mMetrics); 6726 6727 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6728 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6729 } 6730 6731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6732 final PackageParser.Package pkg; 6733 try { 6734 pkg = pp.parsePackage(scanFile, parseFlags); 6735 } catch (PackageParserException e) { 6736 throw PackageManagerException.from(e); 6737 } finally { 6738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6739 } 6740 6741 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6742 } 6743 6744 /** 6745 * Scans a package and returns the newly parsed package. 6746 * @throws PackageManagerException on a parse error. 6747 */ 6748 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6749 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6750 throws PackageManagerException { 6751 // If the package has children and this is the first dive in the function 6752 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6753 // packages (parent and children) would be successfully scanned before the 6754 // actual scan since scanning mutates internal state and we want to atomically 6755 // install the package and its children. 6756 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6757 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6758 scanFlags |= SCAN_CHECK_ONLY; 6759 } 6760 } else { 6761 scanFlags &= ~SCAN_CHECK_ONLY; 6762 } 6763 6764 // Scan the parent 6765 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6766 scanFlags, currentTime, user); 6767 6768 // Scan the children 6769 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6770 for (int i = 0; i < childCount; i++) { 6771 PackageParser.Package childPackage = pkg.childPackages.get(i); 6772 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6773 currentTime, user); 6774 } 6775 6776 6777 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6778 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6779 } 6780 6781 return scannedPkg; 6782 } 6783 6784 /** 6785 * Scans a package and returns the newly parsed package. 6786 * @throws PackageManagerException on a parse error. 6787 */ 6788 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6789 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6790 throws PackageManagerException { 6791 PackageSetting ps = null; 6792 PackageSetting updatedPkg; 6793 // reader 6794 synchronized (mPackages) { 6795 // Look to see if we already know about this package. 6796 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6797 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6798 // This package has been renamed to its original name. Let's 6799 // use that. 6800 ps = mSettings.peekPackageLPr(oldName); 6801 } 6802 // If there was no original package, see one for the real package name. 6803 if (ps == null) { 6804 ps = mSettings.peekPackageLPr(pkg.packageName); 6805 } 6806 // Check to see if this package could be hiding/updating a system 6807 // package. Must look for it either under the original or real 6808 // package name depending on our state. 6809 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6810 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6811 6812 // If this is a package we don't know about on the system partition, we 6813 // may need to remove disabled child packages on the system partition 6814 // or may need to not add child packages if the parent apk is updated 6815 // on the data partition and no longer defines this child package. 6816 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6817 // If this is a parent package for an updated system app and this system 6818 // app got an OTA update which no longer defines some of the child packages 6819 // we have to prune them from the disabled system packages. 6820 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6821 if (disabledPs != null) { 6822 final int scannedChildCount = (pkg.childPackages != null) 6823 ? pkg.childPackages.size() : 0; 6824 final int disabledChildCount = disabledPs.childPackageNames != null 6825 ? disabledPs.childPackageNames.size() : 0; 6826 for (int i = 0; i < disabledChildCount; i++) { 6827 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6828 boolean disabledPackageAvailable = false; 6829 for (int j = 0; j < scannedChildCount; j++) { 6830 PackageParser.Package childPkg = pkg.childPackages.get(j); 6831 if (childPkg.packageName.equals(disabledChildPackageName)) { 6832 disabledPackageAvailable = true; 6833 break; 6834 } 6835 } 6836 if (!disabledPackageAvailable) { 6837 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6838 } 6839 } 6840 } 6841 } 6842 } 6843 6844 boolean updatedPkgBetter = false; 6845 // First check if this is a system package that may involve an update 6846 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6847 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6848 // it needs to drop FLAG_PRIVILEGED. 6849 if (locationIsPrivileged(scanFile)) { 6850 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6851 } else { 6852 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6853 } 6854 6855 if (ps != null && !ps.codePath.equals(scanFile)) { 6856 // The path has changed from what was last scanned... check the 6857 // version of the new path against what we have stored to determine 6858 // what to do. 6859 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6860 if (pkg.mVersionCode <= ps.versionCode) { 6861 // The system package has been updated and the code path does not match 6862 // Ignore entry. Skip it. 6863 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6864 + " ignored: updated version " + ps.versionCode 6865 + " better than this " + pkg.mVersionCode); 6866 if (!updatedPkg.codePath.equals(scanFile)) { 6867 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6868 + ps.name + " changing from " + updatedPkg.codePathString 6869 + " to " + scanFile); 6870 updatedPkg.codePath = scanFile; 6871 updatedPkg.codePathString = scanFile.toString(); 6872 updatedPkg.resourcePath = scanFile; 6873 updatedPkg.resourcePathString = scanFile.toString(); 6874 } 6875 updatedPkg.pkg = pkg; 6876 updatedPkg.versionCode = pkg.mVersionCode; 6877 6878 // Update the disabled system child packages to point to the package too. 6879 final int childCount = updatedPkg.childPackageNames != null 6880 ? updatedPkg.childPackageNames.size() : 0; 6881 for (int i = 0; i < childCount; i++) { 6882 String childPackageName = updatedPkg.childPackageNames.get(i); 6883 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6884 childPackageName); 6885 if (updatedChildPkg != null) { 6886 updatedChildPkg.pkg = pkg; 6887 updatedChildPkg.versionCode = pkg.mVersionCode; 6888 } 6889 } 6890 6891 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6892 + scanFile + " ignored: updated version " + ps.versionCode 6893 + " better than this " + pkg.mVersionCode); 6894 } else { 6895 // The current app on the system partition is better than 6896 // what we have updated to on the data partition; switch 6897 // back to the system partition version. 6898 // At this point, its safely assumed that package installation for 6899 // apps in system partition will go through. If not there won't be a working 6900 // version of the app 6901 // writer 6902 synchronized (mPackages) { 6903 // Just remove the loaded entries from package lists. 6904 mPackages.remove(ps.name); 6905 } 6906 6907 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6908 + " reverting from " + ps.codePathString 6909 + ": new version " + pkg.mVersionCode 6910 + " better than installed " + ps.versionCode); 6911 6912 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6913 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6914 synchronized (mInstallLock) { 6915 args.cleanUpResourcesLI(); 6916 } 6917 synchronized (mPackages) { 6918 mSettings.enableSystemPackageLPw(ps.name); 6919 } 6920 updatedPkgBetter = true; 6921 } 6922 } 6923 } 6924 6925 if (updatedPkg != null) { 6926 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6927 // initially 6928 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6929 6930 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6931 // flag set initially 6932 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6933 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6934 } 6935 } 6936 6937 // Verify certificates against what was last scanned 6938 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6939 6940 /* 6941 * A new system app appeared, but we already had a non-system one of the 6942 * same name installed earlier. 6943 */ 6944 boolean shouldHideSystemApp = false; 6945 if (updatedPkg == null && ps != null 6946 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6947 /* 6948 * Check to make sure the signatures match first. If they don't, 6949 * wipe the installed application and its data. 6950 */ 6951 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6952 != PackageManager.SIGNATURE_MATCH) { 6953 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6954 + " signatures don't match existing userdata copy; removing"); 6955 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6956 "scanPackageInternalLI")) { 6957 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6958 } 6959 ps = null; 6960 } else { 6961 /* 6962 * If the newly-added system app is an older version than the 6963 * already installed version, hide it. It will be scanned later 6964 * and re-added like an update. 6965 */ 6966 if (pkg.mVersionCode <= ps.versionCode) { 6967 shouldHideSystemApp = true; 6968 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6969 + " but new version " + pkg.mVersionCode + " better than installed " 6970 + ps.versionCode + "; hiding system"); 6971 } else { 6972 /* 6973 * The newly found system app is a newer version that the 6974 * one previously installed. Simply remove the 6975 * already-installed application and replace it with our own 6976 * while keeping the application data. 6977 */ 6978 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6979 + " reverting from " + ps.codePathString + ": new version " 6980 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6981 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6982 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6983 synchronized (mInstallLock) { 6984 args.cleanUpResourcesLI(); 6985 } 6986 } 6987 } 6988 } 6989 6990 // The apk is forward locked (not public) if its code and resources 6991 // are kept in different files. (except for app in either system or 6992 // vendor path). 6993 // TODO grab this value from PackageSettings 6994 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6995 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6996 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6997 } 6998 } 6999 7000 // TODO: extend to support forward-locked splits 7001 String resourcePath = null; 7002 String baseResourcePath = null; 7003 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7004 if (ps != null && ps.resourcePathString != null) { 7005 resourcePath = ps.resourcePathString; 7006 baseResourcePath = ps.resourcePathString; 7007 } else { 7008 // Should not happen at all. Just log an error. 7009 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7010 } 7011 } else { 7012 resourcePath = pkg.codePath; 7013 baseResourcePath = pkg.baseCodePath; 7014 } 7015 7016 // Set application objects path explicitly. 7017 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7018 pkg.setApplicationInfoCodePath(pkg.codePath); 7019 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7020 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7021 pkg.setApplicationInfoResourcePath(resourcePath); 7022 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7023 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7024 7025 // Note that we invoke the following method only if we are about to unpack an application 7026 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7027 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7028 7029 /* 7030 * If the system app should be overridden by a previously installed 7031 * data, hide the system app now and let the /data/app scan pick it up 7032 * again. 7033 */ 7034 if (shouldHideSystemApp) { 7035 synchronized (mPackages) { 7036 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7037 } 7038 } 7039 7040 return scannedPkg; 7041 } 7042 7043 private static String fixProcessName(String defProcessName, 7044 String processName, int uid) { 7045 if (processName == null) { 7046 return defProcessName; 7047 } 7048 return processName; 7049 } 7050 7051 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7052 throws PackageManagerException { 7053 if (pkgSetting.signatures.mSignatures != null) { 7054 // Already existing package. Make sure signatures match 7055 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7056 == PackageManager.SIGNATURE_MATCH; 7057 if (!match) { 7058 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7059 == PackageManager.SIGNATURE_MATCH; 7060 } 7061 if (!match) { 7062 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7063 == PackageManager.SIGNATURE_MATCH; 7064 } 7065 if (!match) { 7066 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7067 + pkg.packageName + " signatures do not match the " 7068 + "previously installed version; ignoring!"); 7069 } 7070 } 7071 7072 // Check for shared user signatures 7073 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7074 // Already existing package. Make sure signatures match 7075 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7076 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7077 if (!match) { 7078 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7079 == PackageManager.SIGNATURE_MATCH; 7080 } 7081 if (!match) { 7082 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7083 == PackageManager.SIGNATURE_MATCH; 7084 } 7085 if (!match) { 7086 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7087 "Package " + pkg.packageName 7088 + " has no signatures that match those in shared user " 7089 + pkgSetting.sharedUser.name + "; ignoring!"); 7090 } 7091 } 7092 } 7093 7094 /** 7095 * Enforces that only the system UID or root's UID can call a method exposed 7096 * via Binder. 7097 * 7098 * @param message used as message if SecurityException is thrown 7099 * @throws SecurityException if the caller is not system or root 7100 */ 7101 private static final void enforceSystemOrRoot(String message) { 7102 final int uid = Binder.getCallingUid(); 7103 if (uid != Process.SYSTEM_UID && uid != 0) { 7104 throw new SecurityException(message); 7105 } 7106 } 7107 7108 @Override 7109 public void performFstrimIfNeeded() { 7110 enforceSystemOrRoot("Only the system can request fstrim"); 7111 7112 // Before everything else, see whether we need to fstrim. 7113 try { 7114 IMountService ms = PackageHelper.getMountService(); 7115 if (ms != null) { 7116 final boolean isUpgrade = isUpgrade(); 7117 boolean doTrim = isUpgrade; 7118 if (doTrim) { 7119 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7120 } else { 7121 final long interval = android.provider.Settings.Global.getLong( 7122 mContext.getContentResolver(), 7123 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7124 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7125 if (interval > 0) { 7126 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7127 if (timeSinceLast > interval) { 7128 doTrim = true; 7129 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7130 + "; running immediately"); 7131 } 7132 } 7133 } 7134 if (doTrim) { 7135 if (!isFirstBoot()) { 7136 try { 7137 ActivityManagerNative.getDefault().showBootMessage( 7138 mContext.getResources().getString( 7139 R.string.android_upgrading_fstrim), true); 7140 } catch (RemoteException e) { 7141 } 7142 } 7143 ms.runMaintenance(); 7144 } 7145 } else { 7146 Slog.e(TAG, "Mount service unavailable!"); 7147 } 7148 } catch (RemoteException e) { 7149 // Can't happen; MountService is local 7150 } 7151 } 7152 7153 @Override 7154 public void updatePackagesIfNeeded() { 7155 enforceSystemOrRoot("Only the system can request package update"); 7156 7157 // We need to re-extract after an OTA. 7158 boolean causeUpgrade = isUpgrade(); 7159 7160 // First boot or factory reset. 7161 // Note: we also handle devices that are upgrading to N right now as if it is their 7162 // first boot, as they do not have profile data. 7163 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7164 7165 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7166 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7167 7168 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7169 return; 7170 } 7171 7172 List<PackageParser.Package> pkgs; 7173 synchronized (mPackages) { 7174 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7175 } 7176 7177 int numberOfPackagesVisited = 0; 7178 int numberOfPackagesOptimized = 0; 7179 int numberOfPackagesSkipped = 0; 7180 int numberOfPackagesFailed = 0; 7181 final int numberOfPackagesToDexopt = pkgs.size(); 7182 final long startTime = System.nanoTime(); 7183 7184 for (PackageParser.Package pkg : pkgs) { 7185 numberOfPackagesVisited++; 7186 7187 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7188 if (DEBUG_DEXOPT) { 7189 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7190 } 7191 numberOfPackagesSkipped++; 7192 continue; 7193 } 7194 7195 if (DEBUG_DEXOPT) { 7196 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7197 numberOfPackagesToDexopt + ": " + pkg.packageName); 7198 } 7199 7200 if (mIsPreNUpgrade) { 7201 try { 7202 ActivityManagerNative.getDefault().showBootMessage( 7203 mContext.getResources().getString(R.string.android_upgrading_apk, 7204 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7205 } catch (RemoteException e) { 7206 } 7207 } 7208 7209 int dexOptStatus = performDexOptTraced(pkg.packageName, 7210 null /* instructionSet */, 7211 true /* checkProfiles */, 7212 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7213 false /* force */); 7214 switch (dexOptStatus) { 7215 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7216 numberOfPackagesOptimized++; 7217 break; 7218 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7219 numberOfPackagesSkipped++; 7220 break; 7221 case PackageDexOptimizer.DEX_OPT_FAILED: 7222 numberOfPackagesFailed++; 7223 break; 7224 default: 7225 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7226 break; 7227 } 7228 } 7229 7230 final int elapsedTime = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); 7231 MetricsLogger.action(mContext, 7232 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_DEXOPTED, numberOfPackagesOptimized); 7233 MetricsLogger.action(mContext, 7234 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_SKIPPED, numberOfPackagesSkipped); 7235 MetricsLogger.action(mContext, 7236 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_FAILED, numberOfPackagesFailed); 7237 MetricsLogger.action(mContext, 7238 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_TOTAL, getOptimizablePackages().size()); 7239 MetricsLogger.action(mContext, 7240 MetricsEvent.OPTIMIZING_APPS_TOTAL_TIME_MS, elapsedTime); 7241 } 7242 7243 @Override 7244 public void notifyPackageUse(String packageName, int reason) { 7245 synchronized (mPackages) { 7246 PackageParser.Package p = mPackages.get(packageName); 7247 if (p == null) { 7248 return; 7249 } 7250 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7251 } 7252 } 7253 7254 // TODO: this is not used nor needed. Delete it. 7255 @Override 7256 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7257 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7258 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7259 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7260 } 7261 7262 @Override 7263 public boolean performDexOpt(String packageName, String instructionSet, 7264 boolean checkProfiles, int compileReason, boolean force) { 7265 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7266 getCompilerFilterForReason(compileReason), force); 7267 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7268 } 7269 7270 @Override 7271 public boolean performDexOptMode(String packageName, String instructionSet, 7272 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7273 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7274 targetCompilerFilter, force); 7275 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7276 } 7277 7278 private int performDexOptTraced(String packageName, String instructionSet, 7279 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7281 try { 7282 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7283 targetCompilerFilter, force); 7284 } finally { 7285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7286 } 7287 } 7288 7289 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7290 // if the package can now be considered up to date for the given filter. 7291 private int performDexOptInternal(String packageName, String instructionSet, 7292 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7293 PackageParser.Package p; 7294 final String targetInstructionSet; 7295 synchronized (mPackages) { 7296 p = mPackages.get(packageName); 7297 if (p == null) { 7298 // Package could not be found. Report failure. 7299 return PackageDexOptimizer.DEX_OPT_FAILED; 7300 } 7301 mPackageUsage.write(false); 7302 7303 targetInstructionSet = instructionSet != null ? instructionSet : 7304 getPrimaryInstructionSet(p.applicationInfo); 7305 } 7306 long callingId = Binder.clearCallingIdentity(); 7307 try { 7308 synchronized (mInstallLock) { 7309 final String[] instructionSets = new String[] { targetInstructionSet }; 7310 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7311 targetCompilerFilter, force); 7312 } 7313 } finally { 7314 Binder.restoreCallingIdentity(callingId); 7315 } 7316 } 7317 7318 public ArraySet<String> getOptimizablePackages() { 7319 ArraySet<String> pkgs = new ArraySet<String>(); 7320 synchronized (mPackages) { 7321 for (PackageParser.Package p : mPackages.values()) { 7322 if (PackageDexOptimizer.canOptimizePackage(p)) { 7323 pkgs.add(p.packageName); 7324 } 7325 } 7326 } 7327 return pkgs; 7328 } 7329 7330 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7331 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7332 boolean force) { 7333 // Select the dex optimizer based on the force parameter. 7334 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7335 // allocate an object here. 7336 PackageDexOptimizer pdo = force 7337 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7338 : mPackageDexOptimizer; 7339 7340 // Optimize all dependencies first. Note: we ignore the return value and march on 7341 // on errors. 7342 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7343 if (!deps.isEmpty()) { 7344 for (PackageParser.Package depPackage : deps) { 7345 // TODO: Analyze and investigate if we (should) profile libraries. 7346 // Currently this will do a full compilation of the library by default. 7347 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7348 false /* checkProfiles */, 7349 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7350 } 7351 } 7352 7353 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7354 targetCompilerFilter); 7355 } 7356 7357 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7358 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7359 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7360 Set<String> collectedNames = new HashSet<>(); 7361 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7362 7363 retValue.remove(p); 7364 7365 return retValue; 7366 } else { 7367 return Collections.emptyList(); 7368 } 7369 } 7370 7371 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7372 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7373 if (!collectedNames.contains(p.packageName)) { 7374 collectedNames.add(p.packageName); 7375 collected.add(p); 7376 7377 if (p.usesLibraries != null) { 7378 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7379 } 7380 if (p.usesOptionalLibraries != null) { 7381 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7382 collectedNames); 7383 } 7384 } 7385 } 7386 7387 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7388 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7389 for (String libName : libs) { 7390 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7391 if (libPkg != null) { 7392 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7393 } 7394 } 7395 } 7396 7397 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7398 synchronized (mPackages) { 7399 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7400 if (lib != null && lib.apk != null) { 7401 return mPackages.get(lib.apk); 7402 } 7403 } 7404 return null; 7405 } 7406 7407 public void shutdown() { 7408 mPackageUsage.write(true); 7409 } 7410 7411 @Override 7412 public void forceDexOpt(String packageName) { 7413 enforceSystemOrRoot("forceDexOpt"); 7414 7415 PackageParser.Package pkg; 7416 synchronized (mPackages) { 7417 pkg = mPackages.get(packageName); 7418 if (pkg == null) { 7419 throw new IllegalArgumentException("Unknown package: " + packageName); 7420 } 7421 } 7422 7423 synchronized (mInstallLock) { 7424 final String[] instructionSets = new String[] { 7425 getPrimaryInstructionSet(pkg.applicationInfo) }; 7426 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7428 7429 // Whoever is calling forceDexOpt wants a fully compiled package. 7430 // Don't use profiles since that may cause compilation to be skipped. 7431 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7432 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7433 true /* force */); 7434 7435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7436 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7437 throw new IllegalStateException("Failed to dexopt: " + res); 7438 } 7439 } 7440 } 7441 7442 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7443 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7444 Slog.w(TAG, "Unable to update from " + oldPkg.name 7445 + " to " + newPkg.packageName 7446 + ": old package not in system partition"); 7447 return false; 7448 } else if (mPackages.get(oldPkg.name) != null) { 7449 Slog.w(TAG, "Unable to update from " + oldPkg.name 7450 + " to " + newPkg.packageName 7451 + ": old package still exists"); 7452 return false; 7453 } 7454 return true; 7455 } 7456 7457 void removeCodePathLI(File codePath) { 7458 if (codePath.isDirectory()) { 7459 try { 7460 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7461 } catch (InstallerException e) { 7462 Slog.w(TAG, "Failed to remove code path", e); 7463 } 7464 } else { 7465 codePath.delete(); 7466 } 7467 } 7468 7469 private int[] resolveUserIds(int userId) { 7470 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7471 } 7472 7473 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7474 if (pkg == null) { 7475 Slog.wtf(TAG, "Package was null!", new Throwable()); 7476 return; 7477 } 7478 clearAppDataLeafLIF(pkg, userId, flags); 7479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7480 for (int i = 0; i < childCount; i++) { 7481 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7482 } 7483 } 7484 7485 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7486 final PackageSetting ps; 7487 synchronized (mPackages) { 7488 ps = mSettings.mPackages.get(pkg.packageName); 7489 } 7490 for (int realUserId : resolveUserIds(userId)) { 7491 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7492 try { 7493 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7494 ceDataInode); 7495 } catch (InstallerException e) { 7496 Slog.w(TAG, String.valueOf(e)); 7497 } 7498 } 7499 } 7500 7501 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7502 if (pkg == null) { 7503 Slog.wtf(TAG, "Package was null!", new Throwable()); 7504 return; 7505 } 7506 destroyAppDataLeafLIF(pkg, userId, flags); 7507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7508 for (int i = 0; i < childCount; i++) { 7509 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7510 } 7511 } 7512 7513 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7514 final PackageSetting ps; 7515 synchronized (mPackages) { 7516 ps = mSettings.mPackages.get(pkg.packageName); 7517 } 7518 for (int realUserId : resolveUserIds(userId)) { 7519 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7520 try { 7521 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7522 ceDataInode); 7523 } catch (InstallerException e) { 7524 Slog.w(TAG, String.valueOf(e)); 7525 } 7526 } 7527 } 7528 7529 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7530 if (pkg == null) { 7531 Slog.wtf(TAG, "Package was null!", new Throwable()); 7532 return; 7533 } 7534 destroyAppProfilesLeafLIF(pkg); 7535 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7536 for (int i = 0; i < childCount; i++) { 7537 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7538 } 7539 } 7540 7541 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7542 try { 7543 mInstaller.destroyAppProfiles(pkg.packageName); 7544 } catch (InstallerException e) { 7545 Slog.w(TAG, String.valueOf(e)); 7546 } 7547 } 7548 7549 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7550 if (pkg == null) { 7551 Slog.wtf(TAG, "Package was null!", new Throwable()); 7552 return; 7553 } 7554 clearAppProfilesLeafLIF(pkg); 7555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7556 for (int i = 0; i < childCount; i++) { 7557 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7558 } 7559 } 7560 7561 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7562 try { 7563 mInstaller.clearAppProfiles(pkg.packageName); 7564 } catch (InstallerException e) { 7565 Slog.w(TAG, String.valueOf(e)); 7566 } 7567 } 7568 7569 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7570 long lastUpdateTime) { 7571 // Set parent install/update time 7572 PackageSetting ps = (PackageSetting) pkg.mExtras; 7573 if (ps != null) { 7574 ps.firstInstallTime = firstInstallTime; 7575 ps.lastUpdateTime = lastUpdateTime; 7576 } 7577 // Set children install/update time 7578 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7579 for (int i = 0; i < childCount; i++) { 7580 PackageParser.Package childPkg = pkg.childPackages.get(i); 7581 ps = (PackageSetting) childPkg.mExtras; 7582 if (ps != null) { 7583 ps.firstInstallTime = firstInstallTime; 7584 ps.lastUpdateTime = lastUpdateTime; 7585 } 7586 } 7587 } 7588 7589 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7590 PackageParser.Package changingLib) { 7591 if (file.path != null) { 7592 usesLibraryFiles.add(file.path); 7593 return; 7594 } 7595 PackageParser.Package p = mPackages.get(file.apk); 7596 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7597 // If we are doing this while in the middle of updating a library apk, 7598 // then we need to make sure to use that new apk for determining the 7599 // dependencies here. (We haven't yet finished committing the new apk 7600 // to the package manager state.) 7601 if (p == null || p.packageName.equals(changingLib.packageName)) { 7602 p = changingLib; 7603 } 7604 } 7605 if (p != null) { 7606 usesLibraryFiles.addAll(p.getAllCodePaths()); 7607 } 7608 } 7609 7610 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7611 PackageParser.Package changingLib) throws PackageManagerException { 7612 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7613 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7614 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7615 for (int i=0; i<N; i++) { 7616 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7617 if (file == null) { 7618 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7619 "Package " + pkg.packageName + " requires unavailable shared library " 7620 + pkg.usesLibraries.get(i) + "; failing!"); 7621 } 7622 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7623 } 7624 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7625 for (int i=0; i<N; i++) { 7626 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7627 if (file == null) { 7628 Slog.w(TAG, "Package " + pkg.packageName 7629 + " desires unavailable shared library " 7630 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7631 } else { 7632 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7633 } 7634 } 7635 N = usesLibraryFiles.size(); 7636 if (N > 0) { 7637 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7638 } else { 7639 pkg.usesLibraryFiles = null; 7640 } 7641 } 7642 } 7643 7644 private static boolean hasString(List<String> list, List<String> which) { 7645 if (list == null) { 7646 return false; 7647 } 7648 for (int i=list.size()-1; i>=0; i--) { 7649 for (int j=which.size()-1; j>=0; j--) { 7650 if (which.get(j).equals(list.get(i))) { 7651 return true; 7652 } 7653 } 7654 } 7655 return false; 7656 } 7657 7658 private void updateAllSharedLibrariesLPw() { 7659 for (PackageParser.Package pkg : mPackages.values()) { 7660 try { 7661 updateSharedLibrariesLPw(pkg, null); 7662 } catch (PackageManagerException e) { 7663 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7664 } 7665 } 7666 } 7667 7668 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7669 PackageParser.Package changingPkg) { 7670 ArrayList<PackageParser.Package> res = null; 7671 for (PackageParser.Package pkg : mPackages.values()) { 7672 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7673 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7674 if (res == null) { 7675 res = new ArrayList<PackageParser.Package>(); 7676 } 7677 res.add(pkg); 7678 try { 7679 updateSharedLibrariesLPw(pkg, changingPkg); 7680 } catch (PackageManagerException e) { 7681 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7682 } 7683 } 7684 } 7685 return res; 7686 } 7687 7688 /** 7689 * Derive the value of the {@code cpuAbiOverride} based on the provided 7690 * value and an optional stored value from the package settings. 7691 */ 7692 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7693 String cpuAbiOverride = null; 7694 7695 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7696 cpuAbiOverride = null; 7697 } else if (abiOverride != null) { 7698 cpuAbiOverride = abiOverride; 7699 } else if (settings != null) { 7700 cpuAbiOverride = settings.cpuAbiOverrideString; 7701 } 7702 7703 return cpuAbiOverride; 7704 } 7705 7706 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7707 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7708 throws PackageManagerException { 7709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7710 // If the package has children and this is the first dive in the function 7711 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7712 // whether all packages (parent and children) would be successfully scanned 7713 // before the actual scan since scanning mutates internal state and we want 7714 // to atomically install the package and its children. 7715 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7716 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7717 scanFlags |= SCAN_CHECK_ONLY; 7718 } 7719 } else { 7720 scanFlags &= ~SCAN_CHECK_ONLY; 7721 } 7722 7723 final PackageParser.Package scannedPkg; 7724 try { 7725 // Scan the parent 7726 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7727 // Scan the children 7728 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7729 for (int i = 0; i < childCount; i++) { 7730 PackageParser.Package childPkg = pkg.childPackages.get(i); 7731 scanPackageLI(childPkg, policyFlags, 7732 scanFlags, currentTime, user); 7733 } 7734 } finally { 7735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7736 } 7737 7738 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7739 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7740 } 7741 7742 return scannedPkg; 7743 } 7744 7745 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7746 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7747 boolean success = false; 7748 try { 7749 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7750 currentTime, user); 7751 success = true; 7752 return res; 7753 } finally { 7754 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7755 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7756 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7757 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7758 destroyAppProfilesLIF(pkg); 7759 } 7760 } 7761 } 7762 7763 /** 7764 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7765 */ 7766 private static boolean apkHasCode(String fileName) { 7767 StrictJarFile jarFile = null; 7768 try { 7769 jarFile = new StrictJarFile(fileName, 7770 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7771 return jarFile.findEntry("classes.dex") != null; 7772 } catch (IOException ignore) { 7773 } finally { 7774 try { 7775 jarFile.close(); 7776 } catch (IOException ignore) {} 7777 } 7778 return false; 7779 } 7780 7781 /** 7782 * Enforces code policy for the package. This ensures that if an APK has 7783 * declared hasCode="true" in its manifest that the APK actually contains 7784 * code. 7785 * 7786 * @throws PackageManagerException If bytecode could not be found when it should exist 7787 */ 7788 private static void enforceCodePolicy(PackageParser.Package pkg) 7789 throws PackageManagerException { 7790 final boolean shouldHaveCode = 7791 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7792 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7793 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7794 "Package " + pkg.baseCodePath + " code is missing"); 7795 } 7796 7797 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7798 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7799 final boolean splitShouldHaveCode = 7800 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7801 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7802 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7803 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7804 } 7805 } 7806 } 7807 } 7808 7809 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7810 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7811 throws PackageManagerException { 7812 final File scanFile = new File(pkg.codePath); 7813 if (pkg.applicationInfo.getCodePath() == null || 7814 pkg.applicationInfo.getResourcePath() == null) { 7815 // Bail out. The resource and code paths haven't been set. 7816 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7817 "Code and resource paths haven't been set correctly"); 7818 } 7819 7820 // Apply policy 7821 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7822 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7823 if (pkg.applicationInfo.isDirectBootAware()) { 7824 // we're direct boot aware; set for all components 7825 for (PackageParser.Service s : pkg.services) { 7826 s.info.encryptionAware = s.info.directBootAware = true; 7827 } 7828 for (PackageParser.Provider p : pkg.providers) { 7829 p.info.encryptionAware = p.info.directBootAware = true; 7830 } 7831 for (PackageParser.Activity a : pkg.activities) { 7832 a.info.encryptionAware = a.info.directBootAware = true; 7833 } 7834 for (PackageParser.Activity r : pkg.receivers) { 7835 r.info.encryptionAware = r.info.directBootAware = true; 7836 } 7837 } 7838 } else { 7839 // Only allow system apps to be flagged as core apps. 7840 pkg.coreApp = false; 7841 // clear flags not applicable to regular apps 7842 pkg.applicationInfo.privateFlags &= 7843 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7844 pkg.applicationInfo.privateFlags &= 7845 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7846 } 7847 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7848 7849 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7850 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7851 } 7852 7853 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7854 enforceCodePolicy(pkg); 7855 } 7856 7857 if (mCustomResolverComponentName != null && 7858 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7859 setUpCustomResolverActivity(pkg); 7860 } 7861 7862 if (pkg.packageName.equals("android")) { 7863 synchronized (mPackages) { 7864 if (mAndroidApplication != null) { 7865 Slog.w(TAG, "*************************************************"); 7866 Slog.w(TAG, "Core android package being redefined. Skipping."); 7867 Slog.w(TAG, " file=" + scanFile); 7868 Slog.w(TAG, "*************************************************"); 7869 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7870 "Core android package being redefined. Skipping."); 7871 } 7872 7873 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7874 // Set up information for our fall-back user intent resolution activity. 7875 mPlatformPackage = pkg; 7876 pkg.mVersionCode = mSdkVersion; 7877 mAndroidApplication = pkg.applicationInfo; 7878 7879 if (!mResolverReplaced) { 7880 mResolveActivity.applicationInfo = mAndroidApplication; 7881 mResolveActivity.name = ResolverActivity.class.getName(); 7882 mResolveActivity.packageName = mAndroidApplication.packageName; 7883 mResolveActivity.processName = "system:ui"; 7884 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7885 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7886 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7887 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7888 mResolveActivity.exported = true; 7889 mResolveActivity.enabled = true; 7890 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7891 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7892 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7893 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7894 | ActivityInfo.CONFIG_ORIENTATION 7895 | ActivityInfo.CONFIG_KEYBOARD 7896 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7897 mResolveInfo.activityInfo = mResolveActivity; 7898 mResolveInfo.priority = 0; 7899 mResolveInfo.preferredOrder = 0; 7900 mResolveInfo.match = 0; 7901 mResolveComponentName = new ComponentName( 7902 mAndroidApplication.packageName, mResolveActivity.name); 7903 } 7904 } 7905 } 7906 } 7907 7908 if (DEBUG_PACKAGE_SCANNING) { 7909 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7910 Log.d(TAG, "Scanning package " + pkg.packageName); 7911 } 7912 7913 synchronized (mPackages) { 7914 if (mPackages.containsKey(pkg.packageName) 7915 || mSharedLibraries.containsKey(pkg.packageName)) { 7916 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7917 "Application package " + pkg.packageName 7918 + " already installed. Skipping duplicate."); 7919 } 7920 7921 // If we're only installing presumed-existing packages, require that the 7922 // scanned APK is both already known and at the path previously established 7923 // for it. Previously unknown packages we pick up normally, but if we have an 7924 // a priori expectation about this package's install presence, enforce it. 7925 // With a singular exception for new system packages. When an OTA contains 7926 // a new system package, we allow the codepath to change from a system location 7927 // to the user-installed location. If we don't allow this change, any newer, 7928 // user-installed version of the application will be ignored. 7929 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7930 if (mExpectingBetter.containsKey(pkg.packageName)) { 7931 logCriticalInfo(Log.WARN, 7932 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7933 } else { 7934 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7935 if (known != null) { 7936 if (DEBUG_PACKAGE_SCANNING) { 7937 Log.d(TAG, "Examining " + pkg.codePath 7938 + " and requiring known paths " + known.codePathString 7939 + " & " + known.resourcePathString); 7940 } 7941 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7942 || !pkg.applicationInfo.getResourcePath().equals( 7943 known.resourcePathString)) { 7944 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7945 "Application package " + pkg.packageName 7946 + " found at " + pkg.applicationInfo.getCodePath() 7947 + " but expected at " + known.codePathString 7948 + "; ignoring."); 7949 } 7950 } 7951 } 7952 } 7953 } 7954 7955 // Initialize package source and resource directories 7956 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7957 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7958 7959 SharedUserSetting suid = null; 7960 PackageSetting pkgSetting = null; 7961 7962 if (!isSystemApp(pkg)) { 7963 // Only system apps can use these features. 7964 pkg.mOriginalPackages = null; 7965 pkg.mRealPackage = null; 7966 pkg.mAdoptPermissions = null; 7967 } 7968 7969 // Getting the package setting may have a side-effect, so if we 7970 // are only checking if scan would succeed, stash a copy of the 7971 // old setting to restore at the end. 7972 PackageSetting nonMutatedPs = null; 7973 7974 // writer 7975 synchronized (mPackages) { 7976 if (pkg.mSharedUserId != null) { 7977 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7978 if (suid == null) { 7979 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7980 "Creating application package " + pkg.packageName 7981 + " for shared user failed"); 7982 } 7983 if (DEBUG_PACKAGE_SCANNING) { 7984 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7985 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7986 + "): packages=" + suid.packages); 7987 } 7988 } 7989 7990 // Check if we are renaming from an original package name. 7991 PackageSetting origPackage = null; 7992 String realName = null; 7993 if (pkg.mOriginalPackages != null) { 7994 // This package may need to be renamed to a previously 7995 // installed name. Let's check on that... 7996 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7997 if (pkg.mOriginalPackages.contains(renamed)) { 7998 // This package had originally been installed as the 7999 // original name, and we have already taken care of 8000 // transitioning to the new one. Just update the new 8001 // one to continue using the old name. 8002 realName = pkg.mRealPackage; 8003 if (!pkg.packageName.equals(renamed)) { 8004 // Callers into this function may have already taken 8005 // care of renaming the package; only do it here if 8006 // it is not already done. 8007 pkg.setPackageName(renamed); 8008 } 8009 8010 } else { 8011 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8012 if ((origPackage = mSettings.peekPackageLPr( 8013 pkg.mOriginalPackages.get(i))) != null) { 8014 // We do have the package already installed under its 8015 // original name... should we use it? 8016 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8017 // New package is not compatible with original. 8018 origPackage = null; 8019 continue; 8020 } else if (origPackage.sharedUser != null) { 8021 // Make sure uid is compatible between packages. 8022 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8023 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8024 + " to " + pkg.packageName + ": old uid " 8025 + origPackage.sharedUser.name 8026 + " differs from " + pkg.mSharedUserId); 8027 origPackage = null; 8028 continue; 8029 } 8030 // TODO: Add case when shared user id is added [b/28144775] 8031 } else { 8032 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8033 + pkg.packageName + " to old name " + origPackage.name); 8034 } 8035 break; 8036 } 8037 } 8038 } 8039 } 8040 8041 if (mTransferedPackages.contains(pkg.packageName)) { 8042 Slog.w(TAG, "Package " + pkg.packageName 8043 + " was transferred to another, but its .apk remains"); 8044 } 8045 8046 // See comments in nonMutatedPs declaration 8047 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8048 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8049 if (foundPs != null) { 8050 nonMutatedPs = new PackageSetting(foundPs); 8051 } 8052 } 8053 8054 // Just create the setting, don't add it yet. For already existing packages 8055 // the PkgSetting exists already and doesn't have to be created. 8056 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8057 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8058 pkg.applicationInfo.primaryCpuAbi, 8059 pkg.applicationInfo.secondaryCpuAbi, 8060 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8061 user, false); 8062 if (pkgSetting == null) { 8063 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8064 "Creating application package " + pkg.packageName + " failed"); 8065 } 8066 8067 if (pkgSetting.origPackage != null) { 8068 // If we are first transitioning from an original package, 8069 // fix up the new package's name now. We need to do this after 8070 // looking up the package under its new name, so getPackageLP 8071 // can take care of fiddling things correctly. 8072 pkg.setPackageName(origPackage.name); 8073 8074 // File a report about this. 8075 String msg = "New package " + pkgSetting.realName 8076 + " renamed to replace old package " + pkgSetting.name; 8077 reportSettingsProblem(Log.WARN, msg); 8078 8079 // Make a note of it. 8080 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8081 mTransferedPackages.add(origPackage.name); 8082 } 8083 8084 // No longer need to retain this. 8085 pkgSetting.origPackage = null; 8086 } 8087 8088 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8089 // Make a note of it. 8090 mTransferedPackages.add(pkg.packageName); 8091 } 8092 8093 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8094 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8095 } 8096 8097 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8098 // Check all shared libraries and map to their actual file path. 8099 // We only do this here for apps not on a system dir, because those 8100 // are the only ones that can fail an install due to this. We 8101 // will take care of the system apps by updating all of their 8102 // library paths after the scan is done. 8103 updateSharedLibrariesLPw(pkg, null); 8104 } 8105 8106 if (mFoundPolicyFile) { 8107 SELinuxMMAC.assignSeinfoValue(pkg); 8108 } 8109 8110 pkg.applicationInfo.uid = pkgSetting.appId; 8111 pkg.mExtras = pkgSetting; 8112 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8113 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8114 // We just determined the app is signed correctly, so bring 8115 // over the latest parsed certs. 8116 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8117 } else { 8118 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8119 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8120 "Package " + pkg.packageName + " upgrade keys do not match the " 8121 + "previously installed version"); 8122 } else { 8123 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8124 String msg = "System package " + pkg.packageName 8125 + " signature changed; retaining data."; 8126 reportSettingsProblem(Log.WARN, msg); 8127 } 8128 } 8129 } else { 8130 try { 8131 verifySignaturesLP(pkgSetting, pkg); 8132 // We just determined the app is signed correctly, so bring 8133 // over the latest parsed certs. 8134 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8135 } catch (PackageManagerException e) { 8136 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8137 throw e; 8138 } 8139 // The signature has changed, but this package is in the system 8140 // image... let's recover! 8141 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8142 // However... if this package is part of a shared user, but it 8143 // doesn't match the signature of the shared user, let's fail. 8144 // What this means is that you can't change the signatures 8145 // associated with an overall shared user, which doesn't seem all 8146 // that unreasonable. 8147 if (pkgSetting.sharedUser != null) { 8148 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8149 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8150 throw new PackageManagerException( 8151 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8152 "Signature mismatch for shared user: " 8153 + pkgSetting.sharedUser); 8154 } 8155 } 8156 // File a report about this. 8157 String msg = "System package " + pkg.packageName 8158 + " signature changed; retaining data."; 8159 reportSettingsProblem(Log.WARN, msg); 8160 } 8161 } 8162 // Verify that this new package doesn't have any content providers 8163 // that conflict with existing packages. Only do this if the 8164 // package isn't already installed, since we don't want to break 8165 // things that are installed. 8166 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8167 final int N = pkg.providers.size(); 8168 int i; 8169 for (i=0; i<N; i++) { 8170 PackageParser.Provider p = pkg.providers.get(i); 8171 if (p.info.authority != null) { 8172 String names[] = p.info.authority.split(";"); 8173 for (int j = 0; j < names.length; j++) { 8174 if (mProvidersByAuthority.containsKey(names[j])) { 8175 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8176 final String otherPackageName = 8177 ((other != null && other.getComponentName() != null) ? 8178 other.getComponentName().getPackageName() : "?"); 8179 throw new PackageManagerException( 8180 INSTALL_FAILED_CONFLICTING_PROVIDER, 8181 "Can't install because provider name " + names[j] 8182 + " (in package " + pkg.applicationInfo.packageName 8183 + ") is already used by " + otherPackageName); 8184 } 8185 } 8186 } 8187 } 8188 } 8189 8190 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8191 // This package wants to adopt ownership of permissions from 8192 // another package. 8193 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8194 final String origName = pkg.mAdoptPermissions.get(i); 8195 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8196 if (orig != null) { 8197 if (verifyPackageUpdateLPr(orig, pkg)) { 8198 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8199 + pkg.packageName); 8200 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8201 } 8202 } 8203 } 8204 } 8205 } 8206 8207 final String pkgName = pkg.packageName; 8208 8209 final long scanFileTime = scanFile.lastModified(); 8210 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8211 pkg.applicationInfo.processName = fixProcessName( 8212 pkg.applicationInfo.packageName, 8213 pkg.applicationInfo.processName, 8214 pkg.applicationInfo.uid); 8215 8216 if (pkg != mPlatformPackage) { 8217 // Get all of our default paths setup 8218 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8219 } 8220 8221 final String path = scanFile.getPath(); 8222 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8223 8224 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8225 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8226 8227 // Some system apps still use directory structure for native libraries 8228 // in which case we might end up not detecting abi solely based on apk 8229 // structure. Try to detect abi based on directory structure. 8230 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8231 pkg.applicationInfo.primaryCpuAbi == null) { 8232 setBundledAppAbisAndRoots(pkg, pkgSetting); 8233 setNativeLibraryPaths(pkg); 8234 } 8235 8236 } else { 8237 if ((scanFlags & SCAN_MOVE) != 0) { 8238 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8239 // but we already have this packages package info in the PackageSetting. We just 8240 // use that and derive the native library path based on the new codepath. 8241 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8242 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8243 } 8244 8245 // Set native library paths again. For moves, the path will be updated based on the 8246 // ABIs we've determined above. For non-moves, the path will be updated based on the 8247 // ABIs we determined during compilation, but the path will depend on the final 8248 // package path (after the rename away from the stage path). 8249 setNativeLibraryPaths(pkg); 8250 } 8251 8252 // This is a special case for the "system" package, where the ABI is 8253 // dictated by the zygote configuration (and init.rc). We should keep track 8254 // of this ABI so that we can deal with "normal" applications that run under 8255 // the same UID correctly. 8256 if (mPlatformPackage == pkg) { 8257 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8258 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8259 } 8260 8261 // If there's a mismatch between the abi-override in the package setting 8262 // and the abiOverride specified for the install. Warn about this because we 8263 // would've already compiled the app without taking the package setting into 8264 // account. 8265 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8266 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8267 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8268 " for package " + pkg.packageName); 8269 } 8270 } 8271 8272 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8273 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8274 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8275 8276 // Copy the derived override back to the parsed package, so that we can 8277 // update the package settings accordingly. 8278 pkg.cpuAbiOverride = cpuAbiOverride; 8279 8280 if (DEBUG_ABI_SELECTION) { 8281 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8282 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8283 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8284 } 8285 8286 // Push the derived path down into PackageSettings so we know what to 8287 // clean up at uninstall time. 8288 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8289 8290 if (DEBUG_ABI_SELECTION) { 8291 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8292 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8293 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8294 } 8295 8296 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8297 // We don't do this here during boot because we can do it all 8298 // at once after scanning all existing packages. 8299 // 8300 // We also do this *before* we perform dexopt on this package, so that 8301 // we can avoid redundant dexopts, and also to make sure we've got the 8302 // code and package path correct. 8303 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8304 pkg, true /* boot complete */); 8305 } 8306 8307 if (mFactoryTest && pkg.requestedPermissions.contains( 8308 android.Manifest.permission.FACTORY_TEST)) { 8309 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8310 } 8311 8312 ArrayList<PackageParser.Package> clientLibPkgs = null; 8313 8314 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8315 if (nonMutatedPs != null) { 8316 synchronized (mPackages) { 8317 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8318 } 8319 } 8320 return pkg; 8321 } 8322 8323 // Only privileged apps and updated privileged apps can add child packages. 8324 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8325 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8326 throw new PackageManagerException("Only privileged apps and updated " 8327 + "privileged apps can add child packages. Ignoring package " 8328 + pkg.packageName); 8329 } 8330 final int childCount = pkg.childPackages.size(); 8331 for (int i = 0; i < childCount; i++) { 8332 PackageParser.Package childPkg = pkg.childPackages.get(i); 8333 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8334 childPkg.packageName)) { 8335 throw new PackageManagerException("Cannot override a child package of " 8336 + "another disabled system app. Ignoring package " + pkg.packageName); 8337 } 8338 } 8339 } 8340 8341 // writer 8342 synchronized (mPackages) { 8343 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8344 // Only system apps can add new shared libraries. 8345 if (pkg.libraryNames != null) { 8346 for (int i=0; i<pkg.libraryNames.size(); i++) { 8347 String name = pkg.libraryNames.get(i); 8348 boolean allowed = false; 8349 if (pkg.isUpdatedSystemApp()) { 8350 // New library entries can only be added through the 8351 // system image. This is important to get rid of a lot 8352 // of nasty edge cases: for example if we allowed a non- 8353 // system update of the app to add a library, then uninstalling 8354 // the update would make the library go away, and assumptions 8355 // we made such as through app install filtering would now 8356 // have allowed apps on the device which aren't compatible 8357 // with it. Better to just have the restriction here, be 8358 // conservative, and create many fewer cases that can negatively 8359 // impact the user experience. 8360 final PackageSetting sysPs = mSettings 8361 .getDisabledSystemPkgLPr(pkg.packageName); 8362 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8363 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8364 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8365 allowed = true; 8366 break; 8367 } 8368 } 8369 } 8370 } else { 8371 allowed = true; 8372 } 8373 if (allowed) { 8374 if (!mSharedLibraries.containsKey(name)) { 8375 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8376 } else if (!name.equals(pkg.packageName)) { 8377 Slog.w(TAG, "Package " + pkg.packageName + " library " 8378 + name + " already exists; skipping"); 8379 } 8380 } else { 8381 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8382 + name + " that is not declared on system image; skipping"); 8383 } 8384 } 8385 if ((scanFlags & SCAN_BOOTING) == 0) { 8386 // If we are not booting, we need to update any applications 8387 // that are clients of our shared library. If we are booting, 8388 // this will all be done once the scan is complete. 8389 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8390 } 8391 } 8392 } 8393 } 8394 8395 if ((scanFlags & SCAN_BOOTING) != 0) { 8396 // No apps can run during boot scan, so they don't need to be frozen 8397 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8398 // Caller asked to not kill app, so it's probably not frozen 8399 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8400 // Caller asked us to ignore frozen check for some reason; they 8401 // probably didn't know the package name 8402 } else { 8403 // We're doing major surgery on this package, so it better be frozen 8404 // right now to keep it from launching 8405 checkPackageFrozen(pkgName); 8406 } 8407 8408 // Also need to kill any apps that are dependent on the library. 8409 if (clientLibPkgs != null) { 8410 for (int i=0; i<clientLibPkgs.size(); i++) { 8411 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8412 killApplication(clientPkg.applicationInfo.packageName, 8413 clientPkg.applicationInfo.uid, "update lib"); 8414 } 8415 } 8416 8417 // Make sure we're not adding any bogus keyset info 8418 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8419 ksms.assertScannedPackageValid(pkg); 8420 8421 // writer 8422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8423 8424 boolean createIdmapFailed = false; 8425 synchronized (mPackages) { 8426 // We don't expect installation to fail beyond this point 8427 8428 // Add the new setting to mSettings 8429 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8430 // Add the new setting to mPackages 8431 mPackages.put(pkg.applicationInfo.packageName, pkg); 8432 // Make sure we don't accidentally delete its data. 8433 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8434 while (iter.hasNext()) { 8435 PackageCleanItem item = iter.next(); 8436 if (pkgName.equals(item.packageName)) { 8437 iter.remove(); 8438 } 8439 } 8440 8441 // Take care of first install / last update times. 8442 if (currentTime != 0) { 8443 if (pkgSetting.firstInstallTime == 0) { 8444 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8445 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8446 pkgSetting.lastUpdateTime = currentTime; 8447 } 8448 } else if (pkgSetting.firstInstallTime == 0) { 8449 // We need *something*. Take time time stamp of the file. 8450 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8451 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8452 if (scanFileTime != pkgSetting.timeStamp) { 8453 // A package on the system image has changed; consider this 8454 // to be an update. 8455 pkgSetting.lastUpdateTime = scanFileTime; 8456 } 8457 } 8458 8459 // Add the package's KeySets to the global KeySetManagerService 8460 ksms.addScannedPackageLPw(pkg); 8461 8462 int N = pkg.providers.size(); 8463 StringBuilder r = null; 8464 int i; 8465 for (i=0; i<N; i++) { 8466 PackageParser.Provider p = pkg.providers.get(i); 8467 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8468 p.info.processName, pkg.applicationInfo.uid); 8469 mProviders.addProvider(p); 8470 p.syncable = p.info.isSyncable; 8471 if (p.info.authority != null) { 8472 String names[] = p.info.authority.split(";"); 8473 p.info.authority = null; 8474 for (int j = 0; j < names.length; j++) { 8475 if (j == 1 && p.syncable) { 8476 // We only want the first authority for a provider to possibly be 8477 // syncable, so if we already added this provider using a different 8478 // authority clear the syncable flag. We copy the provider before 8479 // changing it because the mProviders object contains a reference 8480 // to a provider that we don't want to change. 8481 // Only do this for the second authority since the resulting provider 8482 // object can be the same for all future authorities for this provider. 8483 p = new PackageParser.Provider(p); 8484 p.syncable = false; 8485 } 8486 if (!mProvidersByAuthority.containsKey(names[j])) { 8487 mProvidersByAuthority.put(names[j], p); 8488 if (p.info.authority == null) { 8489 p.info.authority = names[j]; 8490 } else { 8491 p.info.authority = p.info.authority + ";" + names[j]; 8492 } 8493 if (DEBUG_PACKAGE_SCANNING) { 8494 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8495 Log.d(TAG, "Registered content provider: " + names[j] 8496 + ", className = " + p.info.name + ", isSyncable = " 8497 + p.info.isSyncable); 8498 } 8499 } else { 8500 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8501 Slog.w(TAG, "Skipping provider name " + names[j] + 8502 " (in package " + pkg.applicationInfo.packageName + 8503 "): name already used by " 8504 + ((other != null && other.getComponentName() != null) 8505 ? other.getComponentName().getPackageName() : "?")); 8506 } 8507 } 8508 } 8509 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8510 if (r == null) { 8511 r = new StringBuilder(256); 8512 } else { 8513 r.append(' '); 8514 } 8515 r.append(p.info.name); 8516 } 8517 } 8518 if (r != null) { 8519 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8520 } 8521 8522 N = pkg.services.size(); 8523 r = null; 8524 for (i=0; i<N; i++) { 8525 PackageParser.Service s = pkg.services.get(i); 8526 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8527 s.info.processName, pkg.applicationInfo.uid); 8528 mServices.addService(s); 8529 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8530 if (r == null) { 8531 r = new StringBuilder(256); 8532 } else { 8533 r.append(' '); 8534 } 8535 r.append(s.info.name); 8536 } 8537 } 8538 if (r != null) { 8539 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8540 } 8541 8542 N = pkg.receivers.size(); 8543 r = null; 8544 for (i=0; i<N; i++) { 8545 PackageParser.Activity a = pkg.receivers.get(i); 8546 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8547 a.info.processName, pkg.applicationInfo.uid); 8548 mReceivers.addActivity(a, "receiver"); 8549 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8550 if (r == null) { 8551 r = new StringBuilder(256); 8552 } else { 8553 r.append(' '); 8554 } 8555 r.append(a.info.name); 8556 } 8557 } 8558 if (r != null) { 8559 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8560 } 8561 8562 N = pkg.activities.size(); 8563 r = null; 8564 for (i=0; i<N; i++) { 8565 PackageParser.Activity a = pkg.activities.get(i); 8566 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8567 a.info.processName, pkg.applicationInfo.uid); 8568 mActivities.addActivity(a, "activity"); 8569 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8570 if (r == null) { 8571 r = new StringBuilder(256); 8572 } else { 8573 r.append(' '); 8574 } 8575 r.append(a.info.name); 8576 } 8577 } 8578 if (r != null) { 8579 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8580 } 8581 8582 N = pkg.permissionGroups.size(); 8583 r = null; 8584 for (i=0; i<N; i++) { 8585 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8586 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8587 if (cur == null) { 8588 mPermissionGroups.put(pg.info.name, pg); 8589 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8590 if (r == null) { 8591 r = new StringBuilder(256); 8592 } else { 8593 r.append(' '); 8594 } 8595 r.append(pg.info.name); 8596 } 8597 } else { 8598 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8599 + pg.info.packageName + " ignored: original from " 8600 + cur.info.packageName); 8601 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8602 if (r == null) { 8603 r = new StringBuilder(256); 8604 } else { 8605 r.append(' '); 8606 } 8607 r.append("DUP:"); 8608 r.append(pg.info.name); 8609 } 8610 } 8611 } 8612 if (r != null) { 8613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8614 } 8615 8616 N = pkg.permissions.size(); 8617 r = null; 8618 for (i=0; i<N; i++) { 8619 PackageParser.Permission p = pkg.permissions.get(i); 8620 8621 // Assume by default that we did not install this permission into the system. 8622 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8623 8624 // Now that permission groups have a special meaning, we ignore permission 8625 // groups for legacy apps to prevent unexpected behavior. In particular, 8626 // permissions for one app being granted to someone just becase they happen 8627 // to be in a group defined by another app (before this had no implications). 8628 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8629 p.group = mPermissionGroups.get(p.info.group); 8630 // Warn for a permission in an unknown group. 8631 if (p.info.group != null && p.group == null) { 8632 Slog.w(TAG, "Permission " + p.info.name + " from package " 8633 + p.info.packageName + " in an unknown group " + p.info.group); 8634 } 8635 } 8636 8637 ArrayMap<String, BasePermission> permissionMap = 8638 p.tree ? mSettings.mPermissionTrees 8639 : mSettings.mPermissions; 8640 BasePermission bp = permissionMap.get(p.info.name); 8641 8642 // Allow system apps to redefine non-system permissions 8643 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8644 final boolean currentOwnerIsSystem = (bp.perm != null 8645 && isSystemApp(bp.perm.owner)); 8646 if (isSystemApp(p.owner)) { 8647 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8648 // It's a built-in permission and no owner, take ownership now 8649 bp.packageSetting = pkgSetting; 8650 bp.perm = p; 8651 bp.uid = pkg.applicationInfo.uid; 8652 bp.sourcePackage = p.info.packageName; 8653 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8654 } else if (!currentOwnerIsSystem) { 8655 String msg = "New decl " + p.owner + " of permission " 8656 + p.info.name + " is system; overriding " + bp.sourcePackage; 8657 reportSettingsProblem(Log.WARN, msg); 8658 bp = null; 8659 } 8660 } 8661 } 8662 8663 if (bp == null) { 8664 bp = new BasePermission(p.info.name, p.info.packageName, 8665 BasePermission.TYPE_NORMAL); 8666 permissionMap.put(p.info.name, bp); 8667 } 8668 8669 if (bp.perm == null) { 8670 if (bp.sourcePackage == null 8671 || bp.sourcePackage.equals(p.info.packageName)) { 8672 BasePermission tree = findPermissionTreeLP(p.info.name); 8673 if (tree == null 8674 || tree.sourcePackage.equals(p.info.packageName)) { 8675 bp.packageSetting = pkgSetting; 8676 bp.perm = p; 8677 bp.uid = pkg.applicationInfo.uid; 8678 bp.sourcePackage = p.info.packageName; 8679 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8680 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8681 if (r == null) { 8682 r = new StringBuilder(256); 8683 } else { 8684 r.append(' '); 8685 } 8686 r.append(p.info.name); 8687 } 8688 } else { 8689 Slog.w(TAG, "Permission " + p.info.name + " from package " 8690 + p.info.packageName + " ignored: base tree " 8691 + tree.name + " is from package " 8692 + tree.sourcePackage); 8693 } 8694 } else { 8695 Slog.w(TAG, "Permission " + p.info.name + " from package " 8696 + p.info.packageName + " ignored: original from " 8697 + bp.sourcePackage); 8698 } 8699 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8700 if (r == null) { 8701 r = new StringBuilder(256); 8702 } else { 8703 r.append(' '); 8704 } 8705 r.append("DUP:"); 8706 r.append(p.info.name); 8707 } 8708 if (bp.perm == p) { 8709 bp.protectionLevel = p.info.protectionLevel; 8710 } 8711 } 8712 8713 if (r != null) { 8714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8715 } 8716 8717 N = pkg.instrumentation.size(); 8718 r = null; 8719 for (i=0; i<N; i++) { 8720 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8721 a.info.packageName = pkg.applicationInfo.packageName; 8722 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8723 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8724 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8725 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8726 a.info.dataDir = pkg.applicationInfo.dataDir; 8727 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8728 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8729 8730 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8731 // need other information about the application, like the ABI and what not ? 8732 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8733 mInstrumentation.put(a.getComponentName(), a); 8734 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8735 if (r == null) { 8736 r = new StringBuilder(256); 8737 } else { 8738 r.append(' '); 8739 } 8740 r.append(a.info.name); 8741 } 8742 } 8743 if (r != null) { 8744 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8745 } 8746 8747 if (pkg.protectedBroadcasts != null) { 8748 N = pkg.protectedBroadcasts.size(); 8749 for (i=0; i<N; i++) { 8750 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8751 } 8752 } 8753 8754 pkgSetting.setTimeStamp(scanFileTime); 8755 8756 // Create idmap files for pairs of (packages, overlay packages). 8757 // Note: "android", ie framework-res.apk, is handled by native layers. 8758 if (pkg.mOverlayTarget != null) { 8759 // This is an overlay package. 8760 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8761 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8762 mOverlays.put(pkg.mOverlayTarget, 8763 new ArrayMap<String, PackageParser.Package>()); 8764 } 8765 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8766 map.put(pkg.packageName, pkg); 8767 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8768 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8769 createIdmapFailed = true; 8770 } 8771 } 8772 } else if (mOverlays.containsKey(pkg.packageName) && 8773 !pkg.packageName.equals("android")) { 8774 // This is a regular package, with one or more known overlay packages. 8775 createIdmapsForPackageLI(pkg); 8776 } 8777 } 8778 8779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8780 8781 if (createIdmapFailed) { 8782 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8783 "scanPackageLI failed to createIdmap"); 8784 } 8785 return pkg; 8786 } 8787 8788 /** 8789 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8790 * is derived purely on the basis of the contents of {@code scanFile} and 8791 * {@code cpuAbiOverride}. 8792 * 8793 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8794 */ 8795 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8796 String cpuAbiOverride, boolean extractLibs) 8797 throws PackageManagerException { 8798 // TODO: We can probably be smarter about this stuff. For installed apps, 8799 // we can calculate this information at install time once and for all. For 8800 // system apps, we can probably assume that this information doesn't change 8801 // after the first boot scan. As things stand, we do lots of unnecessary work. 8802 8803 // Give ourselves some initial paths; we'll come back for another 8804 // pass once we've determined ABI below. 8805 setNativeLibraryPaths(pkg); 8806 8807 // We would never need to extract libs for forward-locked and external packages, 8808 // since the container service will do it for us. We shouldn't attempt to 8809 // extract libs from system app when it was not updated. 8810 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8811 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8812 extractLibs = false; 8813 } 8814 8815 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8816 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8817 8818 NativeLibraryHelper.Handle handle = null; 8819 try { 8820 handle = NativeLibraryHelper.Handle.create(pkg); 8821 // TODO(multiArch): This can be null for apps that didn't go through the 8822 // usual installation process. We can calculate it again, like we 8823 // do during install time. 8824 // 8825 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8826 // unnecessary. 8827 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8828 8829 // Null out the abis so that they can be recalculated. 8830 pkg.applicationInfo.primaryCpuAbi = null; 8831 pkg.applicationInfo.secondaryCpuAbi = null; 8832 if (isMultiArch(pkg.applicationInfo)) { 8833 // Warn if we've set an abiOverride for multi-lib packages.. 8834 // By definition, we need to copy both 32 and 64 bit libraries for 8835 // such packages. 8836 if (pkg.cpuAbiOverride != null 8837 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8838 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8839 } 8840 8841 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8842 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8843 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8844 if (extractLibs) { 8845 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8846 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8847 useIsaSpecificSubdirs); 8848 } else { 8849 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8850 } 8851 } 8852 8853 maybeThrowExceptionForMultiArchCopy( 8854 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8855 8856 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8857 if (extractLibs) { 8858 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8859 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8860 useIsaSpecificSubdirs); 8861 } else { 8862 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8863 } 8864 } 8865 8866 maybeThrowExceptionForMultiArchCopy( 8867 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8868 8869 if (abi64 >= 0) { 8870 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8871 } 8872 8873 if (abi32 >= 0) { 8874 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8875 if (abi64 >= 0) { 8876 if (pkg.use32bitAbi) { 8877 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8878 pkg.applicationInfo.primaryCpuAbi = abi; 8879 } else { 8880 pkg.applicationInfo.secondaryCpuAbi = abi; 8881 } 8882 } else { 8883 pkg.applicationInfo.primaryCpuAbi = abi; 8884 } 8885 } 8886 8887 } else { 8888 String[] abiList = (cpuAbiOverride != null) ? 8889 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8890 8891 // Enable gross and lame hacks for apps that are built with old 8892 // SDK tools. We must scan their APKs for renderscript bitcode and 8893 // not launch them if it's present. Don't bother checking on devices 8894 // that don't have 64 bit support. 8895 boolean needsRenderScriptOverride = false; 8896 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8897 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8898 abiList = Build.SUPPORTED_32_BIT_ABIS; 8899 needsRenderScriptOverride = true; 8900 } 8901 8902 final int copyRet; 8903 if (extractLibs) { 8904 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8905 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8906 } else { 8907 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8908 } 8909 8910 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8911 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8912 "Error unpackaging native libs for app, errorCode=" + copyRet); 8913 } 8914 8915 if (copyRet >= 0) { 8916 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8917 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8918 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8919 } else if (needsRenderScriptOverride) { 8920 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8921 } 8922 } 8923 } catch (IOException ioe) { 8924 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8925 } finally { 8926 IoUtils.closeQuietly(handle); 8927 } 8928 8929 // Now that we've calculated the ABIs and determined if it's an internal app, 8930 // we will go ahead and populate the nativeLibraryPath. 8931 setNativeLibraryPaths(pkg); 8932 } 8933 8934 /** 8935 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8936 * i.e, so that all packages can be run inside a single process if required. 8937 * 8938 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8939 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8940 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8941 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8942 * updating a package that belongs to a shared user. 8943 * 8944 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8945 * adds unnecessary complexity. 8946 */ 8947 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8948 PackageParser.Package scannedPackage, boolean bootComplete) { 8949 String requiredInstructionSet = null; 8950 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8951 requiredInstructionSet = VMRuntime.getInstructionSet( 8952 scannedPackage.applicationInfo.primaryCpuAbi); 8953 } 8954 8955 PackageSetting requirer = null; 8956 for (PackageSetting ps : packagesForUser) { 8957 // If packagesForUser contains scannedPackage, we skip it. This will happen 8958 // when scannedPackage is an update of an existing package. Without this check, 8959 // we will never be able to change the ABI of any package belonging to a shared 8960 // user, even if it's compatible with other packages. 8961 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8962 if (ps.primaryCpuAbiString == null) { 8963 continue; 8964 } 8965 8966 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8967 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8968 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8969 // this but there's not much we can do. 8970 String errorMessage = "Instruction set mismatch, " 8971 + ((requirer == null) ? "[caller]" : requirer) 8972 + " requires " + requiredInstructionSet + " whereas " + ps 8973 + " requires " + instructionSet; 8974 Slog.w(TAG, errorMessage); 8975 } 8976 8977 if (requiredInstructionSet == null) { 8978 requiredInstructionSet = instructionSet; 8979 requirer = ps; 8980 } 8981 } 8982 } 8983 8984 if (requiredInstructionSet != null) { 8985 String adjustedAbi; 8986 if (requirer != null) { 8987 // requirer != null implies that either scannedPackage was null or that scannedPackage 8988 // did not require an ABI, in which case we have to adjust scannedPackage to match 8989 // the ABI of the set (which is the same as requirer's ABI) 8990 adjustedAbi = requirer.primaryCpuAbiString; 8991 if (scannedPackage != null) { 8992 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8993 } 8994 } else { 8995 // requirer == null implies that we're updating all ABIs in the set to 8996 // match scannedPackage. 8997 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8998 } 8999 9000 for (PackageSetting ps : packagesForUser) { 9001 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9002 if (ps.primaryCpuAbiString != null) { 9003 continue; 9004 } 9005 9006 ps.primaryCpuAbiString = adjustedAbi; 9007 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9008 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9009 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9010 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9011 + " (requirer=" 9012 + (requirer == null ? "null" : requirer.pkg.packageName) 9013 + ", scannedPackage=" 9014 + (scannedPackage != null ? scannedPackage.packageName : "null") 9015 + ")"); 9016 try { 9017 mInstaller.rmdex(ps.codePathString, 9018 getDexCodeInstructionSet(getPreferredInstructionSet())); 9019 } catch (InstallerException ignored) { 9020 } 9021 } 9022 } 9023 } 9024 } 9025 } 9026 9027 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9028 synchronized (mPackages) { 9029 mResolverReplaced = true; 9030 // Set up information for custom user intent resolution activity. 9031 mResolveActivity.applicationInfo = pkg.applicationInfo; 9032 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9033 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9034 mResolveActivity.processName = pkg.applicationInfo.packageName; 9035 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9036 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9037 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9038 mResolveActivity.theme = 0; 9039 mResolveActivity.exported = true; 9040 mResolveActivity.enabled = true; 9041 mResolveInfo.activityInfo = mResolveActivity; 9042 mResolveInfo.priority = 0; 9043 mResolveInfo.preferredOrder = 0; 9044 mResolveInfo.match = 0; 9045 mResolveComponentName = mCustomResolverComponentName; 9046 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9047 mResolveComponentName); 9048 } 9049 } 9050 9051 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9052 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9053 9054 // Set up information for ephemeral installer activity 9055 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9056 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9057 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9058 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9059 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9060 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9061 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9062 mEphemeralInstallerActivity.theme = 0; 9063 mEphemeralInstallerActivity.exported = true; 9064 mEphemeralInstallerActivity.enabled = true; 9065 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9066 mEphemeralInstallerInfo.priority = 0; 9067 mEphemeralInstallerInfo.preferredOrder = 0; 9068 mEphemeralInstallerInfo.match = 0; 9069 9070 if (DEBUG_EPHEMERAL) { 9071 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9072 } 9073 } 9074 9075 private static String calculateBundledApkRoot(final String codePathString) { 9076 final File codePath = new File(codePathString); 9077 final File codeRoot; 9078 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9079 codeRoot = Environment.getRootDirectory(); 9080 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9081 codeRoot = Environment.getOemDirectory(); 9082 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9083 codeRoot = Environment.getVendorDirectory(); 9084 } else { 9085 // Unrecognized code path; take its top real segment as the apk root: 9086 // e.g. /something/app/blah.apk => /something 9087 try { 9088 File f = codePath.getCanonicalFile(); 9089 File parent = f.getParentFile(); // non-null because codePath is a file 9090 File tmp; 9091 while ((tmp = parent.getParentFile()) != null) { 9092 f = parent; 9093 parent = tmp; 9094 } 9095 codeRoot = f; 9096 Slog.w(TAG, "Unrecognized code path " 9097 + codePath + " - using " + codeRoot); 9098 } catch (IOException e) { 9099 // Can't canonicalize the code path -- shenanigans? 9100 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9101 return Environment.getRootDirectory().getPath(); 9102 } 9103 } 9104 return codeRoot.getPath(); 9105 } 9106 9107 /** 9108 * Derive and set the location of native libraries for the given package, 9109 * which varies depending on where and how the package was installed. 9110 */ 9111 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9112 final ApplicationInfo info = pkg.applicationInfo; 9113 final String codePath = pkg.codePath; 9114 final File codeFile = new File(codePath); 9115 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9116 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9117 9118 info.nativeLibraryRootDir = null; 9119 info.nativeLibraryRootRequiresIsa = false; 9120 info.nativeLibraryDir = null; 9121 info.secondaryNativeLibraryDir = null; 9122 9123 if (isApkFile(codeFile)) { 9124 // Monolithic install 9125 if (bundledApp) { 9126 // If "/system/lib64/apkname" exists, assume that is the per-package 9127 // native library directory to use; otherwise use "/system/lib/apkname". 9128 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9129 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9130 getPrimaryInstructionSet(info)); 9131 9132 // This is a bundled system app so choose the path based on the ABI. 9133 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9134 // is just the default path. 9135 final String apkName = deriveCodePathName(codePath); 9136 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9137 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9138 apkName).getAbsolutePath(); 9139 9140 if (info.secondaryCpuAbi != null) { 9141 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9142 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9143 secondaryLibDir, apkName).getAbsolutePath(); 9144 } 9145 } else if (asecApp) { 9146 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9147 .getAbsolutePath(); 9148 } else { 9149 final String apkName = deriveCodePathName(codePath); 9150 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9151 .getAbsolutePath(); 9152 } 9153 9154 info.nativeLibraryRootRequiresIsa = false; 9155 info.nativeLibraryDir = info.nativeLibraryRootDir; 9156 } else { 9157 // Cluster install 9158 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9159 info.nativeLibraryRootRequiresIsa = true; 9160 9161 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9162 getPrimaryInstructionSet(info)).getAbsolutePath(); 9163 9164 if (info.secondaryCpuAbi != null) { 9165 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9166 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9167 } 9168 } 9169 } 9170 9171 /** 9172 * Calculate the abis and roots for a bundled app. These can uniquely 9173 * be determined from the contents of the system partition, i.e whether 9174 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9175 * of this information, and instead assume that the system was built 9176 * sensibly. 9177 */ 9178 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9179 PackageSetting pkgSetting) { 9180 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9181 9182 // If "/system/lib64/apkname" exists, assume that is the per-package 9183 // native library directory to use; otherwise use "/system/lib/apkname". 9184 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9185 setBundledAppAbi(pkg, apkRoot, apkName); 9186 // pkgSetting might be null during rescan following uninstall of updates 9187 // to a bundled app, so accommodate that possibility. The settings in 9188 // that case will be established later from the parsed package. 9189 // 9190 // If the settings aren't null, sync them up with what we've just derived. 9191 // note that apkRoot isn't stored in the package settings. 9192 if (pkgSetting != null) { 9193 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9194 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9195 } 9196 } 9197 9198 /** 9199 * Deduces the ABI of a bundled app and sets the relevant fields on the 9200 * parsed pkg object. 9201 * 9202 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9203 * under which system libraries are installed. 9204 * @param apkName the name of the installed package. 9205 */ 9206 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9207 final File codeFile = new File(pkg.codePath); 9208 9209 final boolean has64BitLibs; 9210 final boolean has32BitLibs; 9211 if (isApkFile(codeFile)) { 9212 // Monolithic install 9213 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9214 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9215 } else { 9216 // Cluster install 9217 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9218 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9219 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9220 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9221 has64BitLibs = (new File(rootDir, isa)).exists(); 9222 } else { 9223 has64BitLibs = false; 9224 } 9225 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9226 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9227 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9228 has32BitLibs = (new File(rootDir, isa)).exists(); 9229 } else { 9230 has32BitLibs = false; 9231 } 9232 } 9233 9234 if (has64BitLibs && !has32BitLibs) { 9235 // The package has 64 bit libs, but not 32 bit libs. Its primary 9236 // ABI should be 64 bit. We can safely assume here that the bundled 9237 // native libraries correspond to the most preferred ABI in the list. 9238 9239 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9240 pkg.applicationInfo.secondaryCpuAbi = null; 9241 } else if (has32BitLibs && !has64BitLibs) { 9242 // The package has 32 bit libs but not 64 bit libs. Its primary 9243 // ABI should be 32 bit. 9244 9245 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9246 pkg.applicationInfo.secondaryCpuAbi = null; 9247 } else if (has32BitLibs && has64BitLibs) { 9248 // The application has both 64 and 32 bit bundled libraries. We check 9249 // here that the app declares multiArch support, and warn if it doesn't. 9250 // 9251 // We will be lenient here and record both ABIs. The primary will be the 9252 // ABI that's higher on the list, i.e, a device that's configured to prefer 9253 // 64 bit apps will see a 64 bit primary ABI, 9254 9255 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9256 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9257 } 9258 9259 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9260 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9261 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9262 } else { 9263 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9264 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9265 } 9266 } else { 9267 pkg.applicationInfo.primaryCpuAbi = null; 9268 pkg.applicationInfo.secondaryCpuAbi = null; 9269 } 9270 } 9271 9272 private void killApplication(String pkgName, int appId, String reason) { 9273 // Request the ActivityManager to kill the process(only for existing packages) 9274 // so that we do not end up in a confused state while the user is still using the older 9275 // version of the application while the new one gets installed. 9276 final long token = Binder.clearCallingIdentity(); 9277 try { 9278 IActivityManager am = ActivityManagerNative.getDefault(); 9279 if (am != null) { 9280 try { 9281 am.killApplicationWithAppId(pkgName, appId, reason); 9282 } catch (RemoteException e) { 9283 } 9284 } 9285 } finally { 9286 Binder.restoreCallingIdentity(token); 9287 } 9288 } 9289 9290 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9291 // Remove the parent package setting 9292 PackageSetting ps = (PackageSetting) pkg.mExtras; 9293 if (ps != null) { 9294 removePackageLI(ps, chatty); 9295 } 9296 // Remove the child package setting 9297 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9298 for (int i = 0; i < childCount; i++) { 9299 PackageParser.Package childPkg = pkg.childPackages.get(i); 9300 ps = (PackageSetting) childPkg.mExtras; 9301 if (ps != null) { 9302 removePackageLI(ps, chatty); 9303 } 9304 } 9305 } 9306 9307 void removePackageLI(PackageSetting ps, boolean chatty) { 9308 if (DEBUG_INSTALL) { 9309 if (chatty) 9310 Log.d(TAG, "Removing package " + ps.name); 9311 } 9312 9313 // writer 9314 synchronized (mPackages) { 9315 mPackages.remove(ps.name); 9316 final PackageParser.Package pkg = ps.pkg; 9317 if (pkg != null) { 9318 cleanPackageDataStructuresLILPw(pkg, chatty); 9319 } 9320 } 9321 } 9322 9323 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9324 if (DEBUG_INSTALL) { 9325 if (chatty) 9326 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9327 } 9328 9329 // writer 9330 synchronized (mPackages) { 9331 // Remove the parent package 9332 mPackages.remove(pkg.applicationInfo.packageName); 9333 cleanPackageDataStructuresLILPw(pkg, chatty); 9334 9335 // Remove the child packages 9336 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9337 for (int i = 0; i < childCount; i++) { 9338 PackageParser.Package childPkg = pkg.childPackages.get(i); 9339 mPackages.remove(childPkg.applicationInfo.packageName); 9340 cleanPackageDataStructuresLILPw(childPkg, chatty); 9341 } 9342 } 9343 } 9344 9345 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9346 int N = pkg.providers.size(); 9347 StringBuilder r = null; 9348 int i; 9349 for (i=0; i<N; i++) { 9350 PackageParser.Provider p = pkg.providers.get(i); 9351 mProviders.removeProvider(p); 9352 if (p.info.authority == null) { 9353 9354 /* There was another ContentProvider with this authority when 9355 * this app was installed so this authority is null, 9356 * Ignore it as we don't have to unregister the provider. 9357 */ 9358 continue; 9359 } 9360 String names[] = p.info.authority.split(";"); 9361 for (int j = 0; j < names.length; j++) { 9362 if (mProvidersByAuthority.get(names[j]) == p) { 9363 mProvidersByAuthority.remove(names[j]); 9364 if (DEBUG_REMOVE) { 9365 if (chatty) 9366 Log.d(TAG, "Unregistered content provider: " + names[j] 9367 + ", className = " + p.info.name + ", isSyncable = " 9368 + p.info.isSyncable); 9369 } 9370 } 9371 } 9372 if (DEBUG_REMOVE && chatty) { 9373 if (r == null) { 9374 r = new StringBuilder(256); 9375 } else { 9376 r.append(' '); 9377 } 9378 r.append(p.info.name); 9379 } 9380 } 9381 if (r != null) { 9382 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9383 } 9384 9385 N = pkg.services.size(); 9386 r = null; 9387 for (i=0; i<N; i++) { 9388 PackageParser.Service s = pkg.services.get(i); 9389 mServices.removeService(s); 9390 if (chatty) { 9391 if (r == null) { 9392 r = new StringBuilder(256); 9393 } else { 9394 r.append(' '); 9395 } 9396 r.append(s.info.name); 9397 } 9398 } 9399 if (r != null) { 9400 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9401 } 9402 9403 N = pkg.receivers.size(); 9404 r = null; 9405 for (i=0; i<N; i++) { 9406 PackageParser.Activity a = pkg.receivers.get(i); 9407 mReceivers.removeActivity(a, "receiver"); 9408 if (DEBUG_REMOVE && chatty) { 9409 if (r == null) { 9410 r = new StringBuilder(256); 9411 } else { 9412 r.append(' '); 9413 } 9414 r.append(a.info.name); 9415 } 9416 } 9417 if (r != null) { 9418 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9419 } 9420 9421 N = pkg.activities.size(); 9422 r = null; 9423 for (i=0; i<N; i++) { 9424 PackageParser.Activity a = pkg.activities.get(i); 9425 mActivities.removeActivity(a, "activity"); 9426 if (DEBUG_REMOVE && chatty) { 9427 if (r == null) { 9428 r = new StringBuilder(256); 9429 } else { 9430 r.append(' '); 9431 } 9432 r.append(a.info.name); 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9437 } 9438 9439 N = pkg.permissions.size(); 9440 r = null; 9441 for (i=0; i<N; i++) { 9442 PackageParser.Permission p = pkg.permissions.get(i); 9443 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9444 if (bp == null) { 9445 bp = mSettings.mPermissionTrees.get(p.info.name); 9446 } 9447 if (bp != null && bp.perm == p) { 9448 bp.perm = null; 9449 if (DEBUG_REMOVE && chatty) { 9450 if (r == null) { 9451 r = new StringBuilder(256); 9452 } else { 9453 r.append(' '); 9454 } 9455 r.append(p.info.name); 9456 } 9457 } 9458 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9459 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9460 if (appOpPkgs != null) { 9461 appOpPkgs.remove(pkg.packageName); 9462 } 9463 } 9464 } 9465 if (r != null) { 9466 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9467 } 9468 9469 N = pkg.requestedPermissions.size(); 9470 r = null; 9471 for (i=0; i<N; i++) { 9472 String perm = pkg.requestedPermissions.get(i); 9473 BasePermission bp = mSettings.mPermissions.get(perm); 9474 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9475 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9476 if (appOpPkgs != null) { 9477 appOpPkgs.remove(pkg.packageName); 9478 if (appOpPkgs.isEmpty()) { 9479 mAppOpPermissionPackages.remove(perm); 9480 } 9481 } 9482 } 9483 } 9484 if (r != null) { 9485 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9486 } 9487 9488 N = pkg.instrumentation.size(); 9489 r = null; 9490 for (i=0; i<N; i++) { 9491 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9492 mInstrumentation.remove(a.getComponentName()); 9493 if (DEBUG_REMOVE && chatty) { 9494 if (r == null) { 9495 r = new StringBuilder(256); 9496 } else { 9497 r.append(' '); 9498 } 9499 r.append(a.info.name); 9500 } 9501 } 9502 if (r != null) { 9503 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9504 } 9505 9506 r = null; 9507 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9508 // Only system apps can hold shared libraries. 9509 if (pkg.libraryNames != null) { 9510 for (i=0; i<pkg.libraryNames.size(); i++) { 9511 String name = pkg.libraryNames.get(i); 9512 SharedLibraryEntry cur = mSharedLibraries.get(name); 9513 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9514 mSharedLibraries.remove(name); 9515 if (DEBUG_REMOVE && chatty) { 9516 if (r == null) { 9517 r = new StringBuilder(256); 9518 } else { 9519 r.append(' '); 9520 } 9521 r.append(name); 9522 } 9523 } 9524 } 9525 } 9526 } 9527 if (r != null) { 9528 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9529 } 9530 } 9531 9532 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9533 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9534 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9535 return true; 9536 } 9537 } 9538 return false; 9539 } 9540 9541 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9542 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9543 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9544 9545 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9546 // Update the parent permissions 9547 updatePermissionsLPw(pkg.packageName, pkg, flags); 9548 // Update the child permissions 9549 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9550 for (int i = 0; i < childCount; i++) { 9551 PackageParser.Package childPkg = pkg.childPackages.get(i); 9552 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9553 } 9554 } 9555 9556 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9557 int flags) { 9558 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9559 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9560 } 9561 9562 private void updatePermissionsLPw(String changingPkg, 9563 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9564 // Make sure there are no dangling permission trees. 9565 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9566 while (it.hasNext()) { 9567 final BasePermission bp = it.next(); 9568 if (bp.packageSetting == null) { 9569 // We may not yet have parsed the package, so just see if 9570 // we still know about its settings. 9571 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9572 } 9573 if (bp.packageSetting == null) { 9574 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9575 + " from package " + bp.sourcePackage); 9576 it.remove(); 9577 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9578 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9579 Slog.i(TAG, "Removing old permission tree: " + bp.name 9580 + " from package " + bp.sourcePackage); 9581 flags |= UPDATE_PERMISSIONS_ALL; 9582 it.remove(); 9583 } 9584 } 9585 } 9586 9587 // Make sure all dynamic permissions have been assigned to a package, 9588 // and make sure there are no dangling permissions. 9589 it = mSettings.mPermissions.values().iterator(); 9590 while (it.hasNext()) { 9591 final BasePermission bp = it.next(); 9592 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9593 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9594 + bp.name + " pkg=" + bp.sourcePackage 9595 + " info=" + bp.pendingInfo); 9596 if (bp.packageSetting == null && bp.pendingInfo != null) { 9597 final BasePermission tree = findPermissionTreeLP(bp.name); 9598 if (tree != null && tree.perm != null) { 9599 bp.packageSetting = tree.packageSetting; 9600 bp.perm = new PackageParser.Permission(tree.perm.owner, 9601 new PermissionInfo(bp.pendingInfo)); 9602 bp.perm.info.packageName = tree.perm.info.packageName; 9603 bp.perm.info.name = bp.name; 9604 bp.uid = tree.uid; 9605 } 9606 } 9607 } 9608 if (bp.packageSetting == null) { 9609 // We may not yet have parsed the package, so just see if 9610 // we still know about its settings. 9611 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9612 } 9613 if (bp.packageSetting == null) { 9614 Slog.w(TAG, "Removing dangling permission: " + bp.name 9615 + " from package " + bp.sourcePackage); 9616 it.remove(); 9617 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9618 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9619 Slog.i(TAG, "Removing old permission: " + bp.name 9620 + " from package " + bp.sourcePackage); 9621 flags |= UPDATE_PERMISSIONS_ALL; 9622 it.remove(); 9623 } 9624 } 9625 } 9626 9627 // Now update the permissions for all packages, in particular 9628 // replace the granted permissions of the system packages. 9629 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9630 for (PackageParser.Package pkg : mPackages.values()) { 9631 if (pkg != pkgInfo) { 9632 // Only replace for packages on requested volume 9633 final String volumeUuid = getVolumeUuidForPackage(pkg); 9634 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9635 && Objects.equals(replaceVolumeUuid, volumeUuid); 9636 grantPermissionsLPw(pkg, replace, changingPkg); 9637 } 9638 } 9639 } 9640 9641 if (pkgInfo != null) { 9642 // Only replace for packages on requested volume 9643 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9644 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9645 && Objects.equals(replaceVolumeUuid, volumeUuid); 9646 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9647 } 9648 } 9649 9650 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9651 String packageOfInterest) { 9652 // IMPORTANT: There are two types of permissions: install and runtime. 9653 // Install time permissions are granted when the app is installed to 9654 // all device users and users added in the future. Runtime permissions 9655 // are granted at runtime explicitly to specific users. Normal and signature 9656 // protected permissions are install time permissions. Dangerous permissions 9657 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9658 // otherwise they are runtime permissions. This function does not manage 9659 // runtime permissions except for the case an app targeting Lollipop MR1 9660 // being upgraded to target a newer SDK, in which case dangerous permissions 9661 // are transformed from install time to runtime ones. 9662 9663 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9664 if (ps == null) { 9665 return; 9666 } 9667 9668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9669 9670 PermissionsState permissionsState = ps.getPermissionsState(); 9671 PermissionsState origPermissions = permissionsState; 9672 9673 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9674 9675 boolean runtimePermissionsRevoked = false; 9676 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9677 9678 boolean changedInstallPermission = false; 9679 9680 if (replace) { 9681 ps.installPermissionsFixed = false; 9682 if (!ps.isSharedUser()) { 9683 origPermissions = new PermissionsState(permissionsState); 9684 permissionsState.reset(); 9685 } else { 9686 // We need to know only about runtime permission changes since the 9687 // calling code always writes the install permissions state but 9688 // the runtime ones are written only if changed. The only cases of 9689 // changed runtime permissions here are promotion of an install to 9690 // runtime and revocation of a runtime from a shared user. 9691 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9692 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9693 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9694 runtimePermissionsRevoked = true; 9695 } 9696 } 9697 } 9698 9699 permissionsState.setGlobalGids(mGlobalGids); 9700 9701 final int N = pkg.requestedPermissions.size(); 9702 for (int i=0; i<N; i++) { 9703 final String name = pkg.requestedPermissions.get(i); 9704 final BasePermission bp = mSettings.mPermissions.get(name); 9705 9706 if (DEBUG_INSTALL) { 9707 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9708 } 9709 9710 if (bp == null || bp.packageSetting == null) { 9711 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9712 Slog.w(TAG, "Unknown permission " + name 9713 + " in package " + pkg.packageName); 9714 } 9715 continue; 9716 } 9717 9718 final String perm = bp.name; 9719 boolean allowedSig = false; 9720 int grant = GRANT_DENIED; 9721 9722 // Keep track of app op permissions. 9723 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9724 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9725 if (pkgs == null) { 9726 pkgs = new ArraySet<>(); 9727 mAppOpPermissionPackages.put(bp.name, pkgs); 9728 } 9729 pkgs.add(pkg.packageName); 9730 } 9731 9732 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9733 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9734 >= Build.VERSION_CODES.M; 9735 switch (level) { 9736 case PermissionInfo.PROTECTION_NORMAL: { 9737 // For all apps normal permissions are install time ones. 9738 grant = GRANT_INSTALL; 9739 } break; 9740 9741 case PermissionInfo.PROTECTION_DANGEROUS: { 9742 // If a permission review is required for legacy apps we represent 9743 // their permissions as always granted runtime ones since we need 9744 // to keep the review required permission flag per user while an 9745 // install permission's state is shared across all users. 9746 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9747 // For legacy apps dangerous permissions are install time ones. 9748 grant = GRANT_INSTALL; 9749 } else if (origPermissions.hasInstallPermission(bp.name)) { 9750 // For legacy apps that became modern, install becomes runtime. 9751 grant = GRANT_UPGRADE; 9752 } else if (mPromoteSystemApps 9753 && isSystemApp(ps) 9754 && mExistingSystemPackages.contains(ps.name)) { 9755 // For legacy system apps, install becomes runtime. 9756 // We cannot check hasInstallPermission() for system apps since those 9757 // permissions were granted implicitly and not persisted pre-M. 9758 grant = GRANT_UPGRADE; 9759 } else { 9760 // For modern apps keep runtime permissions unchanged. 9761 grant = GRANT_RUNTIME; 9762 } 9763 } break; 9764 9765 case PermissionInfo.PROTECTION_SIGNATURE: { 9766 // For all apps signature permissions are install time ones. 9767 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9768 if (allowedSig) { 9769 grant = GRANT_INSTALL; 9770 } 9771 } break; 9772 } 9773 9774 if (DEBUG_INSTALL) { 9775 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9776 } 9777 9778 if (grant != GRANT_DENIED) { 9779 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9780 // If this is an existing, non-system package, then 9781 // we can't add any new permissions to it. 9782 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9783 // Except... if this is a permission that was added 9784 // to the platform (note: need to only do this when 9785 // updating the platform). 9786 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9787 grant = GRANT_DENIED; 9788 } 9789 } 9790 } 9791 9792 switch (grant) { 9793 case GRANT_INSTALL: { 9794 // Revoke this as runtime permission to handle the case of 9795 // a runtime permission being downgraded to an install one. 9796 // Also in permission review mode we keep dangerous permissions 9797 // for legacy apps 9798 for (int userId : UserManagerService.getInstance().getUserIds()) { 9799 if (origPermissions.getRuntimePermissionState( 9800 bp.name, userId) != null) { 9801 // Revoke the runtime permission and clear the flags. 9802 origPermissions.revokeRuntimePermission(bp, userId); 9803 origPermissions.updatePermissionFlags(bp, userId, 9804 PackageManager.MASK_PERMISSION_FLAGS, 0); 9805 // If we revoked a permission permission, we have to write. 9806 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9807 changedRuntimePermissionUserIds, userId); 9808 } 9809 } 9810 // Grant an install permission. 9811 if (permissionsState.grantInstallPermission(bp) != 9812 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9813 changedInstallPermission = true; 9814 } 9815 } break; 9816 9817 case GRANT_RUNTIME: { 9818 // Grant previously granted runtime permissions. 9819 for (int userId : UserManagerService.getInstance().getUserIds()) { 9820 PermissionState permissionState = origPermissions 9821 .getRuntimePermissionState(bp.name, userId); 9822 int flags = permissionState != null 9823 ? permissionState.getFlags() : 0; 9824 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9825 if (permissionsState.grantRuntimePermission(bp, userId) == 9826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9827 // If we cannot put the permission as it was, we have to write. 9828 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9829 changedRuntimePermissionUserIds, userId); 9830 } 9831 // If the app supports runtime permissions no need for a review. 9832 if (Build.PERMISSIONS_REVIEW_REQUIRED 9833 && appSupportsRuntimePermissions 9834 && (flags & PackageManager 9835 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9836 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9837 // Since we changed the flags, we have to write. 9838 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9839 changedRuntimePermissionUserIds, userId); 9840 } 9841 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9842 && !appSupportsRuntimePermissions) { 9843 // For legacy apps that need a permission review, every new 9844 // runtime permission is granted but it is pending a review. 9845 // We also need to review only platform defined runtime 9846 // permissions as these are the only ones the platform knows 9847 // how to disable the API to simulate revocation as legacy 9848 // apps don't expect to run with revoked permissions. 9849 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9850 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9851 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9852 // We changed the flags, hence have to write. 9853 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9854 changedRuntimePermissionUserIds, userId); 9855 } 9856 } 9857 if (permissionsState.grantRuntimePermission(bp, userId) 9858 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9859 // We changed the permission, hence have to write. 9860 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9861 changedRuntimePermissionUserIds, userId); 9862 } 9863 } 9864 // Propagate the permission flags. 9865 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9866 } 9867 } break; 9868 9869 case GRANT_UPGRADE: { 9870 // Grant runtime permissions for a previously held install permission. 9871 PermissionState permissionState = origPermissions 9872 .getInstallPermissionState(bp.name); 9873 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9874 9875 if (origPermissions.revokeInstallPermission(bp) 9876 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9877 // We will be transferring the permission flags, so clear them. 9878 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9879 PackageManager.MASK_PERMISSION_FLAGS, 0); 9880 changedInstallPermission = true; 9881 } 9882 9883 // If the permission is not to be promoted to runtime we ignore it and 9884 // also its other flags as they are not applicable to install permissions. 9885 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9886 for (int userId : currentUserIds) { 9887 if (permissionsState.grantRuntimePermission(bp, userId) != 9888 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9889 // Transfer the permission flags. 9890 permissionsState.updatePermissionFlags(bp, userId, 9891 flags, flags); 9892 // If we granted the permission, we have to write. 9893 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9894 changedRuntimePermissionUserIds, userId); 9895 } 9896 } 9897 } 9898 } break; 9899 9900 default: { 9901 if (packageOfInterest == null 9902 || packageOfInterest.equals(pkg.packageName)) { 9903 Slog.w(TAG, "Not granting permission " + perm 9904 + " to package " + pkg.packageName 9905 + " because it was previously installed without"); 9906 } 9907 } break; 9908 } 9909 } else { 9910 if (permissionsState.revokeInstallPermission(bp) != 9911 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9912 // Also drop the permission flags. 9913 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9914 PackageManager.MASK_PERMISSION_FLAGS, 0); 9915 changedInstallPermission = true; 9916 Slog.i(TAG, "Un-granting permission " + perm 9917 + " from package " + pkg.packageName 9918 + " (protectionLevel=" + bp.protectionLevel 9919 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9920 + ")"); 9921 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9922 // Don't print warning for app op permissions, since it is fine for them 9923 // not to be granted, there is a UI for the user to decide. 9924 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9925 Slog.w(TAG, "Not granting permission " + perm 9926 + " to package " + pkg.packageName 9927 + " (protectionLevel=" + bp.protectionLevel 9928 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9929 + ")"); 9930 } 9931 } 9932 } 9933 } 9934 9935 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9936 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9937 // This is the first that we have heard about this package, so the 9938 // permissions we have now selected are fixed until explicitly 9939 // changed. 9940 ps.installPermissionsFixed = true; 9941 } 9942 9943 // Persist the runtime permissions state for users with changes. If permissions 9944 // were revoked because no app in the shared user declares them we have to 9945 // write synchronously to avoid losing runtime permissions state. 9946 for (int userId : changedRuntimePermissionUserIds) { 9947 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9948 } 9949 9950 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9951 } 9952 9953 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9954 boolean allowed = false; 9955 final int NP = PackageParser.NEW_PERMISSIONS.length; 9956 for (int ip=0; ip<NP; ip++) { 9957 final PackageParser.NewPermissionInfo npi 9958 = PackageParser.NEW_PERMISSIONS[ip]; 9959 if (npi.name.equals(perm) 9960 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9961 allowed = true; 9962 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9963 + pkg.packageName); 9964 break; 9965 } 9966 } 9967 return allowed; 9968 } 9969 9970 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9971 BasePermission bp, PermissionsState origPermissions) { 9972 boolean allowed; 9973 allowed = (compareSignatures( 9974 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9975 == PackageManager.SIGNATURE_MATCH) 9976 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9977 == PackageManager.SIGNATURE_MATCH); 9978 if (!allowed && (bp.protectionLevel 9979 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9980 if (isSystemApp(pkg)) { 9981 // For updated system applications, a system permission 9982 // is granted only if it had been defined by the original application. 9983 if (pkg.isUpdatedSystemApp()) { 9984 final PackageSetting sysPs = mSettings 9985 .getDisabledSystemPkgLPr(pkg.packageName); 9986 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9987 // If the original was granted this permission, we take 9988 // that grant decision as read and propagate it to the 9989 // update. 9990 if (sysPs.isPrivileged()) { 9991 allowed = true; 9992 } 9993 } else { 9994 // The system apk may have been updated with an older 9995 // version of the one on the data partition, but which 9996 // granted a new system permission that it didn't have 9997 // before. In this case we do want to allow the app to 9998 // now get the new permission if the ancestral apk is 9999 // privileged to get it. 10000 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10001 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10002 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10003 allowed = true; 10004 break; 10005 } 10006 } 10007 } 10008 // Also if a privileged parent package on the system image or any of 10009 // its children requested a privileged permission, the updated child 10010 // packages can also get the permission. 10011 if (pkg.parentPackage != null) { 10012 final PackageSetting disabledSysParentPs = mSettings 10013 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10014 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10015 && disabledSysParentPs.isPrivileged()) { 10016 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10017 allowed = true; 10018 } else if (disabledSysParentPs.pkg.childPackages != null) { 10019 final int count = disabledSysParentPs.pkg.childPackages.size(); 10020 for (int i = 0; i < count; i++) { 10021 PackageParser.Package disabledSysChildPkg = 10022 disabledSysParentPs.pkg.childPackages.get(i); 10023 if (isPackageRequestingPermission(disabledSysChildPkg, 10024 perm)) { 10025 allowed = true; 10026 break; 10027 } 10028 } 10029 } 10030 } 10031 } 10032 } 10033 } else { 10034 allowed = isPrivilegedApp(pkg); 10035 } 10036 } 10037 } 10038 if (!allowed) { 10039 if (!allowed && (bp.protectionLevel 10040 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10041 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10042 // If this was a previously normal/dangerous permission that got moved 10043 // to a system permission as part of the runtime permission redesign, then 10044 // we still want to blindly grant it to old apps. 10045 allowed = true; 10046 } 10047 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10048 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10049 // If this permission is to be granted to the system installer and 10050 // this app is an installer, then it gets the permission. 10051 allowed = true; 10052 } 10053 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10054 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10055 // If this permission is to be granted to the system verifier and 10056 // this app is a verifier, then it gets the permission. 10057 allowed = true; 10058 } 10059 if (!allowed && (bp.protectionLevel 10060 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10061 && isSystemApp(pkg)) { 10062 // Any pre-installed system app is allowed to get this permission. 10063 allowed = true; 10064 } 10065 if (!allowed && (bp.protectionLevel 10066 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10067 // For development permissions, a development permission 10068 // is granted only if it was already granted. 10069 allowed = origPermissions.hasInstallPermission(perm); 10070 } 10071 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10072 && pkg.packageName.equals(mSetupWizardPackage)) { 10073 // If this permission is to be granted to the system setup wizard and 10074 // this app is a setup wizard, then it gets the permission. 10075 allowed = true; 10076 } 10077 } 10078 return allowed; 10079 } 10080 10081 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10082 final int permCount = pkg.requestedPermissions.size(); 10083 for (int j = 0; j < permCount; j++) { 10084 String requestedPermission = pkg.requestedPermissions.get(j); 10085 if (permission.equals(requestedPermission)) { 10086 return true; 10087 } 10088 } 10089 return false; 10090 } 10091 10092 final class ActivityIntentResolver 10093 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10095 boolean defaultOnly, int userId) { 10096 if (!sUserManager.exists(userId)) return null; 10097 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10098 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10099 } 10100 10101 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10102 int userId) { 10103 if (!sUserManager.exists(userId)) return null; 10104 mFlags = flags; 10105 return super.queryIntent(intent, resolvedType, 10106 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10107 } 10108 10109 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10110 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10111 if (!sUserManager.exists(userId)) return null; 10112 if (packageActivities == null) { 10113 return null; 10114 } 10115 mFlags = flags; 10116 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10117 final int N = packageActivities.size(); 10118 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10119 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10120 10121 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10122 for (int i = 0; i < N; ++i) { 10123 intentFilters = packageActivities.get(i).intents; 10124 if (intentFilters != null && intentFilters.size() > 0) { 10125 PackageParser.ActivityIntentInfo[] array = 10126 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10127 intentFilters.toArray(array); 10128 listCut.add(array); 10129 } 10130 } 10131 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10132 } 10133 10134 /** 10135 * Finds a privileged activity that matches the specified activity names. 10136 */ 10137 private PackageParser.Activity findMatchingActivity( 10138 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10139 for (PackageParser.Activity sysActivity : activityList) { 10140 if (sysActivity.info.name.equals(activityInfo.name)) { 10141 return sysActivity; 10142 } 10143 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10144 return sysActivity; 10145 } 10146 if (sysActivity.info.targetActivity != null) { 10147 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10148 return sysActivity; 10149 } 10150 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10151 return sysActivity; 10152 } 10153 } 10154 } 10155 return null; 10156 } 10157 10158 public class IterGenerator<E> { 10159 public Iterator<E> generate(ActivityIntentInfo info) { 10160 return null; 10161 } 10162 } 10163 10164 public class ActionIterGenerator extends IterGenerator<String> { 10165 @Override 10166 public Iterator<String> generate(ActivityIntentInfo info) { 10167 return info.actionsIterator(); 10168 } 10169 } 10170 10171 public class CategoriesIterGenerator extends IterGenerator<String> { 10172 @Override 10173 public Iterator<String> generate(ActivityIntentInfo info) { 10174 return info.categoriesIterator(); 10175 } 10176 } 10177 10178 public class SchemesIterGenerator extends IterGenerator<String> { 10179 @Override 10180 public Iterator<String> generate(ActivityIntentInfo info) { 10181 return info.schemesIterator(); 10182 } 10183 } 10184 10185 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10186 @Override 10187 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10188 return info.authoritiesIterator(); 10189 } 10190 } 10191 10192 /** 10193 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10194 * MODIFIED. Do not pass in a list that should not be changed. 10195 */ 10196 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10197 IterGenerator<T> generator, Iterator<T> searchIterator) { 10198 // loop through the set of actions; every one must be found in the intent filter 10199 while (searchIterator.hasNext()) { 10200 // we must have at least one filter in the list to consider a match 10201 if (intentList.size() == 0) { 10202 break; 10203 } 10204 10205 final T searchAction = searchIterator.next(); 10206 10207 // loop through the set of intent filters 10208 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10209 while (intentIter.hasNext()) { 10210 final ActivityIntentInfo intentInfo = intentIter.next(); 10211 boolean selectionFound = false; 10212 10213 // loop through the intent filter's selection criteria; at least one 10214 // of them must match the searched criteria 10215 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10216 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10217 final T intentSelection = intentSelectionIter.next(); 10218 if (intentSelection != null && intentSelection.equals(searchAction)) { 10219 selectionFound = true; 10220 break; 10221 } 10222 } 10223 10224 // the selection criteria wasn't found in this filter's set; this filter 10225 // is not a potential match 10226 if (!selectionFound) { 10227 intentIter.remove(); 10228 } 10229 } 10230 } 10231 } 10232 10233 private boolean isProtectedAction(ActivityIntentInfo filter) { 10234 final Iterator<String> actionsIter = filter.actionsIterator(); 10235 while (actionsIter != null && actionsIter.hasNext()) { 10236 final String filterAction = actionsIter.next(); 10237 if (PROTECTED_ACTIONS.contains(filterAction)) { 10238 return true; 10239 } 10240 } 10241 return false; 10242 } 10243 10244 /** 10245 * Adjusts the priority of the given intent filter according to policy. 10246 * <p> 10247 * <ul> 10248 * <li>The priority for non privileged applications is capped to '0'</li> 10249 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10250 * <li>The priority for unbundled updates to privileged applications is capped to the 10251 * priority defined on the system partition</li> 10252 * </ul> 10253 * <p> 10254 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10255 * allowed to obtain any priority on any action. 10256 */ 10257 private void adjustPriority( 10258 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10259 // nothing to do; priority is fine as-is 10260 if (intent.getPriority() <= 0) { 10261 return; 10262 } 10263 10264 final ActivityInfo activityInfo = intent.activity.info; 10265 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10266 10267 final boolean privilegedApp = 10268 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10269 if (!privilegedApp) { 10270 // non-privileged applications can never define a priority >0 10271 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10272 + " package: " + applicationInfo.packageName 10273 + " activity: " + intent.activity.className 10274 + " origPrio: " + intent.getPriority()); 10275 intent.setPriority(0); 10276 return; 10277 } 10278 10279 if (systemActivities == null) { 10280 // the system package is not disabled; we're parsing the system partition 10281 if (isProtectedAction(intent)) { 10282 if (mDeferProtectedFilters) { 10283 // We can't deal with these just yet. No component should ever obtain a 10284 // >0 priority for a protected actions, with ONE exception -- the setup 10285 // wizard. The setup wizard, however, cannot be known until we're able to 10286 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10287 // until all intent filters have been processed. Chicken, meet egg. 10288 // Let the filter temporarily have a high priority and rectify the 10289 // priorities after all system packages have been scanned. 10290 mProtectedFilters.add(intent); 10291 if (DEBUG_FILTERS) { 10292 Slog.i(TAG, "Protected action; save for later;" 10293 + " package: " + applicationInfo.packageName 10294 + " activity: " + intent.activity.className 10295 + " origPrio: " + intent.getPriority()); 10296 } 10297 return; 10298 } else { 10299 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10300 Slog.i(TAG, "No setup wizard;" 10301 + " All protected intents capped to priority 0"); 10302 } 10303 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10304 if (DEBUG_FILTERS) { 10305 Slog.i(TAG, "Found setup wizard;" 10306 + " allow priority " + intent.getPriority() + ";" 10307 + " package: " + intent.activity.info.packageName 10308 + " activity: " + intent.activity.className 10309 + " priority: " + intent.getPriority()); 10310 } 10311 // setup wizard gets whatever it wants 10312 return; 10313 } 10314 Slog.w(TAG, "Protected action; cap priority to 0;" 10315 + " package: " + intent.activity.info.packageName 10316 + " activity: " + intent.activity.className 10317 + " origPrio: " + intent.getPriority()); 10318 intent.setPriority(0); 10319 return; 10320 } 10321 } 10322 // privileged apps on the system image get whatever priority they request 10323 return; 10324 } 10325 10326 // privileged app unbundled update ... try to find the same activity 10327 final PackageParser.Activity foundActivity = 10328 findMatchingActivity(systemActivities, activityInfo); 10329 if (foundActivity == null) { 10330 // this is a new activity; it cannot obtain >0 priority 10331 if (DEBUG_FILTERS) { 10332 Slog.i(TAG, "New activity; cap priority to 0;" 10333 + " package: " + applicationInfo.packageName 10334 + " activity: " + intent.activity.className 10335 + " origPrio: " + intent.getPriority()); 10336 } 10337 intent.setPriority(0); 10338 return; 10339 } 10340 10341 // found activity, now check for filter equivalence 10342 10343 // a shallow copy is enough; we modify the list, not its contents 10344 final List<ActivityIntentInfo> intentListCopy = 10345 new ArrayList<>(foundActivity.intents); 10346 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10347 10348 // find matching action subsets 10349 final Iterator<String> actionsIterator = intent.actionsIterator(); 10350 if (actionsIterator != null) { 10351 getIntentListSubset( 10352 intentListCopy, new ActionIterGenerator(), actionsIterator); 10353 if (intentListCopy.size() == 0) { 10354 // no more intents to match; we're not equivalent 10355 if (DEBUG_FILTERS) { 10356 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10357 + " package: " + applicationInfo.packageName 10358 + " activity: " + intent.activity.className 10359 + " origPrio: " + intent.getPriority()); 10360 } 10361 intent.setPriority(0); 10362 return; 10363 } 10364 } 10365 10366 // find matching category subsets 10367 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10368 if (categoriesIterator != null) { 10369 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10370 categoriesIterator); 10371 if (intentListCopy.size() == 0) { 10372 // no more intents to match; we're not equivalent 10373 if (DEBUG_FILTERS) { 10374 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10375 + " package: " + applicationInfo.packageName 10376 + " activity: " + intent.activity.className 10377 + " origPrio: " + intent.getPriority()); 10378 } 10379 intent.setPriority(0); 10380 return; 10381 } 10382 } 10383 10384 // find matching schemes subsets 10385 final Iterator<String> schemesIterator = intent.schemesIterator(); 10386 if (schemesIterator != null) { 10387 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10388 schemesIterator); 10389 if (intentListCopy.size() == 0) { 10390 // no more intents to match; we're not equivalent 10391 if (DEBUG_FILTERS) { 10392 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10393 + " package: " + applicationInfo.packageName 10394 + " activity: " + intent.activity.className 10395 + " origPrio: " + intent.getPriority()); 10396 } 10397 intent.setPriority(0); 10398 return; 10399 } 10400 } 10401 10402 // find matching authorities subsets 10403 final Iterator<IntentFilter.AuthorityEntry> 10404 authoritiesIterator = intent.authoritiesIterator(); 10405 if (authoritiesIterator != null) { 10406 getIntentListSubset(intentListCopy, 10407 new AuthoritiesIterGenerator(), 10408 authoritiesIterator); 10409 if (intentListCopy.size() == 0) { 10410 // no more intents to match; we're not equivalent 10411 if (DEBUG_FILTERS) { 10412 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10413 + " package: " + applicationInfo.packageName 10414 + " activity: " + intent.activity.className 10415 + " origPrio: " + intent.getPriority()); 10416 } 10417 intent.setPriority(0); 10418 return; 10419 } 10420 } 10421 10422 // we found matching filter(s); app gets the max priority of all intents 10423 int cappedPriority = 0; 10424 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10425 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10426 } 10427 if (intent.getPriority() > cappedPriority) { 10428 if (DEBUG_FILTERS) { 10429 Slog.i(TAG, "Found matching filter(s);" 10430 + " cap priority to " + cappedPriority + ";" 10431 + " package: " + applicationInfo.packageName 10432 + " activity: " + intent.activity.className 10433 + " origPrio: " + intent.getPriority()); 10434 } 10435 intent.setPriority(cappedPriority); 10436 return; 10437 } 10438 // all this for nothing; the requested priority was <= what was on the system 10439 } 10440 10441 public final void addActivity(PackageParser.Activity a, String type) { 10442 mActivities.put(a.getComponentName(), a); 10443 if (DEBUG_SHOW_INFO) 10444 Log.v( 10445 TAG, " " + type + " " + 10446 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10447 if (DEBUG_SHOW_INFO) 10448 Log.v(TAG, " Class=" + a.info.name); 10449 final int NI = a.intents.size(); 10450 for (int j=0; j<NI; j++) { 10451 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10452 if ("activity".equals(type)) { 10453 final PackageSetting ps = 10454 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10455 final List<PackageParser.Activity> systemActivities = 10456 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10457 adjustPriority(systemActivities, intent); 10458 } 10459 if (DEBUG_SHOW_INFO) { 10460 Log.v(TAG, " IntentFilter:"); 10461 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10462 } 10463 if (!intent.debugCheck()) { 10464 Log.w(TAG, "==> For Activity " + a.info.name); 10465 } 10466 addFilter(intent); 10467 } 10468 } 10469 10470 public final void removeActivity(PackageParser.Activity a, String type) { 10471 mActivities.remove(a.getComponentName()); 10472 if (DEBUG_SHOW_INFO) { 10473 Log.v(TAG, " " + type + " " 10474 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10475 : a.info.name) + ":"); 10476 Log.v(TAG, " Class=" + a.info.name); 10477 } 10478 final int NI = a.intents.size(); 10479 for (int j=0; j<NI; j++) { 10480 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10481 if (DEBUG_SHOW_INFO) { 10482 Log.v(TAG, " IntentFilter:"); 10483 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10484 } 10485 removeFilter(intent); 10486 } 10487 } 10488 10489 @Override 10490 protected boolean allowFilterResult( 10491 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10492 ActivityInfo filterAi = filter.activity.info; 10493 for (int i=dest.size()-1; i>=0; i--) { 10494 ActivityInfo destAi = dest.get(i).activityInfo; 10495 if (destAi.name == filterAi.name 10496 && destAi.packageName == filterAi.packageName) { 10497 return false; 10498 } 10499 } 10500 return true; 10501 } 10502 10503 @Override 10504 protected ActivityIntentInfo[] newArray(int size) { 10505 return new ActivityIntentInfo[size]; 10506 } 10507 10508 @Override 10509 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10510 if (!sUserManager.exists(userId)) return true; 10511 PackageParser.Package p = filter.activity.owner; 10512 if (p != null) { 10513 PackageSetting ps = (PackageSetting)p.mExtras; 10514 if (ps != null) { 10515 // System apps are never considered stopped for purposes of 10516 // filtering, because there may be no way for the user to 10517 // actually re-launch them. 10518 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10519 && ps.getStopped(userId); 10520 } 10521 } 10522 return false; 10523 } 10524 10525 @Override 10526 protected boolean isPackageForFilter(String packageName, 10527 PackageParser.ActivityIntentInfo info) { 10528 return packageName.equals(info.activity.owner.packageName); 10529 } 10530 10531 @Override 10532 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10533 int match, int userId) { 10534 if (!sUserManager.exists(userId)) return null; 10535 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10536 return null; 10537 } 10538 final PackageParser.Activity activity = info.activity; 10539 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10540 if (ps == null) { 10541 return null; 10542 } 10543 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10544 ps.readUserState(userId), userId); 10545 if (ai == null) { 10546 return null; 10547 } 10548 final ResolveInfo res = new ResolveInfo(); 10549 res.activityInfo = ai; 10550 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10551 res.filter = info; 10552 } 10553 if (info != null) { 10554 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10555 } 10556 res.priority = info.getPriority(); 10557 res.preferredOrder = activity.owner.mPreferredOrder; 10558 //System.out.println("Result: " + res.activityInfo.className + 10559 // " = " + res.priority); 10560 res.match = match; 10561 res.isDefault = info.hasDefault; 10562 res.labelRes = info.labelRes; 10563 res.nonLocalizedLabel = info.nonLocalizedLabel; 10564 if (userNeedsBadging(userId)) { 10565 res.noResourceId = true; 10566 } else { 10567 res.icon = info.icon; 10568 } 10569 res.iconResourceId = info.icon; 10570 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10571 return res; 10572 } 10573 10574 @Override 10575 protected void sortResults(List<ResolveInfo> results) { 10576 Collections.sort(results, mResolvePrioritySorter); 10577 } 10578 10579 @Override 10580 protected void dumpFilter(PrintWriter out, String prefix, 10581 PackageParser.ActivityIntentInfo filter) { 10582 out.print(prefix); out.print( 10583 Integer.toHexString(System.identityHashCode(filter.activity))); 10584 out.print(' '); 10585 filter.activity.printComponentShortName(out); 10586 out.print(" filter "); 10587 out.println(Integer.toHexString(System.identityHashCode(filter))); 10588 } 10589 10590 @Override 10591 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10592 return filter.activity; 10593 } 10594 10595 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10596 PackageParser.Activity activity = (PackageParser.Activity)label; 10597 out.print(prefix); out.print( 10598 Integer.toHexString(System.identityHashCode(activity))); 10599 out.print(' '); 10600 activity.printComponentShortName(out); 10601 if (count > 1) { 10602 out.print(" ("); out.print(count); out.print(" filters)"); 10603 } 10604 out.println(); 10605 } 10606 10607 // Keys are String (activity class name), values are Activity. 10608 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10609 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10610 private int mFlags; 10611 } 10612 10613 private final class ServiceIntentResolver 10614 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10615 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10616 boolean defaultOnly, int userId) { 10617 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10618 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10619 } 10620 10621 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10622 int userId) { 10623 if (!sUserManager.exists(userId)) return null; 10624 mFlags = flags; 10625 return super.queryIntent(intent, resolvedType, 10626 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10627 } 10628 10629 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10630 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10631 if (!sUserManager.exists(userId)) return null; 10632 if (packageServices == null) { 10633 return null; 10634 } 10635 mFlags = flags; 10636 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10637 final int N = packageServices.size(); 10638 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10639 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10640 10641 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10642 for (int i = 0; i < N; ++i) { 10643 intentFilters = packageServices.get(i).intents; 10644 if (intentFilters != null && intentFilters.size() > 0) { 10645 PackageParser.ServiceIntentInfo[] array = 10646 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10647 intentFilters.toArray(array); 10648 listCut.add(array); 10649 } 10650 } 10651 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10652 } 10653 10654 public final void addService(PackageParser.Service s) { 10655 mServices.put(s.getComponentName(), s); 10656 if (DEBUG_SHOW_INFO) { 10657 Log.v(TAG, " " 10658 + (s.info.nonLocalizedLabel != null 10659 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10660 Log.v(TAG, " Class=" + s.info.name); 10661 } 10662 final int NI = s.intents.size(); 10663 int j; 10664 for (j=0; j<NI; j++) { 10665 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10666 if (DEBUG_SHOW_INFO) { 10667 Log.v(TAG, " IntentFilter:"); 10668 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10669 } 10670 if (!intent.debugCheck()) { 10671 Log.w(TAG, "==> For Service " + s.info.name); 10672 } 10673 addFilter(intent); 10674 } 10675 } 10676 10677 public final void removeService(PackageParser.Service s) { 10678 mServices.remove(s.getComponentName()); 10679 if (DEBUG_SHOW_INFO) { 10680 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10681 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10682 Log.v(TAG, " Class=" + s.info.name); 10683 } 10684 final int NI = s.intents.size(); 10685 int j; 10686 for (j=0; j<NI; j++) { 10687 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10688 if (DEBUG_SHOW_INFO) { 10689 Log.v(TAG, " IntentFilter:"); 10690 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10691 } 10692 removeFilter(intent); 10693 } 10694 } 10695 10696 @Override 10697 protected boolean allowFilterResult( 10698 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10699 ServiceInfo filterSi = filter.service.info; 10700 for (int i=dest.size()-1; i>=0; i--) { 10701 ServiceInfo destAi = dest.get(i).serviceInfo; 10702 if (destAi.name == filterSi.name 10703 && destAi.packageName == filterSi.packageName) { 10704 return false; 10705 } 10706 } 10707 return true; 10708 } 10709 10710 @Override 10711 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10712 return new PackageParser.ServiceIntentInfo[size]; 10713 } 10714 10715 @Override 10716 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10717 if (!sUserManager.exists(userId)) return true; 10718 PackageParser.Package p = filter.service.owner; 10719 if (p != null) { 10720 PackageSetting ps = (PackageSetting)p.mExtras; 10721 if (ps != null) { 10722 // System apps are never considered stopped for purposes of 10723 // filtering, because there may be no way for the user to 10724 // actually re-launch them. 10725 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10726 && ps.getStopped(userId); 10727 } 10728 } 10729 return false; 10730 } 10731 10732 @Override 10733 protected boolean isPackageForFilter(String packageName, 10734 PackageParser.ServiceIntentInfo info) { 10735 return packageName.equals(info.service.owner.packageName); 10736 } 10737 10738 @Override 10739 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10740 int match, int userId) { 10741 if (!sUserManager.exists(userId)) return null; 10742 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10743 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10744 return null; 10745 } 10746 final PackageParser.Service service = info.service; 10747 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10748 if (ps == null) { 10749 return null; 10750 } 10751 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10752 ps.readUserState(userId), userId); 10753 if (si == null) { 10754 return null; 10755 } 10756 final ResolveInfo res = new ResolveInfo(); 10757 res.serviceInfo = si; 10758 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10759 res.filter = filter; 10760 } 10761 res.priority = info.getPriority(); 10762 res.preferredOrder = service.owner.mPreferredOrder; 10763 res.match = match; 10764 res.isDefault = info.hasDefault; 10765 res.labelRes = info.labelRes; 10766 res.nonLocalizedLabel = info.nonLocalizedLabel; 10767 res.icon = info.icon; 10768 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10769 return res; 10770 } 10771 10772 @Override 10773 protected void sortResults(List<ResolveInfo> results) { 10774 Collections.sort(results, mResolvePrioritySorter); 10775 } 10776 10777 @Override 10778 protected void dumpFilter(PrintWriter out, String prefix, 10779 PackageParser.ServiceIntentInfo filter) { 10780 out.print(prefix); out.print( 10781 Integer.toHexString(System.identityHashCode(filter.service))); 10782 out.print(' '); 10783 filter.service.printComponentShortName(out); 10784 out.print(" filter "); 10785 out.println(Integer.toHexString(System.identityHashCode(filter))); 10786 } 10787 10788 @Override 10789 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10790 return filter.service; 10791 } 10792 10793 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10794 PackageParser.Service service = (PackageParser.Service)label; 10795 out.print(prefix); out.print( 10796 Integer.toHexString(System.identityHashCode(service))); 10797 out.print(' '); 10798 service.printComponentShortName(out); 10799 if (count > 1) { 10800 out.print(" ("); out.print(count); out.print(" filters)"); 10801 } 10802 out.println(); 10803 } 10804 10805// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10806// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10807// final List<ResolveInfo> retList = Lists.newArrayList(); 10808// while (i.hasNext()) { 10809// final ResolveInfo resolveInfo = (ResolveInfo) i; 10810// if (isEnabledLP(resolveInfo.serviceInfo)) { 10811// retList.add(resolveInfo); 10812// } 10813// } 10814// return retList; 10815// } 10816 10817 // Keys are String (activity class name), values are Activity. 10818 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10819 = new ArrayMap<ComponentName, PackageParser.Service>(); 10820 private int mFlags; 10821 }; 10822 10823 private final class ProviderIntentResolver 10824 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10825 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10826 boolean defaultOnly, int userId) { 10827 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10828 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10829 } 10830 10831 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10832 int userId) { 10833 if (!sUserManager.exists(userId)) 10834 return null; 10835 mFlags = flags; 10836 return super.queryIntent(intent, resolvedType, 10837 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10838 } 10839 10840 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10841 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10842 if (!sUserManager.exists(userId)) 10843 return null; 10844 if (packageProviders == null) { 10845 return null; 10846 } 10847 mFlags = flags; 10848 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10849 final int N = packageProviders.size(); 10850 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10851 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10852 10853 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10854 for (int i = 0; i < N; ++i) { 10855 intentFilters = packageProviders.get(i).intents; 10856 if (intentFilters != null && intentFilters.size() > 0) { 10857 PackageParser.ProviderIntentInfo[] array = 10858 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10859 intentFilters.toArray(array); 10860 listCut.add(array); 10861 } 10862 } 10863 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10864 } 10865 10866 public final void addProvider(PackageParser.Provider p) { 10867 if (mProviders.containsKey(p.getComponentName())) { 10868 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10869 return; 10870 } 10871 10872 mProviders.put(p.getComponentName(), p); 10873 if (DEBUG_SHOW_INFO) { 10874 Log.v(TAG, " " 10875 + (p.info.nonLocalizedLabel != null 10876 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10877 Log.v(TAG, " Class=" + p.info.name); 10878 } 10879 final int NI = p.intents.size(); 10880 int j; 10881 for (j = 0; j < NI; j++) { 10882 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10883 if (DEBUG_SHOW_INFO) { 10884 Log.v(TAG, " IntentFilter:"); 10885 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10886 } 10887 if (!intent.debugCheck()) { 10888 Log.w(TAG, "==> For Provider " + p.info.name); 10889 } 10890 addFilter(intent); 10891 } 10892 } 10893 10894 public final void removeProvider(PackageParser.Provider p) { 10895 mProviders.remove(p.getComponentName()); 10896 if (DEBUG_SHOW_INFO) { 10897 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10898 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10899 Log.v(TAG, " Class=" + p.info.name); 10900 } 10901 final int NI = p.intents.size(); 10902 int j; 10903 for (j = 0; j < NI; j++) { 10904 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10905 if (DEBUG_SHOW_INFO) { 10906 Log.v(TAG, " IntentFilter:"); 10907 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10908 } 10909 removeFilter(intent); 10910 } 10911 } 10912 10913 @Override 10914 protected boolean allowFilterResult( 10915 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10916 ProviderInfo filterPi = filter.provider.info; 10917 for (int i = dest.size() - 1; i >= 0; i--) { 10918 ProviderInfo destPi = dest.get(i).providerInfo; 10919 if (destPi.name == filterPi.name 10920 && destPi.packageName == filterPi.packageName) { 10921 return false; 10922 } 10923 } 10924 return true; 10925 } 10926 10927 @Override 10928 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10929 return new PackageParser.ProviderIntentInfo[size]; 10930 } 10931 10932 @Override 10933 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10934 if (!sUserManager.exists(userId)) 10935 return true; 10936 PackageParser.Package p = filter.provider.owner; 10937 if (p != null) { 10938 PackageSetting ps = (PackageSetting) p.mExtras; 10939 if (ps != null) { 10940 // System apps are never considered stopped for purposes of 10941 // filtering, because there may be no way for the user to 10942 // actually re-launch them. 10943 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10944 && ps.getStopped(userId); 10945 } 10946 } 10947 return false; 10948 } 10949 10950 @Override 10951 protected boolean isPackageForFilter(String packageName, 10952 PackageParser.ProviderIntentInfo info) { 10953 return packageName.equals(info.provider.owner.packageName); 10954 } 10955 10956 @Override 10957 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10958 int match, int userId) { 10959 if (!sUserManager.exists(userId)) 10960 return null; 10961 final PackageParser.ProviderIntentInfo info = filter; 10962 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10963 return null; 10964 } 10965 final PackageParser.Provider provider = info.provider; 10966 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10967 if (ps == null) { 10968 return null; 10969 } 10970 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10971 ps.readUserState(userId), userId); 10972 if (pi == null) { 10973 return null; 10974 } 10975 final ResolveInfo res = new ResolveInfo(); 10976 res.providerInfo = pi; 10977 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10978 res.filter = filter; 10979 } 10980 res.priority = info.getPriority(); 10981 res.preferredOrder = provider.owner.mPreferredOrder; 10982 res.match = match; 10983 res.isDefault = info.hasDefault; 10984 res.labelRes = info.labelRes; 10985 res.nonLocalizedLabel = info.nonLocalizedLabel; 10986 res.icon = info.icon; 10987 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10988 return res; 10989 } 10990 10991 @Override 10992 protected void sortResults(List<ResolveInfo> results) { 10993 Collections.sort(results, mResolvePrioritySorter); 10994 } 10995 10996 @Override 10997 protected void dumpFilter(PrintWriter out, String prefix, 10998 PackageParser.ProviderIntentInfo filter) { 10999 out.print(prefix); 11000 out.print( 11001 Integer.toHexString(System.identityHashCode(filter.provider))); 11002 out.print(' '); 11003 filter.provider.printComponentShortName(out); 11004 out.print(" filter "); 11005 out.println(Integer.toHexString(System.identityHashCode(filter))); 11006 } 11007 11008 @Override 11009 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11010 return filter.provider; 11011 } 11012 11013 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11014 PackageParser.Provider provider = (PackageParser.Provider)label; 11015 out.print(prefix); out.print( 11016 Integer.toHexString(System.identityHashCode(provider))); 11017 out.print(' '); 11018 provider.printComponentShortName(out); 11019 if (count > 1) { 11020 out.print(" ("); out.print(count); out.print(" filters)"); 11021 } 11022 out.println(); 11023 } 11024 11025 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11026 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11027 private int mFlags; 11028 } 11029 11030 private static final class EphemeralIntentResolver 11031 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11032 @Override 11033 protected EphemeralResolveIntentInfo[] newArray(int size) { 11034 return new EphemeralResolveIntentInfo[size]; 11035 } 11036 11037 @Override 11038 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11039 return true; 11040 } 11041 11042 @Override 11043 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11044 int userId) { 11045 if (!sUserManager.exists(userId)) { 11046 return null; 11047 } 11048 return info.getEphemeralResolveInfo(); 11049 } 11050 } 11051 11052 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11053 new Comparator<ResolveInfo>() { 11054 public int compare(ResolveInfo r1, ResolveInfo r2) { 11055 int v1 = r1.priority; 11056 int v2 = r2.priority; 11057 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11058 if (v1 != v2) { 11059 return (v1 > v2) ? -1 : 1; 11060 } 11061 v1 = r1.preferredOrder; 11062 v2 = r2.preferredOrder; 11063 if (v1 != v2) { 11064 return (v1 > v2) ? -1 : 1; 11065 } 11066 if (r1.isDefault != r2.isDefault) { 11067 return r1.isDefault ? -1 : 1; 11068 } 11069 v1 = r1.match; 11070 v2 = r2.match; 11071 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11072 if (v1 != v2) { 11073 return (v1 > v2) ? -1 : 1; 11074 } 11075 if (r1.system != r2.system) { 11076 return r1.system ? -1 : 1; 11077 } 11078 if (r1.activityInfo != null) { 11079 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11080 } 11081 if (r1.serviceInfo != null) { 11082 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11083 } 11084 if (r1.providerInfo != null) { 11085 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11086 } 11087 return 0; 11088 } 11089 }; 11090 11091 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11092 new Comparator<ProviderInfo>() { 11093 public int compare(ProviderInfo p1, ProviderInfo p2) { 11094 final int v1 = p1.initOrder; 11095 final int v2 = p2.initOrder; 11096 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11097 } 11098 }; 11099 11100 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11101 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11102 final int[] userIds) { 11103 mHandler.post(new Runnable() { 11104 @Override 11105 public void run() { 11106 try { 11107 final IActivityManager am = ActivityManagerNative.getDefault(); 11108 if (am == null) return; 11109 final int[] resolvedUserIds; 11110 if (userIds == null) { 11111 resolvedUserIds = am.getRunningUserIds(); 11112 } else { 11113 resolvedUserIds = userIds; 11114 } 11115 for (int id : resolvedUserIds) { 11116 final Intent intent = new Intent(action, 11117 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11118 if (extras != null) { 11119 intent.putExtras(extras); 11120 } 11121 if (targetPkg != null) { 11122 intent.setPackage(targetPkg); 11123 } 11124 // Modify the UID when posting to other users 11125 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11126 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11127 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11128 intent.putExtra(Intent.EXTRA_UID, uid); 11129 } 11130 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11131 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11132 if (DEBUG_BROADCASTS) { 11133 RuntimeException here = new RuntimeException("here"); 11134 here.fillInStackTrace(); 11135 Slog.d(TAG, "Sending to user " + id + ": " 11136 + intent.toShortString(false, true, false, false) 11137 + " " + intent.getExtras(), here); 11138 } 11139 am.broadcastIntent(null, intent, null, finishedReceiver, 11140 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11141 null, finishedReceiver != null, false, id); 11142 } 11143 } catch (RemoteException ex) { 11144 } 11145 } 11146 }); 11147 } 11148 11149 /** 11150 * Check if the external storage media is available. This is true if there 11151 * is a mounted external storage medium or if the external storage is 11152 * emulated. 11153 */ 11154 private boolean isExternalMediaAvailable() { 11155 return mMediaMounted || Environment.isExternalStorageEmulated(); 11156 } 11157 11158 @Override 11159 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11160 // writer 11161 synchronized (mPackages) { 11162 if (!isExternalMediaAvailable()) { 11163 // If the external storage is no longer mounted at this point, 11164 // the caller may not have been able to delete all of this 11165 // packages files and can not delete any more. Bail. 11166 return null; 11167 } 11168 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11169 if (lastPackage != null) { 11170 pkgs.remove(lastPackage); 11171 } 11172 if (pkgs.size() > 0) { 11173 return pkgs.get(0); 11174 } 11175 } 11176 return null; 11177 } 11178 11179 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11180 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11181 userId, andCode ? 1 : 0, packageName); 11182 if (mSystemReady) { 11183 msg.sendToTarget(); 11184 } else { 11185 if (mPostSystemReadyMessages == null) { 11186 mPostSystemReadyMessages = new ArrayList<>(); 11187 } 11188 mPostSystemReadyMessages.add(msg); 11189 } 11190 } 11191 11192 void startCleaningPackages() { 11193 // reader 11194 if (!isExternalMediaAvailable()) { 11195 return; 11196 } 11197 synchronized (mPackages) { 11198 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11199 return; 11200 } 11201 } 11202 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11203 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11204 IActivityManager am = ActivityManagerNative.getDefault(); 11205 if (am != null) { 11206 try { 11207 am.startService(null, intent, null, mContext.getOpPackageName(), 11208 UserHandle.USER_SYSTEM); 11209 } catch (RemoteException e) { 11210 } 11211 } 11212 } 11213 11214 @Override 11215 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11216 int installFlags, String installerPackageName, int userId) { 11217 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11218 11219 final int callingUid = Binder.getCallingUid(); 11220 enforceCrossUserPermission(callingUid, userId, 11221 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11222 11223 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11224 try { 11225 if (observer != null) { 11226 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11227 } 11228 } catch (RemoteException re) { 11229 } 11230 return; 11231 } 11232 11233 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11234 installFlags |= PackageManager.INSTALL_FROM_ADB; 11235 11236 } else { 11237 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11238 // about installerPackageName. 11239 11240 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11241 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11242 } 11243 11244 UserHandle user; 11245 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11246 user = UserHandle.ALL; 11247 } else { 11248 user = new UserHandle(userId); 11249 } 11250 11251 // Only system components can circumvent runtime permissions when installing. 11252 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11253 && mContext.checkCallingOrSelfPermission(Manifest.permission 11254 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11255 throw new SecurityException("You need the " 11256 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11257 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11258 } 11259 11260 final File originFile = new File(originPath); 11261 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11262 11263 final Message msg = mHandler.obtainMessage(INIT_COPY); 11264 final VerificationInfo verificationInfo = new VerificationInfo( 11265 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11266 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11267 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11268 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11269 null /*certificates*/); 11270 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11271 msg.obj = params; 11272 11273 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11274 System.identityHashCode(msg.obj)); 11275 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11276 System.identityHashCode(msg.obj)); 11277 11278 mHandler.sendMessage(msg); 11279 } 11280 11281 void installStage(String packageName, File stagedDir, String stagedCid, 11282 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11283 String installerPackageName, int installerUid, UserHandle user, 11284 Certificate[][] certificates) { 11285 if (DEBUG_EPHEMERAL) { 11286 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11287 Slog.d(TAG, "Ephemeral install of " + packageName); 11288 } 11289 } 11290 final VerificationInfo verificationInfo = new VerificationInfo( 11291 sessionParams.originatingUri, sessionParams.referrerUri, 11292 sessionParams.originatingUid, installerUid); 11293 11294 final OriginInfo origin; 11295 if (stagedDir != null) { 11296 origin = OriginInfo.fromStagedFile(stagedDir); 11297 } else { 11298 origin = OriginInfo.fromStagedContainer(stagedCid); 11299 } 11300 11301 final Message msg = mHandler.obtainMessage(INIT_COPY); 11302 final InstallParams params = new InstallParams(origin, null, observer, 11303 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11304 verificationInfo, user, sessionParams.abiOverride, 11305 sessionParams.grantedRuntimePermissions, certificates); 11306 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11307 msg.obj = params; 11308 11309 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11310 System.identityHashCode(msg.obj)); 11311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11312 System.identityHashCode(msg.obj)); 11313 11314 mHandler.sendMessage(msg); 11315 } 11316 11317 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11318 int userId) { 11319 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11320 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11321 } 11322 11323 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11324 int appId, int userId) { 11325 Bundle extras = new Bundle(1); 11326 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11327 11328 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11329 packageName, extras, 0, null, null, new int[] {userId}); 11330 try { 11331 IActivityManager am = ActivityManagerNative.getDefault(); 11332 if (isSystem && am.isUserRunning(userId, 0)) { 11333 // The just-installed/enabled app is bundled on the system, so presumed 11334 // to be able to run automatically without needing an explicit launch. 11335 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11336 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11337 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11338 .setPackage(packageName); 11339 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11340 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11341 } 11342 } catch (RemoteException e) { 11343 // shouldn't happen 11344 Slog.w(TAG, "Unable to bootstrap installed package", e); 11345 } 11346 } 11347 11348 @Override 11349 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11350 int userId) { 11351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11352 PackageSetting pkgSetting; 11353 final int uid = Binder.getCallingUid(); 11354 enforceCrossUserPermission(uid, userId, 11355 true /* requireFullPermission */, true /* checkShell */, 11356 "setApplicationHiddenSetting for user " + userId); 11357 11358 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11359 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11360 return false; 11361 } 11362 11363 long callingId = Binder.clearCallingIdentity(); 11364 try { 11365 boolean sendAdded = false; 11366 boolean sendRemoved = false; 11367 // writer 11368 synchronized (mPackages) { 11369 pkgSetting = mSettings.mPackages.get(packageName); 11370 if (pkgSetting == null) { 11371 return false; 11372 } 11373 if (pkgSetting.getHidden(userId) != hidden) { 11374 pkgSetting.setHidden(hidden, userId); 11375 mSettings.writePackageRestrictionsLPr(userId); 11376 if (hidden) { 11377 sendRemoved = true; 11378 } else { 11379 sendAdded = true; 11380 } 11381 } 11382 } 11383 if (sendAdded) { 11384 sendPackageAddedForUser(packageName, pkgSetting, userId); 11385 return true; 11386 } 11387 if (sendRemoved) { 11388 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11389 "hiding pkg"); 11390 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11391 return true; 11392 } 11393 } finally { 11394 Binder.restoreCallingIdentity(callingId); 11395 } 11396 return false; 11397 } 11398 11399 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11400 int userId) { 11401 final PackageRemovedInfo info = new PackageRemovedInfo(); 11402 info.removedPackage = packageName; 11403 info.removedUsers = new int[] {userId}; 11404 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11405 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11406 } 11407 11408 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11409 if (pkgList.length > 0) { 11410 Bundle extras = new Bundle(1); 11411 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11412 11413 sendPackageBroadcast( 11414 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11415 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11416 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11417 new int[] {userId}); 11418 } 11419 } 11420 11421 /** 11422 * Returns true if application is not found or there was an error. Otherwise it returns 11423 * the hidden state of the package for the given user. 11424 */ 11425 @Override 11426 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11427 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11428 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11429 true /* requireFullPermission */, false /* checkShell */, 11430 "getApplicationHidden for user " + userId); 11431 PackageSetting pkgSetting; 11432 long callingId = Binder.clearCallingIdentity(); 11433 try { 11434 // writer 11435 synchronized (mPackages) { 11436 pkgSetting = mSettings.mPackages.get(packageName); 11437 if (pkgSetting == null) { 11438 return true; 11439 } 11440 return pkgSetting.getHidden(userId); 11441 } 11442 } finally { 11443 Binder.restoreCallingIdentity(callingId); 11444 } 11445 } 11446 11447 /** 11448 * @hide 11449 */ 11450 @Override 11451 public int installExistingPackageAsUser(String packageName, int userId) { 11452 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11453 null); 11454 PackageSetting pkgSetting; 11455 final int uid = Binder.getCallingUid(); 11456 enforceCrossUserPermission(uid, userId, 11457 true /* requireFullPermission */, true /* checkShell */, 11458 "installExistingPackage for user " + userId); 11459 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11460 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11461 } 11462 11463 long callingId = Binder.clearCallingIdentity(); 11464 try { 11465 boolean installed = false; 11466 11467 // writer 11468 synchronized (mPackages) { 11469 pkgSetting = mSettings.mPackages.get(packageName); 11470 if (pkgSetting == null) { 11471 return PackageManager.INSTALL_FAILED_INVALID_URI; 11472 } 11473 if (!pkgSetting.getInstalled(userId)) { 11474 pkgSetting.setInstalled(true, userId); 11475 pkgSetting.setHidden(false, userId); 11476 mSettings.writePackageRestrictionsLPr(userId); 11477 installed = true; 11478 } 11479 } 11480 11481 if (installed) { 11482 if (pkgSetting.pkg != null) { 11483 synchronized (mInstallLock) { 11484 // We don't need to freeze for a brand new install 11485 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11486 } 11487 } 11488 sendPackageAddedForUser(packageName, pkgSetting, userId); 11489 } 11490 } finally { 11491 Binder.restoreCallingIdentity(callingId); 11492 } 11493 11494 return PackageManager.INSTALL_SUCCEEDED; 11495 } 11496 11497 boolean isUserRestricted(int userId, String restrictionKey) { 11498 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11499 if (restrictions.getBoolean(restrictionKey, false)) { 11500 Log.w(TAG, "User is restricted: " + restrictionKey); 11501 return true; 11502 } 11503 return false; 11504 } 11505 11506 @Override 11507 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11508 int userId) { 11509 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11510 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11511 true /* requireFullPermission */, true /* checkShell */, 11512 "setPackagesSuspended for user " + userId); 11513 11514 if (ArrayUtils.isEmpty(packageNames)) { 11515 return packageNames; 11516 } 11517 11518 // List of package names for whom the suspended state has changed. 11519 List<String> changedPackages = new ArrayList<>(packageNames.length); 11520 // List of package names for whom the suspended state is not set as requested in this 11521 // method. 11522 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11523 long callingId = Binder.clearCallingIdentity(); 11524 try { 11525 for (int i = 0; i < packageNames.length; i++) { 11526 String packageName = packageNames[i]; 11527 boolean changed = false; 11528 final int appId; 11529 synchronized (mPackages) { 11530 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11531 if (pkgSetting == null) { 11532 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11533 + "\". Skipping suspending/un-suspending."); 11534 unactionedPackages.add(packageName); 11535 continue; 11536 } 11537 appId = pkgSetting.appId; 11538 if (pkgSetting.getSuspended(userId) != suspended) { 11539 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11540 unactionedPackages.add(packageName); 11541 continue; 11542 } 11543 pkgSetting.setSuspended(suspended, userId); 11544 mSettings.writePackageRestrictionsLPr(userId); 11545 changed = true; 11546 changedPackages.add(packageName); 11547 } 11548 } 11549 11550 if (changed && suspended) { 11551 killApplication(packageName, UserHandle.getUid(userId, appId), 11552 "suspending package"); 11553 } 11554 } 11555 } finally { 11556 Binder.restoreCallingIdentity(callingId); 11557 } 11558 11559 if (!changedPackages.isEmpty()) { 11560 sendPackagesSuspendedForUser(changedPackages.toArray( 11561 new String[changedPackages.size()]), userId, suspended); 11562 } 11563 11564 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11565 } 11566 11567 @Override 11568 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11570 true /* requireFullPermission */, false /* checkShell */, 11571 "isPackageSuspendedForUser for user " + userId); 11572 synchronized (mPackages) { 11573 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11574 if (pkgSetting == null) { 11575 throw new IllegalArgumentException("Unknown target package: " + packageName); 11576 } 11577 return pkgSetting.getSuspended(userId); 11578 } 11579 } 11580 11581 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11582 if (isPackageDeviceAdmin(packageName, userId)) { 11583 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11584 + "\": has an active device admin"); 11585 return false; 11586 } 11587 11588 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11589 if (packageName.equals(activeLauncherPackageName)) { 11590 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11591 + "\": contains the active launcher"); 11592 return false; 11593 } 11594 11595 if (packageName.equals(mRequiredInstallerPackage)) { 11596 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11597 + "\": required for package installation"); 11598 return false; 11599 } 11600 11601 if (packageName.equals(mRequiredVerifierPackage)) { 11602 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11603 + "\": required for package verification"); 11604 return false; 11605 } 11606 11607 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11608 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11609 + "\": is the default dialer"); 11610 return false; 11611 } 11612 11613 return true; 11614 } 11615 11616 private String getActiveLauncherPackageName(int userId) { 11617 Intent intent = new Intent(Intent.ACTION_MAIN); 11618 intent.addCategory(Intent.CATEGORY_HOME); 11619 ResolveInfo resolveInfo = resolveIntent( 11620 intent, 11621 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11622 PackageManager.MATCH_DEFAULT_ONLY, 11623 userId); 11624 11625 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11626 } 11627 11628 private String getDefaultDialerPackageName(int userId) { 11629 synchronized (mPackages) { 11630 return mSettings.getDefaultDialerPackageNameLPw(userId); 11631 } 11632 } 11633 11634 @Override 11635 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11636 mContext.enforceCallingOrSelfPermission( 11637 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11638 "Only package verification agents can verify applications"); 11639 11640 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11641 final PackageVerificationResponse response = new PackageVerificationResponse( 11642 verificationCode, Binder.getCallingUid()); 11643 msg.arg1 = id; 11644 msg.obj = response; 11645 mHandler.sendMessage(msg); 11646 } 11647 11648 @Override 11649 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11650 long millisecondsToDelay) { 11651 mContext.enforceCallingOrSelfPermission( 11652 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11653 "Only package verification agents can extend verification timeouts"); 11654 11655 final PackageVerificationState state = mPendingVerification.get(id); 11656 final PackageVerificationResponse response = new PackageVerificationResponse( 11657 verificationCodeAtTimeout, Binder.getCallingUid()); 11658 11659 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11660 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11661 } 11662 if (millisecondsToDelay < 0) { 11663 millisecondsToDelay = 0; 11664 } 11665 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11666 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11667 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11668 } 11669 11670 if ((state != null) && !state.timeoutExtended()) { 11671 state.extendTimeout(); 11672 11673 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11674 msg.arg1 = id; 11675 msg.obj = response; 11676 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11677 } 11678 } 11679 11680 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11681 int verificationCode, UserHandle user) { 11682 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11683 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11684 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11685 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11686 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11687 11688 mContext.sendBroadcastAsUser(intent, user, 11689 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11690 } 11691 11692 private ComponentName matchComponentForVerifier(String packageName, 11693 List<ResolveInfo> receivers) { 11694 ActivityInfo targetReceiver = null; 11695 11696 final int NR = receivers.size(); 11697 for (int i = 0; i < NR; i++) { 11698 final ResolveInfo info = receivers.get(i); 11699 if (info.activityInfo == null) { 11700 continue; 11701 } 11702 11703 if (packageName.equals(info.activityInfo.packageName)) { 11704 targetReceiver = info.activityInfo; 11705 break; 11706 } 11707 } 11708 11709 if (targetReceiver == null) { 11710 return null; 11711 } 11712 11713 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11714 } 11715 11716 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11717 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11718 if (pkgInfo.verifiers.length == 0) { 11719 return null; 11720 } 11721 11722 final int N = pkgInfo.verifiers.length; 11723 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11724 for (int i = 0; i < N; i++) { 11725 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11726 11727 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11728 receivers); 11729 if (comp == null) { 11730 continue; 11731 } 11732 11733 final int verifierUid = getUidForVerifier(verifierInfo); 11734 if (verifierUid == -1) { 11735 continue; 11736 } 11737 11738 if (DEBUG_VERIFY) { 11739 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11740 + " with the correct signature"); 11741 } 11742 sufficientVerifiers.add(comp); 11743 verificationState.addSufficientVerifier(verifierUid); 11744 } 11745 11746 return sufficientVerifiers; 11747 } 11748 11749 private int getUidForVerifier(VerifierInfo verifierInfo) { 11750 synchronized (mPackages) { 11751 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11752 if (pkg == null) { 11753 return -1; 11754 } else if (pkg.mSignatures.length != 1) { 11755 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11756 + " has more than one signature; ignoring"); 11757 return -1; 11758 } 11759 11760 /* 11761 * If the public key of the package's signature does not match 11762 * our expected public key, then this is a different package and 11763 * we should skip. 11764 */ 11765 11766 final byte[] expectedPublicKey; 11767 try { 11768 final Signature verifierSig = pkg.mSignatures[0]; 11769 final PublicKey publicKey = verifierSig.getPublicKey(); 11770 expectedPublicKey = publicKey.getEncoded(); 11771 } catch (CertificateException e) { 11772 return -1; 11773 } 11774 11775 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11776 11777 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11778 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11779 + " does not have the expected public key; ignoring"); 11780 return -1; 11781 } 11782 11783 return pkg.applicationInfo.uid; 11784 } 11785 } 11786 11787 @Override 11788 public void finishPackageInstall(int token, boolean didLaunch) { 11789 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11790 11791 if (DEBUG_INSTALL) { 11792 Slog.v(TAG, "BM finishing package install for " + token); 11793 } 11794 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11795 11796 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11797 mHandler.sendMessage(msg); 11798 } 11799 11800 /** 11801 * Get the verification agent timeout. 11802 * 11803 * @return verification timeout in milliseconds 11804 */ 11805 private long getVerificationTimeout() { 11806 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11807 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11808 DEFAULT_VERIFICATION_TIMEOUT); 11809 } 11810 11811 /** 11812 * Get the default verification agent response code. 11813 * 11814 * @return default verification response code 11815 */ 11816 private int getDefaultVerificationResponse() { 11817 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11818 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11819 DEFAULT_VERIFICATION_RESPONSE); 11820 } 11821 11822 /** 11823 * Check whether or not package verification has been enabled. 11824 * 11825 * @return true if verification should be performed 11826 */ 11827 private boolean isVerificationEnabled(int userId, int installFlags) { 11828 if (!DEFAULT_VERIFY_ENABLE) { 11829 return false; 11830 } 11831 // Ephemeral apps don't get the full verification treatment 11832 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11833 if (DEBUG_EPHEMERAL) { 11834 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11835 } 11836 return false; 11837 } 11838 11839 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11840 11841 // Check if installing from ADB 11842 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11843 // Do not run verification in a test harness environment 11844 if (ActivityManager.isRunningInTestHarness()) { 11845 return false; 11846 } 11847 if (ensureVerifyAppsEnabled) { 11848 return true; 11849 } 11850 // Check if the developer does not want package verification for ADB installs 11851 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11852 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11853 return false; 11854 } 11855 } 11856 11857 if (ensureVerifyAppsEnabled) { 11858 return true; 11859 } 11860 11861 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11862 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11863 } 11864 11865 @Override 11866 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11867 throws RemoteException { 11868 mContext.enforceCallingOrSelfPermission( 11869 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11870 "Only intentfilter verification agents can verify applications"); 11871 11872 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11873 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11874 Binder.getCallingUid(), verificationCode, failedDomains); 11875 msg.arg1 = id; 11876 msg.obj = response; 11877 mHandler.sendMessage(msg); 11878 } 11879 11880 @Override 11881 public int getIntentVerificationStatus(String packageName, int userId) { 11882 synchronized (mPackages) { 11883 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11884 } 11885 } 11886 11887 @Override 11888 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11889 mContext.enforceCallingOrSelfPermission( 11890 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11891 11892 boolean result = false; 11893 synchronized (mPackages) { 11894 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11895 } 11896 if (result) { 11897 scheduleWritePackageRestrictionsLocked(userId); 11898 } 11899 return result; 11900 } 11901 11902 @Override 11903 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11904 String packageName) { 11905 synchronized (mPackages) { 11906 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11907 } 11908 } 11909 11910 @Override 11911 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11912 if (TextUtils.isEmpty(packageName)) { 11913 return ParceledListSlice.emptyList(); 11914 } 11915 synchronized (mPackages) { 11916 PackageParser.Package pkg = mPackages.get(packageName); 11917 if (pkg == null || pkg.activities == null) { 11918 return ParceledListSlice.emptyList(); 11919 } 11920 final int count = pkg.activities.size(); 11921 ArrayList<IntentFilter> result = new ArrayList<>(); 11922 for (int n=0; n<count; n++) { 11923 PackageParser.Activity activity = pkg.activities.get(n); 11924 if (activity.intents != null && activity.intents.size() > 0) { 11925 result.addAll(activity.intents); 11926 } 11927 } 11928 return new ParceledListSlice<>(result); 11929 } 11930 } 11931 11932 @Override 11933 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11934 mContext.enforceCallingOrSelfPermission( 11935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11936 11937 synchronized (mPackages) { 11938 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11939 if (packageName != null) { 11940 result |= updateIntentVerificationStatus(packageName, 11941 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11942 userId); 11943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11944 packageName, userId); 11945 } 11946 return result; 11947 } 11948 } 11949 11950 @Override 11951 public String getDefaultBrowserPackageName(int userId) { 11952 synchronized (mPackages) { 11953 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11954 } 11955 } 11956 11957 /** 11958 * Get the "allow unknown sources" setting. 11959 * 11960 * @return the current "allow unknown sources" setting 11961 */ 11962 private int getUnknownSourcesSettings() { 11963 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11964 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11965 -1); 11966 } 11967 11968 @Override 11969 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11970 final int uid = Binder.getCallingUid(); 11971 // writer 11972 synchronized (mPackages) { 11973 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11974 if (targetPackageSetting == null) { 11975 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11976 } 11977 11978 PackageSetting installerPackageSetting; 11979 if (installerPackageName != null) { 11980 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11981 if (installerPackageSetting == null) { 11982 throw new IllegalArgumentException("Unknown installer package: " 11983 + installerPackageName); 11984 } 11985 } else { 11986 installerPackageSetting = null; 11987 } 11988 11989 Signature[] callerSignature; 11990 Object obj = mSettings.getUserIdLPr(uid); 11991 if (obj != null) { 11992 if (obj instanceof SharedUserSetting) { 11993 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11994 } else if (obj instanceof PackageSetting) { 11995 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11996 } else { 11997 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11998 } 11999 } else { 12000 throw new SecurityException("Unknown calling UID: " + uid); 12001 } 12002 12003 // Verify: can't set installerPackageName to a package that is 12004 // not signed with the same cert as the caller. 12005 if (installerPackageSetting != null) { 12006 if (compareSignatures(callerSignature, 12007 installerPackageSetting.signatures.mSignatures) 12008 != PackageManager.SIGNATURE_MATCH) { 12009 throw new SecurityException( 12010 "Caller does not have same cert as new installer package " 12011 + installerPackageName); 12012 } 12013 } 12014 12015 // Verify: if target already has an installer package, it must 12016 // be signed with the same cert as the caller. 12017 if (targetPackageSetting.installerPackageName != null) { 12018 PackageSetting setting = mSettings.mPackages.get( 12019 targetPackageSetting.installerPackageName); 12020 // If the currently set package isn't valid, then it's always 12021 // okay to change it. 12022 if (setting != null) { 12023 if (compareSignatures(callerSignature, 12024 setting.signatures.mSignatures) 12025 != PackageManager.SIGNATURE_MATCH) { 12026 throw new SecurityException( 12027 "Caller does not have same cert as old installer package " 12028 + targetPackageSetting.installerPackageName); 12029 } 12030 } 12031 } 12032 12033 // Okay! 12034 targetPackageSetting.installerPackageName = installerPackageName; 12035 if (installerPackageName != null) { 12036 mSettings.mInstallerPackages.add(installerPackageName); 12037 } 12038 scheduleWriteSettingsLocked(); 12039 } 12040 } 12041 12042 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12043 // Queue up an async operation since the package installation may take a little while. 12044 mHandler.post(new Runnable() { 12045 public void run() { 12046 mHandler.removeCallbacks(this); 12047 // Result object to be returned 12048 PackageInstalledInfo res = new PackageInstalledInfo(); 12049 res.setReturnCode(currentStatus); 12050 res.uid = -1; 12051 res.pkg = null; 12052 res.removedInfo = null; 12053 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12054 args.doPreInstall(res.returnCode); 12055 synchronized (mInstallLock) { 12056 installPackageTracedLI(args, res); 12057 } 12058 args.doPostInstall(res.returnCode, res.uid); 12059 } 12060 12061 // A restore should be performed at this point if (a) the install 12062 // succeeded, (b) the operation is not an update, and (c) the new 12063 // package has not opted out of backup participation. 12064 final boolean update = res.removedInfo != null 12065 && res.removedInfo.removedPackage != null; 12066 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12067 boolean doRestore = !update 12068 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12069 12070 // Set up the post-install work request bookkeeping. This will be used 12071 // and cleaned up by the post-install event handling regardless of whether 12072 // there's a restore pass performed. Token values are >= 1. 12073 int token; 12074 if (mNextInstallToken < 0) mNextInstallToken = 1; 12075 token = mNextInstallToken++; 12076 12077 PostInstallData data = new PostInstallData(args, res); 12078 mRunningInstalls.put(token, data); 12079 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12080 12081 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12082 // Pass responsibility to the Backup Manager. It will perform a 12083 // restore if appropriate, then pass responsibility back to the 12084 // Package Manager to run the post-install observer callbacks 12085 // and broadcasts. 12086 IBackupManager bm = IBackupManager.Stub.asInterface( 12087 ServiceManager.getService(Context.BACKUP_SERVICE)); 12088 if (bm != null) { 12089 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12090 + " to BM for possible restore"); 12091 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12092 try { 12093 // TODO: http://b/22388012 12094 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12095 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12096 } else { 12097 doRestore = false; 12098 } 12099 } catch (RemoteException e) { 12100 // can't happen; the backup manager is local 12101 } catch (Exception e) { 12102 Slog.e(TAG, "Exception trying to enqueue restore", e); 12103 doRestore = false; 12104 } 12105 } else { 12106 Slog.e(TAG, "Backup Manager not found!"); 12107 doRestore = false; 12108 } 12109 } 12110 12111 if (!doRestore) { 12112 // No restore possible, or the Backup Manager was mysteriously not 12113 // available -- just fire the post-install work request directly. 12114 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12115 12116 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12117 12118 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12119 mHandler.sendMessage(msg); 12120 } 12121 } 12122 }); 12123 } 12124 12125 /** 12126 * Callback from PackageSettings whenever an app is first transitioned out of the 12127 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12128 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12129 * here whether the app is the target of an ongoing install, and only send the 12130 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12131 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12132 * handling. 12133 */ 12134 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12135 // Serialize this with the rest of the install-process message chain. In the 12136 // restore-at-install case, this Runnable will necessarily run before the 12137 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12138 // are coherent. In the non-restore case, the app has already completed install 12139 // and been launched through some other means, so it is not in a problematic 12140 // state for observers to see the FIRST_LAUNCH signal. 12141 mHandler.post(new Runnable() { 12142 @Override 12143 public void run() { 12144 for (int i = 0; i < mRunningInstalls.size(); i++) { 12145 final PostInstallData data = mRunningInstalls.valueAt(i); 12146 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12147 // right package; but is it for the right user? 12148 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12149 if (userId == data.res.newUsers[uIndex]) { 12150 if (DEBUG_BACKUP) { 12151 Slog.i(TAG, "Package " + pkgName 12152 + " being restored so deferring FIRST_LAUNCH"); 12153 } 12154 return; 12155 } 12156 } 12157 } 12158 } 12159 // didn't find it, so not being restored 12160 if (DEBUG_BACKUP) { 12161 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12162 } 12163 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12164 } 12165 }); 12166 } 12167 12168 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12169 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12170 installerPkg, null, userIds); 12171 } 12172 12173 private abstract class HandlerParams { 12174 private static final int MAX_RETRIES = 4; 12175 12176 /** 12177 * Number of times startCopy() has been attempted and had a non-fatal 12178 * error. 12179 */ 12180 private int mRetries = 0; 12181 12182 /** User handle for the user requesting the information or installation. */ 12183 private final UserHandle mUser; 12184 String traceMethod; 12185 int traceCookie; 12186 12187 HandlerParams(UserHandle user) { 12188 mUser = user; 12189 } 12190 12191 UserHandle getUser() { 12192 return mUser; 12193 } 12194 12195 HandlerParams setTraceMethod(String traceMethod) { 12196 this.traceMethod = traceMethod; 12197 return this; 12198 } 12199 12200 HandlerParams setTraceCookie(int traceCookie) { 12201 this.traceCookie = traceCookie; 12202 return this; 12203 } 12204 12205 final boolean startCopy() { 12206 boolean res; 12207 try { 12208 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12209 12210 if (++mRetries > MAX_RETRIES) { 12211 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12212 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12213 handleServiceError(); 12214 return false; 12215 } else { 12216 handleStartCopy(); 12217 res = true; 12218 } 12219 } catch (RemoteException e) { 12220 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12221 mHandler.sendEmptyMessage(MCS_RECONNECT); 12222 res = false; 12223 } 12224 handleReturnCode(); 12225 return res; 12226 } 12227 12228 final void serviceError() { 12229 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12230 handleServiceError(); 12231 handleReturnCode(); 12232 } 12233 12234 abstract void handleStartCopy() throws RemoteException; 12235 abstract void handleServiceError(); 12236 abstract void handleReturnCode(); 12237 } 12238 12239 class MeasureParams extends HandlerParams { 12240 private final PackageStats mStats; 12241 private boolean mSuccess; 12242 12243 private final IPackageStatsObserver mObserver; 12244 12245 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12246 super(new UserHandle(stats.userHandle)); 12247 mObserver = observer; 12248 mStats = stats; 12249 } 12250 12251 @Override 12252 public String toString() { 12253 return "MeasureParams{" 12254 + Integer.toHexString(System.identityHashCode(this)) 12255 + " " + mStats.packageName + "}"; 12256 } 12257 12258 @Override 12259 void handleStartCopy() throws RemoteException { 12260 synchronized (mInstallLock) { 12261 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12262 } 12263 12264 if (mSuccess) { 12265 final boolean mounted; 12266 if (Environment.isExternalStorageEmulated()) { 12267 mounted = true; 12268 } else { 12269 final String status = Environment.getExternalStorageState(); 12270 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12271 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12272 } 12273 12274 if (mounted) { 12275 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12276 12277 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12278 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12279 12280 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12281 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12282 12283 // Always subtract cache size, since it's a subdirectory 12284 mStats.externalDataSize -= mStats.externalCacheSize; 12285 12286 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12287 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12288 12289 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12290 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12291 } 12292 } 12293 } 12294 12295 @Override 12296 void handleReturnCode() { 12297 if (mObserver != null) { 12298 try { 12299 mObserver.onGetStatsCompleted(mStats, mSuccess); 12300 } catch (RemoteException e) { 12301 Slog.i(TAG, "Observer no longer exists."); 12302 } 12303 } 12304 } 12305 12306 @Override 12307 void handleServiceError() { 12308 Slog.e(TAG, "Could not measure application " + mStats.packageName 12309 + " external storage"); 12310 } 12311 } 12312 12313 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12314 throws RemoteException { 12315 long result = 0; 12316 for (File path : paths) { 12317 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12318 } 12319 return result; 12320 } 12321 12322 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12323 for (File path : paths) { 12324 try { 12325 mcs.clearDirectory(path.getAbsolutePath()); 12326 } catch (RemoteException e) { 12327 } 12328 } 12329 } 12330 12331 static class OriginInfo { 12332 /** 12333 * Location where install is coming from, before it has been 12334 * copied/renamed into place. This could be a single monolithic APK 12335 * file, or a cluster directory. This location may be untrusted. 12336 */ 12337 final File file; 12338 final String cid; 12339 12340 /** 12341 * Flag indicating that {@link #file} or {@link #cid} has already been 12342 * staged, meaning downstream users don't need to defensively copy the 12343 * contents. 12344 */ 12345 final boolean staged; 12346 12347 /** 12348 * Flag indicating that {@link #file} or {@link #cid} is an already 12349 * installed app that is being moved. 12350 */ 12351 final boolean existing; 12352 12353 final String resolvedPath; 12354 final File resolvedFile; 12355 12356 static OriginInfo fromNothing() { 12357 return new OriginInfo(null, null, false, false); 12358 } 12359 12360 static OriginInfo fromUntrustedFile(File file) { 12361 return new OriginInfo(file, null, false, false); 12362 } 12363 12364 static OriginInfo fromExistingFile(File file) { 12365 return new OriginInfo(file, null, false, true); 12366 } 12367 12368 static OriginInfo fromStagedFile(File file) { 12369 return new OriginInfo(file, null, true, false); 12370 } 12371 12372 static OriginInfo fromStagedContainer(String cid) { 12373 return new OriginInfo(null, cid, true, false); 12374 } 12375 12376 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12377 this.file = file; 12378 this.cid = cid; 12379 this.staged = staged; 12380 this.existing = existing; 12381 12382 if (cid != null) { 12383 resolvedPath = PackageHelper.getSdDir(cid); 12384 resolvedFile = new File(resolvedPath); 12385 } else if (file != null) { 12386 resolvedPath = file.getAbsolutePath(); 12387 resolvedFile = file; 12388 } else { 12389 resolvedPath = null; 12390 resolvedFile = null; 12391 } 12392 } 12393 } 12394 12395 static class MoveInfo { 12396 final int moveId; 12397 final String fromUuid; 12398 final String toUuid; 12399 final String packageName; 12400 final String dataAppName; 12401 final int appId; 12402 final String seinfo; 12403 final int targetSdkVersion; 12404 12405 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12406 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12407 this.moveId = moveId; 12408 this.fromUuid = fromUuid; 12409 this.toUuid = toUuid; 12410 this.packageName = packageName; 12411 this.dataAppName = dataAppName; 12412 this.appId = appId; 12413 this.seinfo = seinfo; 12414 this.targetSdkVersion = targetSdkVersion; 12415 } 12416 } 12417 12418 static class VerificationInfo { 12419 /** A constant used to indicate that a uid value is not present. */ 12420 public static final int NO_UID = -1; 12421 12422 /** URI referencing where the package was downloaded from. */ 12423 final Uri originatingUri; 12424 12425 /** HTTP referrer URI associated with the originatingURI. */ 12426 final Uri referrer; 12427 12428 /** UID of the application that the install request originated from. */ 12429 final int originatingUid; 12430 12431 /** UID of application requesting the install */ 12432 final int installerUid; 12433 12434 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12435 this.originatingUri = originatingUri; 12436 this.referrer = referrer; 12437 this.originatingUid = originatingUid; 12438 this.installerUid = installerUid; 12439 } 12440 } 12441 12442 class InstallParams extends HandlerParams { 12443 final OriginInfo origin; 12444 final MoveInfo move; 12445 final IPackageInstallObserver2 observer; 12446 int installFlags; 12447 final String installerPackageName; 12448 final String volumeUuid; 12449 private InstallArgs mArgs; 12450 private int mRet; 12451 final String packageAbiOverride; 12452 final String[] grantedRuntimePermissions; 12453 final VerificationInfo verificationInfo; 12454 final Certificate[][] certificates; 12455 12456 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12457 int installFlags, String installerPackageName, String volumeUuid, 12458 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12459 String[] grantedPermissions, Certificate[][] certificates) { 12460 super(user); 12461 this.origin = origin; 12462 this.move = move; 12463 this.observer = observer; 12464 this.installFlags = installFlags; 12465 this.installerPackageName = installerPackageName; 12466 this.volumeUuid = volumeUuid; 12467 this.verificationInfo = verificationInfo; 12468 this.packageAbiOverride = packageAbiOverride; 12469 this.grantedRuntimePermissions = grantedPermissions; 12470 this.certificates = certificates; 12471 } 12472 12473 @Override 12474 public String toString() { 12475 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12476 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12477 } 12478 12479 private int installLocationPolicy(PackageInfoLite pkgLite) { 12480 String packageName = pkgLite.packageName; 12481 int installLocation = pkgLite.installLocation; 12482 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12483 // reader 12484 synchronized (mPackages) { 12485 // Currently installed package which the new package is attempting to replace or 12486 // null if no such package is installed. 12487 PackageParser.Package installedPkg = mPackages.get(packageName); 12488 // Package which currently owns the data which the new package will own if installed. 12489 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12490 // will be null whereas dataOwnerPkg will contain information about the package 12491 // which was uninstalled while keeping its data. 12492 PackageParser.Package dataOwnerPkg = installedPkg; 12493 if (dataOwnerPkg == null) { 12494 PackageSetting ps = mSettings.mPackages.get(packageName); 12495 if (ps != null) { 12496 dataOwnerPkg = ps.pkg; 12497 } 12498 } 12499 12500 if (dataOwnerPkg != null) { 12501 // If installed, the package will get access to data left on the device by its 12502 // predecessor. As a security measure, this is permited only if this is not a 12503 // version downgrade or if the predecessor package is marked as debuggable and 12504 // a downgrade is explicitly requested. 12505 // 12506 // On debuggable platform builds, downgrades are permitted even for 12507 // non-debuggable packages to make testing easier. Debuggable platform builds do 12508 // not offer security guarantees and thus it's OK to disable some security 12509 // mechanisms to make debugging/testing easier on those builds. However, even on 12510 // debuggable builds downgrades of packages are permitted only if requested via 12511 // installFlags. This is because we aim to keep the behavior of debuggable 12512 // platform builds as close as possible to the behavior of non-debuggable 12513 // platform builds. 12514 final boolean downgradeRequested = 12515 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12516 final boolean packageDebuggable = 12517 (dataOwnerPkg.applicationInfo.flags 12518 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12519 final boolean downgradePermitted = 12520 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12521 if (!downgradePermitted) { 12522 try { 12523 checkDowngrade(dataOwnerPkg, pkgLite); 12524 } catch (PackageManagerException e) { 12525 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12526 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12527 } 12528 } 12529 } 12530 12531 if (installedPkg != null) { 12532 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12533 // Check for updated system application. 12534 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12535 if (onSd) { 12536 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12537 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12538 } 12539 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12540 } else { 12541 if (onSd) { 12542 // Install flag overrides everything. 12543 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12544 } 12545 // If current upgrade specifies particular preference 12546 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12547 // Application explicitly specified internal. 12548 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12549 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12550 // App explictly prefers external. Let policy decide 12551 } else { 12552 // Prefer previous location 12553 if (isExternal(installedPkg)) { 12554 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12555 } 12556 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12557 } 12558 } 12559 } else { 12560 // Invalid install. Return error code 12561 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12562 } 12563 } 12564 } 12565 // All the special cases have been taken care of. 12566 // Return result based on recommended install location. 12567 if (onSd) { 12568 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12569 } 12570 return pkgLite.recommendedInstallLocation; 12571 } 12572 12573 /* 12574 * Invoke remote method to get package information and install 12575 * location values. Override install location based on default 12576 * policy if needed and then create install arguments based 12577 * on the install location. 12578 */ 12579 public void handleStartCopy() throws RemoteException { 12580 int ret = PackageManager.INSTALL_SUCCEEDED; 12581 12582 // If we're already staged, we've firmly committed to an install location 12583 if (origin.staged) { 12584 if (origin.file != null) { 12585 installFlags |= PackageManager.INSTALL_INTERNAL; 12586 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12587 } else if (origin.cid != null) { 12588 installFlags |= PackageManager.INSTALL_EXTERNAL; 12589 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12590 } else { 12591 throw new IllegalStateException("Invalid stage location"); 12592 } 12593 } 12594 12595 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12596 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12597 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12598 PackageInfoLite pkgLite = null; 12599 12600 if (onInt && onSd) { 12601 // Check if both bits are set. 12602 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12603 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12604 } else if (onSd && ephemeral) { 12605 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12606 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12607 } else { 12608 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12609 packageAbiOverride); 12610 12611 if (DEBUG_EPHEMERAL && ephemeral) { 12612 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12613 } 12614 12615 /* 12616 * If we have too little free space, try to free cache 12617 * before giving up. 12618 */ 12619 if (!origin.staged && pkgLite.recommendedInstallLocation 12620 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12621 // TODO: focus freeing disk space on the target device 12622 final StorageManager storage = StorageManager.from(mContext); 12623 final long lowThreshold = storage.getStorageLowBytes( 12624 Environment.getDataDirectory()); 12625 12626 final long sizeBytes = mContainerService.calculateInstalledSize( 12627 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12628 12629 try { 12630 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12631 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12632 installFlags, packageAbiOverride); 12633 } catch (InstallerException e) { 12634 Slog.w(TAG, "Failed to free cache", e); 12635 } 12636 12637 /* 12638 * The cache free must have deleted the file we 12639 * downloaded to install. 12640 * 12641 * TODO: fix the "freeCache" call to not delete 12642 * the file we care about. 12643 */ 12644 if (pkgLite.recommendedInstallLocation 12645 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12646 pkgLite.recommendedInstallLocation 12647 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12648 } 12649 } 12650 } 12651 12652 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12653 int loc = pkgLite.recommendedInstallLocation; 12654 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12655 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12656 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12657 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12658 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12659 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12660 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12661 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12662 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12663 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12664 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12665 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12666 } else { 12667 // Override with defaults if needed. 12668 loc = installLocationPolicy(pkgLite); 12669 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12670 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12671 } else if (!onSd && !onInt) { 12672 // Override install location with flags 12673 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12674 // Set the flag to install on external media. 12675 installFlags |= PackageManager.INSTALL_EXTERNAL; 12676 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12677 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12678 if (DEBUG_EPHEMERAL) { 12679 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12680 } 12681 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12682 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12683 |PackageManager.INSTALL_INTERNAL); 12684 } else { 12685 // Make sure the flag for installing on external 12686 // media is unset 12687 installFlags |= PackageManager.INSTALL_INTERNAL; 12688 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12689 } 12690 } 12691 } 12692 } 12693 12694 final InstallArgs args = createInstallArgs(this); 12695 mArgs = args; 12696 12697 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12698 // TODO: http://b/22976637 12699 // Apps installed for "all" users use the device owner to verify the app 12700 UserHandle verifierUser = getUser(); 12701 if (verifierUser == UserHandle.ALL) { 12702 verifierUser = UserHandle.SYSTEM; 12703 } 12704 12705 /* 12706 * Determine if we have any installed package verifiers. If we 12707 * do, then we'll defer to them to verify the packages. 12708 */ 12709 final int requiredUid = mRequiredVerifierPackage == null ? -1 12710 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12711 verifierUser.getIdentifier()); 12712 if (!origin.existing && requiredUid != -1 12713 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12714 final Intent verification = new Intent( 12715 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12716 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12717 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12718 PACKAGE_MIME_TYPE); 12719 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12720 12721 // Query all live verifiers based on current user state 12722 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12723 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12724 12725 if (DEBUG_VERIFY) { 12726 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12727 + verification.toString() + " with " + pkgLite.verifiers.length 12728 + " optional verifiers"); 12729 } 12730 12731 final int verificationId = mPendingVerificationToken++; 12732 12733 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12734 12735 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12736 installerPackageName); 12737 12738 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12739 installFlags); 12740 12741 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12742 pkgLite.packageName); 12743 12744 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12745 pkgLite.versionCode); 12746 12747 if (verificationInfo != null) { 12748 if (verificationInfo.originatingUri != null) { 12749 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12750 verificationInfo.originatingUri); 12751 } 12752 if (verificationInfo.referrer != null) { 12753 verification.putExtra(Intent.EXTRA_REFERRER, 12754 verificationInfo.referrer); 12755 } 12756 if (verificationInfo.originatingUid >= 0) { 12757 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12758 verificationInfo.originatingUid); 12759 } 12760 if (verificationInfo.installerUid >= 0) { 12761 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12762 verificationInfo.installerUid); 12763 } 12764 } 12765 12766 final PackageVerificationState verificationState = new PackageVerificationState( 12767 requiredUid, args); 12768 12769 mPendingVerification.append(verificationId, verificationState); 12770 12771 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12772 receivers, verificationState); 12773 12774 /* 12775 * If any sufficient verifiers were listed in the package 12776 * manifest, attempt to ask them. 12777 */ 12778 if (sufficientVerifiers != null) { 12779 final int N = sufficientVerifiers.size(); 12780 if (N == 0) { 12781 Slog.i(TAG, "Additional verifiers required, but none installed."); 12782 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12783 } else { 12784 for (int i = 0; i < N; i++) { 12785 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12786 12787 final Intent sufficientIntent = new Intent(verification); 12788 sufficientIntent.setComponent(verifierComponent); 12789 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12790 } 12791 } 12792 } 12793 12794 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12795 mRequiredVerifierPackage, receivers); 12796 if (ret == PackageManager.INSTALL_SUCCEEDED 12797 && mRequiredVerifierPackage != null) { 12798 Trace.asyncTraceBegin( 12799 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12800 /* 12801 * Send the intent to the required verification agent, 12802 * but only start the verification timeout after the 12803 * target BroadcastReceivers have run. 12804 */ 12805 verification.setComponent(requiredVerifierComponent); 12806 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12808 new BroadcastReceiver() { 12809 @Override 12810 public void onReceive(Context context, Intent intent) { 12811 final Message msg = mHandler 12812 .obtainMessage(CHECK_PENDING_VERIFICATION); 12813 msg.arg1 = verificationId; 12814 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12815 } 12816 }, null, 0, null, null); 12817 12818 /* 12819 * We don't want the copy to proceed until verification 12820 * succeeds, so null out this field. 12821 */ 12822 mArgs = null; 12823 } 12824 } else { 12825 /* 12826 * No package verification is enabled, so immediately start 12827 * the remote call to initiate copy using temporary file. 12828 */ 12829 ret = args.copyApk(mContainerService, true); 12830 } 12831 } 12832 12833 mRet = ret; 12834 } 12835 12836 @Override 12837 void handleReturnCode() { 12838 // If mArgs is null, then MCS couldn't be reached. When it 12839 // reconnects, it will try again to install. At that point, this 12840 // will succeed. 12841 if (mArgs != null) { 12842 processPendingInstall(mArgs, mRet); 12843 } 12844 } 12845 12846 @Override 12847 void handleServiceError() { 12848 mArgs = createInstallArgs(this); 12849 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12850 } 12851 12852 public boolean isForwardLocked() { 12853 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12854 } 12855 } 12856 12857 /** 12858 * Used during creation of InstallArgs 12859 * 12860 * @param installFlags package installation flags 12861 * @return true if should be installed on external storage 12862 */ 12863 private static boolean installOnExternalAsec(int installFlags) { 12864 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12865 return false; 12866 } 12867 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12868 return true; 12869 } 12870 return false; 12871 } 12872 12873 /** 12874 * Used during creation of InstallArgs 12875 * 12876 * @param installFlags package installation flags 12877 * @return true if should be installed as forward locked 12878 */ 12879 private static boolean installForwardLocked(int installFlags) { 12880 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12881 } 12882 12883 private InstallArgs createInstallArgs(InstallParams params) { 12884 if (params.move != null) { 12885 return new MoveInstallArgs(params); 12886 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12887 return new AsecInstallArgs(params); 12888 } else { 12889 return new FileInstallArgs(params); 12890 } 12891 } 12892 12893 /** 12894 * Create args that describe an existing installed package. Typically used 12895 * when cleaning up old installs, or used as a move source. 12896 */ 12897 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12898 String resourcePath, String[] instructionSets) { 12899 final boolean isInAsec; 12900 if (installOnExternalAsec(installFlags)) { 12901 /* Apps on SD card are always in ASEC containers. */ 12902 isInAsec = true; 12903 } else if (installForwardLocked(installFlags) 12904 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12905 /* 12906 * Forward-locked apps are only in ASEC containers if they're the 12907 * new style 12908 */ 12909 isInAsec = true; 12910 } else { 12911 isInAsec = false; 12912 } 12913 12914 if (isInAsec) { 12915 return new AsecInstallArgs(codePath, instructionSets, 12916 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12917 } else { 12918 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12919 } 12920 } 12921 12922 static abstract class InstallArgs { 12923 /** @see InstallParams#origin */ 12924 final OriginInfo origin; 12925 /** @see InstallParams#move */ 12926 final MoveInfo move; 12927 12928 final IPackageInstallObserver2 observer; 12929 // Always refers to PackageManager flags only 12930 final int installFlags; 12931 final String installerPackageName; 12932 final String volumeUuid; 12933 final UserHandle user; 12934 final String abiOverride; 12935 final String[] installGrantPermissions; 12936 /** If non-null, drop an async trace when the install completes */ 12937 final String traceMethod; 12938 final int traceCookie; 12939 final Certificate[][] certificates; 12940 12941 // The list of instruction sets supported by this app. This is currently 12942 // only used during the rmdex() phase to clean up resources. We can get rid of this 12943 // if we move dex files under the common app path. 12944 /* nullable */ String[] instructionSets; 12945 12946 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12947 int installFlags, String installerPackageName, String volumeUuid, 12948 UserHandle user, String[] instructionSets, 12949 String abiOverride, String[] installGrantPermissions, 12950 String traceMethod, int traceCookie, Certificate[][] certificates) { 12951 this.origin = origin; 12952 this.move = move; 12953 this.installFlags = installFlags; 12954 this.observer = observer; 12955 this.installerPackageName = installerPackageName; 12956 this.volumeUuid = volumeUuid; 12957 this.user = user; 12958 this.instructionSets = instructionSets; 12959 this.abiOverride = abiOverride; 12960 this.installGrantPermissions = installGrantPermissions; 12961 this.traceMethod = traceMethod; 12962 this.traceCookie = traceCookie; 12963 this.certificates = certificates; 12964 } 12965 12966 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12967 abstract int doPreInstall(int status); 12968 12969 /** 12970 * Rename package into final resting place. All paths on the given 12971 * scanned package should be updated to reflect the rename. 12972 */ 12973 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12974 abstract int doPostInstall(int status, int uid); 12975 12976 /** @see PackageSettingBase#codePathString */ 12977 abstract String getCodePath(); 12978 /** @see PackageSettingBase#resourcePathString */ 12979 abstract String getResourcePath(); 12980 12981 // Need installer lock especially for dex file removal. 12982 abstract void cleanUpResourcesLI(); 12983 abstract boolean doPostDeleteLI(boolean delete); 12984 12985 /** 12986 * Called before the source arguments are copied. This is used mostly 12987 * for MoveParams when it needs to read the source file to put it in the 12988 * destination. 12989 */ 12990 int doPreCopy() { 12991 return PackageManager.INSTALL_SUCCEEDED; 12992 } 12993 12994 /** 12995 * Called after the source arguments are copied. This is used mostly for 12996 * MoveParams when it needs to read the source file to put it in the 12997 * destination. 12998 */ 12999 int doPostCopy(int uid) { 13000 return PackageManager.INSTALL_SUCCEEDED; 13001 } 13002 13003 protected boolean isFwdLocked() { 13004 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13005 } 13006 13007 protected boolean isExternalAsec() { 13008 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13009 } 13010 13011 protected boolean isEphemeral() { 13012 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13013 } 13014 13015 UserHandle getUser() { 13016 return user; 13017 } 13018 } 13019 13020 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13021 if (!allCodePaths.isEmpty()) { 13022 if (instructionSets == null) { 13023 throw new IllegalStateException("instructionSet == null"); 13024 } 13025 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13026 for (String codePath : allCodePaths) { 13027 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13028 try { 13029 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13030 } catch (InstallerException ignored) { 13031 } 13032 } 13033 } 13034 } 13035 } 13036 13037 /** 13038 * Logic to handle installation of non-ASEC applications, including copying 13039 * and renaming logic. 13040 */ 13041 class FileInstallArgs extends InstallArgs { 13042 private File codeFile; 13043 private File resourceFile; 13044 13045 // Example topology: 13046 // /data/app/com.example/base.apk 13047 // /data/app/com.example/split_foo.apk 13048 // /data/app/com.example/lib/arm/libfoo.so 13049 // /data/app/com.example/lib/arm64/libfoo.so 13050 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13051 13052 /** New install */ 13053 FileInstallArgs(InstallParams params) { 13054 super(params.origin, params.move, params.observer, params.installFlags, 13055 params.installerPackageName, params.volumeUuid, 13056 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13057 params.grantedRuntimePermissions, 13058 params.traceMethod, params.traceCookie, params.certificates); 13059 if (isFwdLocked()) { 13060 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13061 } 13062 } 13063 13064 /** Existing install */ 13065 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13066 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13067 null, null, null, 0, null /*certificates*/); 13068 this.codeFile = (codePath != null) ? new File(codePath) : null; 13069 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13070 } 13071 13072 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13074 try { 13075 return doCopyApk(imcs, temp); 13076 } finally { 13077 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13078 } 13079 } 13080 13081 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13082 if (origin.staged) { 13083 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13084 codeFile = origin.file; 13085 resourceFile = origin.file; 13086 return PackageManager.INSTALL_SUCCEEDED; 13087 } 13088 13089 try { 13090 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13091 final File tempDir = 13092 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13093 codeFile = tempDir; 13094 resourceFile = tempDir; 13095 } catch (IOException e) { 13096 Slog.w(TAG, "Failed to create copy file: " + e); 13097 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13098 } 13099 13100 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13101 @Override 13102 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13103 if (!FileUtils.isValidExtFilename(name)) { 13104 throw new IllegalArgumentException("Invalid filename: " + name); 13105 } 13106 try { 13107 final File file = new File(codeFile, name); 13108 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13109 O_RDWR | O_CREAT, 0644); 13110 Os.chmod(file.getAbsolutePath(), 0644); 13111 return new ParcelFileDescriptor(fd); 13112 } catch (ErrnoException e) { 13113 throw new RemoteException("Failed to open: " + e.getMessage()); 13114 } 13115 } 13116 }; 13117 13118 int ret = PackageManager.INSTALL_SUCCEEDED; 13119 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13120 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13121 Slog.e(TAG, "Failed to copy package"); 13122 return ret; 13123 } 13124 13125 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13126 NativeLibraryHelper.Handle handle = null; 13127 try { 13128 handle = NativeLibraryHelper.Handle.create(codeFile); 13129 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13130 abiOverride); 13131 } catch (IOException e) { 13132 Slog.e(TAG, "Copying native libraries failed", e); 13133 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13134 } finally { 13135 IoUtils.closeQuietly(handle); 13136 } 13137 13138 return ret; 13139 } 13140 13141 int doPreInstall(int status) { 13142 if (status != PackageManager.INSTALL_SUCCEEDED) { 13143 cleanUp(); 13144 } 13145 return status; 13146 } 13147 13148 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13149 if (status != PackageManager.INSTALL_SUCCEEDED) { 13150 cleanUp(); 13151 return false; 13152 } 13153 13154 final File targetDir = codeFile.getParentFile(); 13155 final File beforeCodeFile = codeFile; 13156 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13157 13158 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13159 try { 13160 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13161 } catch (ErrnoException e) { 13162 Slog.w(TAG, "Failed to rename", e); 13163 return false; 13164 } 13165 13166 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13167 Slog.w(TAG, "Failed to restorecon"); 13168 return false; 13169 } 13170 13171 // Reflect the rename internally 13172 codeFile = afterCodeFile; 13173 resourceFile = afterCodeFile; 13174 13175 // Reflect the rename in scanned details 13176 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13177 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13178 afterCodeFile, pkg.baseCodePath)); 13179 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13180 afterCodeFile, pkg.splitCodePaths)); 13181 13182 // Reflect the rename in app info 13183 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13184 pkg.setApplicationInfoCodePath(pkg.codePath); 13185 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13186 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13187 pkg.setApplicationInfoResourcePath(pkg.codePath); 13188 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13189 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13190 13191 return true; 13192 } 13193 13194 int doPostInstall(int status, int uid) { 13195 if (status != PackageManager.INSTALL_SUCCEEDED) { 13196 cleanUp(); 13197 } 13198 return status; 13199 } 13200 13201 @Override 13202 String getCodePath() { 13203 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13204 } 13205 13206 @Override 13207 String getResourcePath() { 13208 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13209 } 13210 13211 private boolean cleanUp() { 13212 if (codeFile == null || !codeFile.exists()) { 13213 return false; 13214 } 13215 13216 removeCodePathLI(codeFile); 13217 13218 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13219 resourceFile.delete(); 13220 } 13221 13222 return true; 13223 } 13224 13225 void cleanUpResourcesLI() { 13226 // Try enumerating all code paths before deleting 13227 List<String> allCodePaths = Collections.EMPTY_LIST; 13228 if (codeFile != null && codeFile.exists()) { 13229 try { 13230 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13231 allCodePaths = pkg.getAllCodePaths(); 13232 } catch (PackageParserException e) { 13233 // Ignored; we tried our best 13234 } 13235 } 13236 13237 cleanUp(); 13238 removeDexFiles(allCodePaths, instructionSets); 13239 } 13240 13241 boolean doPostDeleteLI(boolean delete) { 13242 // XXX err, shouldn't we respect the delete flag? 13243 cleanUpResourcesLI(); 13244 return true; 13245 } 13246 } 13247 13248 private boolean isAsecExternal(String cid) { 13249 final String asecPath = PackageHelper.getSdFilesystem(cid); 13250 return !asecPath.startsWith(mAsecInternalPath); 13251 } 13252 13253 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13254 PackageManagerException { 13255 if (copyRet < 0) { 13256 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13257 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13258 throw new PackageManagerException(copyRet, message); 13259 } 13260 } 13261 } 13262 13263 /** 13264 * Extract the MountService "container ID" from the full code path of an 13265 * .apk. 13266 */ 13267 static String cidFromCodePath(String fullCodePath) { 13268 int eidx = fullCodePath.lastIndexOf("/"); 13269 String subStr1 = fullCodePath.substring(0, eidx); 13270 int sidx = subStr1.lastIndexOf("/"); 13271 return subStr1.substring(sidx+1, eidx); 13272 } 13273 13274 /** 13275 * Logic to handle installation of ASEC applications, including copying and 13276 * renaming logic. 13277 */ 13278 class AsecInstallArgs extends InstallArgs { 13279 static final String RES_FILE_NAME = "pkg.apk"; 13280 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13281 13282 String cid; 13283 String packagePath; 13284 String resourcePath; 13285 13286 /** New install */ 13287 AsecInstallArgs(InstallParams params) { 13288 super(params.origin, params.move, params.observer, params.installFlags, 13289 params.installerPackageName, params.volumeUuid, 13290 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13291 params.grantedRuntimePermissions, 13292 params.traceMethod, params.traceCookie, params.certificates); 13293 } 13294 13295 /** Existing install */ 13296 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13297 boolean isExternal, boolean isForwardLocked) { 13298 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13299 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13300 instructionSets, null, null, null, 0, null /*certificates*/); 13301 // Hackily pretend we're still looking at a full code path 13302 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13303 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13304 } 13305 13306 // Extract cid from fullCodePath 13307 int eidx = fullCodePath.lastIndexOf("/"); 13308 String subStr1 = fullCodePath.substring(0, eidx); 13309 int sidx = subStr1.lastIndexOf("/"); 13310 cid = subStr1.substring(sidx+1, eidx); 13311 setMountPath(subStr1); 13312 } 13313 13314 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13315 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13316 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13317 instructionSets, null, null, null, 0, null /*certificates*/); 13318 this.cid = cid; 13319 setMountPath(PackageHelper.getSdDir(cid)); 13320 } 13321 13322 void createCopyFile() { 13323 cid = mInstallerService.allocateExternalStageCidLegacy(); 13324 } 13325 13326 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13327 if (origin.staged && origin.cid != null) { 13328 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13329 cid = origin.cid; 13330 setMountPath(PackageHelper.getSdDir(cid)); 13331 return PackageManager.INSTALL_SUCCEEDED; 13332 } 13333 13334 if (temp) { 13335 createCopyFile(); 13336 } else { 13337 /* 13338 * Pre-emptively destroy the container since it's destroyed if 13339 * copying fails due to it existing anyway. 13340 */ 13341 PackageHelper.destroySdDir(cid); 13342 } 13343 13344 final String newMountPath = imcs.copyPackageToContainer( 13345 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13346 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13347 13348 if (newMountPath != null) { 13349 setMountPath(newMountPath); 13350 return PackageManager.INSTALL_SUCCEEDED; 13351 } else { 13352 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13353 } 13354 } 13355 13356 @Override 13357 String getCodePath() { 13358 return packagePath; 13359 } 13360 13361 @Override 13362 String getResourcePath() { 13363 return resourcePath; 13364 } 13365 13366 int doPreInstall(int status) { 13367 if (status != PackageManager.INSTALL_SUCCEEDED) { 13368 // Destroy container 13369 PackageHelper.destroySdDir(cid); 13370 } else { 13371 boolean mounted = PackageHelper.isContainerMounted(cid); 13372 if (!mounted) { 13373 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13374 Process.SYSTEM_UID); 13375 if (newMountPath != null) { 13376 setMountPath(newMountPath); 13377 } else { 13378 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13379 } 13380 } 13381 } 13382 return status; 13383 } 13384 13385 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13386 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13387 String newMountPath = null; 13388 if (PackageHelper.isContainerMounted(cid)) { 13389 // Unmount the container 13390 if (!PackageHelper.unMountSdDir(cid)) { 13391 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13392 return false; 13393 } 13394 } 13395 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13396 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13397 " which might be stale. Will try to clean up."); 13398 // Clean up the stale container and proceed to recreate. 13399 if (!PackageHelper.destroySdDir(newCacheId)) { 13400 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13401 return false; 13402 } 13403 // Successfully cleaned up stale container. Try to rename again. 13404 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13405 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13406 + " inspite of cleaning it up."); 13407 return false; 13408 } 13409 } 13410 if (!PackageHelper.isContainerMounted(newCacheId)) { 13411 Slog.w(TAG, "Mounting container " + newCacheId); 13412 newMountPath = PackageHelper.mountSdDir(newCacheId, 13413 getEncryptKey(), Process.SYSTEM_UID); 13414 } else { 13415 newMountPath = PackageHelper.getSdDir(newCacheId); 13416 } 13417 if (newMountPath == null) { 13418 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13419 return false; 13420 } 13421 Log.i(TAG, "Succesfully renamed " + cid + 13422 " to " + newCacheId + 13423 " at new path: " + newMountPath); 13424 cid = newCacheId; 13425 13426 final File beforeCodeFile = new File(packagePath); 13427 setMountPath(newMountPath); 13428 final File afterCodeFile = new File(packagePath); 13429 13430 // Reflect the rename in scanned details 13431 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13432 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13433 afterCodeFile, pkg.baseCodePath)); 13434 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13435 afterCodeFile, pkg.splitCodePaths)); 13436 13437 // Reflect the rename in app info 13438 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13439 pkg.setApplicationInfoCodePath(pkg.codePath); 13440 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13441 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13442 pkg.setApplicationInfoResourcePath(pkg.codePath); 13443 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13444 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13445 13446 return true; 13447 } 13448 13449 private void setMountPath(String mountPath) { 13450 final File mountFile = new File(mountPath); 13451 13452 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13453 if (monolithicFile.exists()) { 13454 packagePath = monolithicFile.getAbsolutePath(); 13455 if (isFwdLocked()) { 13456 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13457 } else { 13458 resourcePath = packagePath; 13459 } 13460 } else { 13461 packagePath = mountFile.getAbsolutePath(); 13462 resourcePath = packagePath; 13463 } 13464 } 13465 13466 int doPostInstall(int status, int uid) { 13467 if (status != PackageManager.INSTALL_SUCCEEDED) { 13468 cleanUp(); 13469 } else { 13470 final int groupOwner; 13471 final String protectedFile; 13472 if (isFwdLocked()) { 13473 groupOwner = UserHandle.getSharedAppGid(uid); 13474 protectedFile = RES_FILE_NAME; 13475 } else { 13476 groupOwner = -1; 13477 protectedFile = null; 13478 } 13479 13480 if (uid < Process.FIRST_APPLICATION_UID 13481 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13482 Slog.e(TAG, "Failed to finalize " + cid); 13483 PackageHelper.destroySdDir(cid); 13484 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13485 } 13486 13487 boolean mounted = PackageHelper.isContainerMounted(cid); 13488 if (!mounted) { 13489 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13490 } 13491 } 13492 return status; 13493 } 13494 13495 private void cleanUp() { 13496 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13497 13498 // Destroy secure container 13499 PackageHelper.destroySdDir(cid); 13500 } 13501 13502 private List<String> getAllCodePaths() { 13503 final File codeFile = new File(getCodePath()); 13504 if (codeFile != null && codeFile.exists()) { 13505 try { 13506 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13507 return pkg.getAllCodePaths(); 13508 } catch (PackageParserException e) { 13509 // Ignored; we tried our best 13510 } 13511 } 13512 return Collections.EMPTY_LIST; 13513 } 13514 13515 void cleanUpResourcesLI() { 13516 // Enumerate all code paths before deleting 13517 cleanUpResourcesLI(getAllCodePaths()); 13518 } 13519 13520 private void cleanUpResourcesLI(List<String> allCodePaths) { 13521 cleanUp(); 13522 removeDexFiles(allCodePaths, instructionSets); 13523 } 13524 13525 String getPackageName() { 13526 return getAsecPackageName(cid); 13527 } 13528 13529 boolean doPostDeleteLI(boolean delete) { 13530 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13531 final List<String> allCodePaths = getAllCodePaths(); 13532 boolean mounted = PackageHelper.isContainerMounted(cid); 13533 if (mounted) { 13534 // Unmount first 13535 if (PackageHelper.unMountSdDir(cid)) { 13536 mounted = false; 13537 } 13538 } 13539 if (!mounted && delete) { 13540 cleanUpResourcesLI(allCodePaths); 13541 } 13542 return !mounted; 13543 } 13544 13545 @Override 13546 int doPreCopy() { 13547 if (isFwdLocked()) { 13548 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13549 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13551 } 13552 } 13553 13554 return PackageManager.INSTALL_SUCCEEDED; 13555 } 13556 13557 @Override 13558 int doPostCopy(int uid) { 13559 if (isFwdLocked()) { 13560 if (uid < Process.FIRST_APPLICATION_UID 13561 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13562 RES_FILE_NAME)) { 13563 Slog.e(TAG, "Failed to finalize " + cid); 13564 PackageHelper.destroySdDir(cid); 13565 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13566 } 13567 } 13568 13569 return PackageManager.INSTALL_SUCCEEDED; 13570 } 13571 } 13572 13573 /** 13574 * Logic to handle movement of existing installed applications. 13575 */ 13576 class MoveInstallArgs extends InstallArgs { 13577 private File codeFile; 13578 private File resourceFile; 13579 13580 /** New install */ 13581 MoveInstallArgs(InstallParams params) { 13582 super(params.origin, params.move, params.observer, params.installFlags, 13583 params.installerPackageName, params.volumeUuid, 13584 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13585 params.grantedRuntimePermissions, 13586 params.traceMethod, params.traceCookie, params.certificates); 13587 } 13588 13589 int copyApk(IMediaContainerService imcs, boolean temp) { 13590 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13591 + move.fromUuid + " to " + move.toUuid); 13592 synchronized (mInstaller) { 13593 try { 13594 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13595 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13596 } catch (InstallerException e) { 13597 Slog.w(TAG, "Failed to move app", e); 13598 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13599 } 13600 } 13601 13602 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13603 resourceFile = codeFile; 13604 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13605 13606 return PackageManager.INSTALL_SUCCEEDED; 13607 } 13608 13609 int doPreInstall(int status) { 13610 if (status != PackageManager.INSTALL_SUCCEEDED) { 13611 cleanUp(move.toUuid); 13612 } 13613 return status; 13614 } 13615 13616 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13617 if (status != PackageManager.INSTALL_SUCCEEDED) { 13618 cleanUp(move.toUuid); 13619 return false; 13620 } 13621 13622 // Reflect the move in app info 13623 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13624 pkg.setApplicationInfoCodePath(pkg.codePath); 13625 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13626 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13627 pkg.setApplicationInfoResourcePath(pkg.codePath); 13628 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13629 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13630 13631 return true; 13632 } 13633 13634 int doPostInstall(int status, int uid) { 13635 if (status == PackageManager.INSTALL_SUCCEEDED) { 13636 cleanUp(move.fromUuid); 13637 } else { 13638 cleanUp(move.toUuid); 13639 } 13640 return status; 13641 } 13642 13643 @Override 13644 String getCodePath() { 13645 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13646 } 13647 13648 @Override 13649 String getResourcePath() { 13650 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13651 } 13652 13653 private boolean cleanUp(String volumeUuid) { 13654 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13655 move.dataAppName); 13656 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13657 final int[] userIds = sUserManager.getUserIds(); 13658 synchronized (mInstallLock) { 13659 // Clean up both app data and code 13660 // All package moves are frozen until finished 13661 for (int userId : userIds) { 13662 try { 13663 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13664 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13665 } catch (InstallerException e) { 13666 Slog.w(TAG, String.valueOf(e)); 13667 } 13668 } 13669 removeCodePathLI(codeFile); 13670 } 13671 return true; 13672 } 13673 13674 void cleanUpResourcesLI() { 13675 throw new UnsupportedOperationException(); 13676 } 13677 13678 boolean doPostDeleteLI(boolean delete) { 13679 throw new UnsupportedOperationException(); 13680 } 13681 } 13682 13683 static String getAsecPackageName(String packageCid) { 13684 int idx = packageCid.lastIndexOf("-"); 13685 if (idx == -1) { 13686 return packageCid; 13687 } 13688 return packageCid.substring(0, idx); 13689 } 13690 13691 // Utility method used to create code paths based on package name and available index. 13692 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13693 String idxStr = ""; 13694 int idx = 1; 13695 // Fall back to default value of idx=1 if prefix is not 13696 // part of oldCodePath 13697 if (oldCodePath != null) { 13698 String subStr = oldCodePath; 13699 // Drop the suffix right away 13700 if (suffix != null && subStr.endsWith(suffix)) { 13701 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13702 } 13703 // If oldCodePath already contains prefix find out the 13704 // ending index to either increment or decrement. 13705 int sidx = subStr.lastIndexOf(prefix); 13706 if (sidx != -1) { 13707 subStr = subStr.substring(sidx + prefix.length()); 13708 if (subStr != null) { 13709 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13710 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13711 } 13712 try { 13713 idx = Integer.parseInt(subStr); 13714 if (idx <= 1) { 13715 idx++; 13716 } else { 13717 idx--; 13718 } 13719 } catch(NumberFormatException e) { 13720 } 13721 } 13722 } 13723 } 13724 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13725 return prefix + idxStr; 13726 } 13727 13728 private File getNextCodePath(File targetDir, String packageName) { 13729 int suffix = 1; 13730 File result; 13731 do { 13732 result = new File(targetDir, packageName + "-" + suffix); 13733 suffix++; 13734 } while (result.exists()); 13735 return result; 13736 } 13737 13738 // Utility method that returns the relative package path with respect 13739 // to the installation directory. Like say for /data/data/com.test-1.apk 13740 // string com.test-1 is returned. 13741 static String deriveCodePathName(String codePath) { 13742 if (codePath == null) { 13743 return null; 13744 } 13745 final File codeFile = new File(codePath); 13746 final String name = codeFile.getName(); 13747 if (codeFile.isDirectory()) { 13748 return name; 13749 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13750 final int lastDot = name.lastIndexOf('.'); 13751 return name.substring(0, lastDot); 13752 } else { 13753 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13754 return null; 13755 } 13756 } 13757 13758 static class PackageInstalledInfo { 13759 String name; 13760 int uid; 13761 // The set of users that originally had this package installed. 13762 int[] origUsers; 13763 // The set of users that now have this package installed. 13764 int[] newUsers; 13765 PackageParser.Package pkg; 13766 int returnCode; 13767 String returnMsg; 13768 PackageRemovedInfo removedInfo; 13769 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13770 13771 public void setError(int code, String msg) { 13772 setReturnCode(code); 13773 setReturnMessage(msg); 13774 Slog.w(TAG, msg); 13775 } 13776 13777 public void setError(String msg, PackageParserException e) { 13778 setReturnCode(e.error); 13779 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13780 Slog.w(TAG, msg, e); 13781 } 13782 13783 public void setError(String msg, PackageManagerException e) { 13784 returnCode = e.error; 13785 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13786 Slog.w(TAG, msg, e); 13787 } 13788 13789 public void setReturnCode(int returnCode) { 13790 this.returnCode = returnCode; 13791 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13792 for (int i = 0; i < childCount; i++) { 13793 addedChildPackages.valueAt(i).returnCode = returnCode; 13794 } 13795 } 13796 13797 private void setReturnMessage(String returnMsg) { 13798 this.returnMsg = returnMsg; 13799 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13800 for (int i = 0; i < childCount; i++) { 13801 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13802 } 13803 } 13804 13805 // In some error cases we want to convey more info back to the observer 13806 String origPackage; 13807 String origPermission; 13808 } 13809 13810 /* 13811 * Install a non-existing package. 13812 */ 13813 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13814 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13815 PackageInstalledInfo res) { 13816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13817 13818 // Remember this for later, in case we need to rollback this install 13819 String pkgName = pkg.packageName; 13820 13821 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13822 13823 synchronized(mPackages) { 13824 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13825 // A package with the same name is already installed, though 13826 // it has been renamed to an older name. The package we 13827 // are trying to install should be installed as an update to 13828 // the existing one, but that has not been requested, so bail. 13829 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13830 + " without first uninstalling package running as " 13831 + mSettings.mRenamedPackages.get(pkgName)); 13832 return; 13833 } 13834 if (mPackages.containsKey(pkgName)) { 13835 // Don't allow installation over an existing package with the same name. 13836 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13837 + " without first uninstalling."); 13838 return; 13839 } 13840 } 13841 13842 try { 13843 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13844 System.currentTimeMillis(), user); 13845 13846 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13847 13848 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13849 prepareAppDataAfterInstallLIF(newPackage); 13850 13851 } else { 13852 // Remove package from internal structures, but keep around any 13853 // data that might have already existed 13854 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13855 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13856 } 13857 } catch (PackageManagerException e) { 13858 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13859 } 13860 13861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13862 } 13863 13864 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13865 // Can't rotate keys during boot or if sharedUser. 13866 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13867 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13868 return false; 13869 } 13870 // app is using upgradeKeySets; make sure all are valid 13871 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13872 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13873 for (int i = 0; i < upgradeKeySets.length; i++) { 13874 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13875 Slog.wtf(TAG, "Package " 13876 + (oldPs.name != null ? oldPs.name : "<null>") 13877 + " contains upgrade-key-set reference to unknown key-set: " 13878 + upgradeKeySets[i] 13879 + " reverting to signatures check."); 13880 return false; 13881 } 13882 } 13883 return true; 13884 } 13885 13886 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13887 // Upgrade keysets are being used. Determine if new package has a superset of the 13888 // required keys. 13889 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13890 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13891 for (int i = 0; i < upgradeKeySets.length; i++) { 13892 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13893 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13894 return true; 13895 } 13896 } 13897 return false; 13898 } 13899 13900 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13901 try (DigestInputStream digestStream = 13902 new DigestInputStream(new FileInputStream(file), digest)) { 13903 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13904 } 13905 } 13906 13907 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13908 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13909 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13910 13911 final PackageParser.Package oldPackage; 13912 final String pkgName = pkg.packageName; 13913 final int[] allUsers; 13914 final int[] installedUsers; 13915 13916 synchronized(mPackages) { 13917 oldPackage = mPackages.get(pkgName); 13918 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13919 13920 // don't allow upgrade to target a release SDK from a pre-release SDK 13921 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13922 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13923 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13924 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13925 if (oldTargetsPreRelease 13926 && !newTargetsPreRelease 13927 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13928 Slog.w(TAG, "Can't install package targeting released sdk"); 13929 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13930 return; 13931 } 13932 13933 // don't allow an upgrade from full to ephemeral 13934 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13935 if (isEphemeral && !oldIsEphemeral) { 13936 // can't downgrade from full to ephemeral 13937 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13938 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13939 return; 13940 } 13941 13942 // verify signatures are valid 13943 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13944 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13945 if (!checkUpgradeKeySetLP(ps, pkg)) { 13946 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13947 "New package not signed by keys specified by upgrade-keysets: " 13948 + pkgName); 13949 return; 13950 } 13951 } else { 13952 // default to original signature matching 13953 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13954 != PackageManager.SIGNATURE_MATCH) { 13955 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13956 "New package has a different signature: " + pkgName); 13957 return; 13958 } 13959 } 13960 13961 // don't allow a system upgrade unless the upgrade hash matches 13962 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13963 byte[] digestBytes = null; 13964 try { 13965 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13966 updateDigest(digest, new File(pkg.baseCodePath)); 13967 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13968 for (String path : pkg.splitCodePaths) { 13969 updateDigest(digest, new File(path)); 13970 } 13971 } 13972 digestBytes = digest.digest(); 13973 } catch (NoSuchAlgorithmException | IOException e) { 13974 res.setError(INSTALL_FAILED_INVALID_APK, 13975 "Could not compute hash: " + pkgName); 13976 return; 13977 } 13978 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13979 res.setError(INSTALL_FAILED_INVALID_APK, 13980 "New package fails restrict-update check: " + pkgName); 13981 return; 13982 } 13983 // retain upgrade restriction 13984 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13985 } 13986 13987 // Check for shared user id changes 13988 String invalidPackageName = 13989 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13990 if (invalidPackageName != null) { 13991 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13992 "Package " + invalidPackageName + " tried to change user " 13993 + oldPackage.mSharedUserId); 13994 return; 13995 } 13996 13997 // In case of rollback, remember per-user/profile install state 13998 allUsers = sUserManager.getUserIds(); 13999 installedUsers = ps.queryInstalledUsers(allUsers, true); 14000 } 14001 14002 // Update what is removed 14003 res.removedInfo = new PackageRemovedInfo(); 14004 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14005 res.removedInfo.removedPackage = oldPackage.packageName; 14006 res.removedInfo.isUpdate = true; 14007 res.removedInfo.origUsers = installedUsers; 14008 final int childCount = (oldPackage.childPackages != null) 14009 ? oldPackage.childPackages.size() : 0; 14010 for (int i = 0; i < childCount; i++) { 14011 boolean childPackageUpdated = false; 14012 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14013 if (res.addedChildPackages != null) { 14014 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14015 if (childRes != null) { 14016 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14017 childRes.removedInfo.removedPackage = childPkg.packageName; 14018 childRes.removedInfo.isUpdate = true; 14019 childPackageUpdated = true; 14020 } 14021 } 14022 if (!childPackageUpdated) { 14023 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14024 childRemovedRes.removedPackage = childPkg.packageName; 14025 childRemovedRes.isUpdate = false; 14026 childRemovedRes.dataRemoved = true; 14027 synchronized (mPackages) { 14028 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14029 if (childPs != null) { 14030 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14031 } 14032 } 14033 if (res.removedInfo.removedChildPackages == null) { 14034 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14035 } 14036 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14037 } 14038 } 14039 14040 boolean sysPkg = (isSystemApp(oldPackage)); 14041 if (sysPkg) { 14042 // Set the system/privileged flags as needed 14043 final boolean privileged = 14044 (oldPackage.applicationInfo.privateFlags 14045 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14046 final int systemPolicyFlags = policyFlags 14047 | PackageParser.PARSE_IS_SYSTEM 14048 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14049 14050 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14051 user, allUsers, installerPackageName, res); 14052 } else { 14053 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14054 user, allUsers, installerPackageName, res); 14055 } 14056 } 14057 14058 public List<String> getPreviousCodePaths(String packageName) { 14059 final PackageSetting ps = mSettings.mPackages.get(packageName); 14060 final List<String> result = new ArrayList<String>(); 14061 if (ps != null && ps.oldCodePaths != null) { 14062 result.addAll(ps.oldCodePaths); 14063 } 14064 return result; 14065 } 14066 14067 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14068 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14069 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14070 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14071 + deletedPackage); 14072 14073 String pkgName = deletedPackage.packageName; 14074 boolean deletedPkg = true; 14075 boolean addedPkg = false; 14076 boolean updatedSettings = false; 14077 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14078 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14079 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14080 14081 final long origUpdateTime = (pkg.mExtras != null) 14082 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14083 14084 // First delete the existing package while retaining the data directory 14085 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14086 res.removedInfo, true, pkg)) { 14087 // If the existing package wasn't successfully deleted 14088 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14089 deletedPkg = false; 14090 } else { 14091 // Successfully deleted the old package; proceed with replace. 14092 14093 // If deleted package lived in a container, give users a chance to 14094 // relinquish resources before killing. 14095 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14096 if (DEBUG_INSTALL) { 14097 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14098 } 14099 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14100 final ArrayList<String> pkgList = new ArrayList<String>(1); 14101 pkgList.add(deletedPackage.applicationInfo.packageName); 14102 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14103 } 14104 14105 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14106 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14107 clearAppProfilesLIF(pkg); 14108 14109 try { 14110 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14111 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14112 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14113 14114 // Update the in-memory copy of the previous code paths. 14115 PackageSetting ps = mSettings.mPackages.get(pkgName); 14116 if (!killApp) { 14117 if (ps.oldCodePaths == null) { 14118 ps.oldCodePaths = new ArraySet<>(); 14119 } 14120 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14121 if (deletedPackage.splitCodePaths != null) { 14122 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14123 } 14124 } else { 14125 ps.oldCodePaths = null; 14126 } 14127 if (ps.childPackageNames != null) { 14128 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14129 final String childPkgName = ps.childPackageNames.get(i); 14130 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14131 childPs.oldCodePaths = ps.oldCodePaths; 14132 } 14133 } 14134 prepareAppDataAfterInstallLIF(newPackage); 14135 addedPkg = true; 14136 } catch (PackageManagerException e) { 14137 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14138 } 14139 } 14140 14141 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14142 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14143 14144 // Revert all internal state mutations and added folders for the failed install 14145 if (addedPkg) { 14146 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14147 res.removedInfo, true, null); 14148 } 14149 14150 // Restore the old package 14151 if (deletedPkg) { 14152 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14153 File restoreFile = new File(deletedPackage.codePath); 14154 // Parse old package 14155 boolean oldExternal = isExternal(deletedPackage); 14156 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14157 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14158 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14159 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14160 try { 14161 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14162 null); 14163 } catch (PackageManagerException e) { 14164 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14165 + e.getMessage()); 14166 return; 14167 } 14168 14169 synchronized (mPackages) { 14170 // Ensure the installer package name up to date 14171 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14172 14173 // Update permissions for restored package 14174 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14175 14176 mSettings.writeLPr(); 14177 } 14178 14179 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14180 } 14181 } else { 14182 synchronized (mPackages) { 14183 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14184 if (ps != null) { 14185 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14186 if (res.removedInfo.removedChildPackages != null) { 14187 final int childCount = res.removedInfo.removedChildPackages.size(); 14188 // Iterate in reverse as we may modify the collection 14189 for (int i = childCount - 1; i >= 0; i--) { 14190 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14191 if (res.addedChildPackages.containsKey(childPackageName)) { 14192 res.removedInfo.removedChildPackages.removeAt(i); 14193 } else { 14194 PackageRemovedInfo childInfo = res.removedInfo 14195 .removedChildPackages.valueAt(i); 14196 childInfo.removedForAllUsers = mPackages.get( 14197 childInfo.removedPackage) == null; 14198 } 14199 } 14200 } 14201 } 14202 } 14203 } 14204 } 14205 14206 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14207 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14208 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14209 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14210 + ", old=" + deletedPackage); 14211 14212 final boolean disabledSystem; 14213 14214 // Remove existing system package 14215 removePackageLI(deletedPackage, true); 14216 14217 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14218 if (!disabledSystem) { 14219 // We didn't need to disable the .apk as a current system package, 14220 // which means we are replacing another update that is already 14221 // installed. We need to make sure to delete the older one's .apk. 14222 res.removedInfo.args = createInstallArgsForExisting(0, 14223 deletedPackage.applicationInfo.getCodePath(), 14224 deletedPackage.applicationInfo.getResourcePath(), 14225 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14226 } else { 14227 res.removedInfo.args = null; 14228 } 14229 14230 // Successfully disabled the old package. Now proceed with re-installation 14231 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14232 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14233 clearAppProfilesLIF(pkg); 14234 14235 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14236 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14237 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14238 14239 PackageParser.Package newPackage = null; 14240 try { 14241 // Add the package to the internal data structures 14242 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14243 14244 // Set the update and install times 14245 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14246 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14247 System.currentTimeMillis()); 14248 14249 // Update the package dynamic state if succeeded 14250 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14251 // Now that the install succeeded make sure we remove data 14252 // directories for any child package the update removed. 14253 final int deletedChildCount = (deletedPackage.childPackages != null) 14254 ? deletedPackage.childPackages.size() : 0; 14255 final int newChildCount = (newPackage.childPackages != null) 14256 ? newPackage.childPackages.size() : 0; 14257 for (int i = 0; i < deletedChildCount; i++) { 14258 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14259 boolean childPackageDeleted = true; 14260 for (int j = 0; j < newChildCount; j++) { 14261 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14262 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14263 childPackageDeleted = false; 14264 break; 14265 } 14266 } 14267 if (childPackageDeleted) { 14268 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14269 deletedChildPkg.packageName); 14270 if (ps != null && res.removedInfo.removedChildPackages != null) { 14271 PackageRemovedInfo removedChildRes = res.removedInfo 14272 .removedChildPackages.get(deletedChildPkg.packageName); 14273 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14274 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14275 } 14276 } 14277 } 14278 14279 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14280 prepareAppDataAfterInstallLIF(newPackage); 14281 } 14282 } catch (PackageManagerException e) { 14283 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14284 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14285 } 14286 14287 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14288 // Re installation failed. Restore old information 14289 // Remove new pkg information 14290 if (newPackage != null) { 14291 removeInstalledPackageLI(newPackage, true); 14292 } 14293 // Add back the old system package 14294 try { 14295 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14296 } catch (PackageManagerException e) { 14297 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14298 } 14299 14300 synchronized (mPackages) { 14301 if (disabledSystem) { 14302 enableSystemPackageLPw(deletedPackage); 14303 } 14304 14305 // Ensure the installer package name up to date 14306 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14307 14308 // Update permissions for restored package 14309 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14310 14311 mSettings.writeLPr(); 14312 } 14313 14314 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14315 + " after failed upgrade"); 14316 } 14317 } 14318 14319 /** 14320 * Checks whether the parent or any of the child packages have a change shared 14321 * user. For a package to be a valid update the shred users of the parent and 14322 * the children should match. We may later support changing child shared users. 14323 * @param oldPkg The updated package. 14324 * @param newPkg The update package. 14325 * @return The shared user that change between the versions. 14326 */ 14327 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14328 PackageParser.Package newPkg) { 14329 // Check parent shared user 14330 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14331 return newPkg.packageName; 14332 } 14333 // Check child shared users 14334 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14335 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14336 for (int i = 0; i < newChildCount; i++) { 14337 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14338 // If this child was present, did it have the same shared user? 14339 for (int j = 0; j < oldChildCount; j++) { 14340 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14341 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14342 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14343 return newChildPkg.packageName; 14344 } 14345 } 14346 } 14347 return null; 14348 } 14349 14350 private void removeNativeBinariesLI(PackageSetting ps) { 14351 // Remove the lib path for the parent package 14352 if (ps != null) { 14353 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14354 // Remove the lib path for the child packages 14355 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14356 for (int i = 0; i < childCount; i++) { 14357 PackageSetting childPs = null; 14358 synchronized (mPackages) { 14359 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14360 } 14361 if (childPs != null) { 14362 NativeLibraryHelper.removeNativeBinariesLI(childPs 14363 .legacyNativeLibraryPathString); 14364 } 14365 } 14366 } 14367 } 14368 14369 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14370 // Enable the parent package 14371 mSettings.enableSystemPackageLPw(pkg.packageName); 14372 // Enable the child packages 14373 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14374 for (int i = 0; i < childCount; i++) { 14375 PackageParser.Package childPkg = pkg.childPackages.get(i); 14376 mSettings.enableSystemPackageLPw(childPkg.packageName); 14377 } 14378 } 14379 14380 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14381 PackageParser.Package newPkg) { 14382 // Disable the parent package (parent always replaced) 14383 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14384 // Disable the child packages 14385 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14386 for (int i = 0; i < childCount; i++) { 14387 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14388 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14389 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14390 } 14391 return disabled; 14392 } 14393 14394 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14395 String installerPackageName) { 14396 // Enable the parent package 14397 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14398 // Enable the child packages 14399 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14400 for (int i = 0; i < childCount; i++) { 14401 PackageParser.Package childPkg = pkg.childPackages.get(i); 14402 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14403 } 14404 } 14405 14406 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14407 // Collect all used permissions in the UID 14408 ArraySet<String> usedPermissions = new ArraySet<>(); 14409 final int packageCount = su.packages.size(); 14410 for (int i = 0; i < packageCount; i++) { 14411 PackageSetting ps = su.packages.valueAt(i); 14412 if (ps.pkg == null) { 14413 continue; 14414 } 14415 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14416 for (int j = 0; j < requestedPermCount; j++) { 14417 String permission = ps.pkg.requestedPermissions.get(j); 14418 BasePermission bp = mSettings.mPermissions.get(permission); 14419 if (bp != null) { 14420 usedPermissions.add(permission); 14421 } 14422 } 14423 } 14424 14425 PermissionsState permissionsState = su.getPermissionsState(); 14426 // Prune install permissions 14427 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14428 final int installPermCount = installPermStates.size(); 14429 for (int i = installPermCount - 1; i >= 0; i--) { 14430 PermissionState permissionState = installPermStates.get(i); 14431 if (!usedPermissions.contains(permissionState.getName())) { 14432 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14433 if (bp != null) { 14434 permissionsState.revokeInstallPermission(bp); 14435 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14436 PackageManager.MASK_PERMISSION_FLAGS, 0); 14437 } 14438 } 14439 } 14440 14441 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14442 14443 // Prune runtime permissions 14444 for (int userId : allUserIds) { 14445 List<PermissionState> runtimePermStates = permissionsState 14446 .getRuntimePermissionStates(userId); 14447 final int runtimePermCount = runtimePermStates.size(); 14448 for (int i = runtimePermCount - 1; i >= 0; i--) { 14449 PermissionState permissionState = runtimePermStates.get(i); 14450 if (!usedPermissions.contains(permissionState.getName())) { 14451 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14452 if (bp != null) { 14453 permissionsState.revokeRuntimePermission(bp, userId); 14454 permissionsState.updatePermissionFlags(bp, userId, 14455 PackageManager.MASK_PERMISSION_FLAGS, 0); 14456 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14457 runtimePermissionChangedUserIds, userId); 14458 } 14459 } 14460 } 14461 } 14462 14463 return runtimePermissionChangedUserIds; 14464 } 14465 14466 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14467 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14468 // Update the parent package setting 14469 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14470 res, user); 14471 // Update the child packages setting 14472 final int childCount = (newPackage.childPackages != null) 14473 ? newPackage.childPackages.size() : 0; 14474 for (int i = 0; i < childCount; i++) { 14475 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14476 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14477 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14478 childRes.origUsers, childRes, user); 14479 } 14480 } 14481 14482 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14483 String installerPackageName, int[] allUsers, int[] installedForUsers, 14484 PackageInstalledInfo res, UserHandle user) { 14485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14486 14487 String pkgName = newPackage.packageName; 14488 synchronized (mPackages) { 14489 //write settings. the installStatus will be incomplete at this stage. 14490 //note that the new package setting would have already been 14491 //added to mPackages. It hasn't been persisted yet. 14492 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14494 mSettings.writeLPr(); 14495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14496 } 14497 14498 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14499 synchronized (mPackages) { 14500 updatePermissionsLPw(newPackage.packageName, newPackage, 14501 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14502 ? UPDATE_PERMISSIONS_ALL : 0)); 14503 // For system-bundled packages, we assume that installing an upgraded version 14504 // of the package implies that the user actually wants to run that new code, 14505 // so we enable the package. 14506 PackageSetting ps = mSettings.mPackages.get(pkgName); 14507 final int userId = user.getIdentifier(); 14508 if (ps != null) { 14509 if (isSystemApp(newPackage)) { 14510 if (DEBUG_INSTALL) { 14511 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14512 } 14513 // Enable system package for requested users 14514 if (res.origUsers != null) { 14515 for (int origUserId : res.origUsers) { 14516 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14517 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14518 origUserId, installerPackageName); 14519 } 14520 } 14521 } 14522 // Also convey the prior install/uninstall state 14523 if (allUsers != null && installedForUsers != null) { 14524 for (int currentUserId : allUsers) { 14525 final boolean installed = ArrayUtils.contains( 14526 installedForUsers, currentUserId); 14527 if (DEBUG_INSTALL) { 14528 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14529 } 14530 ps.setInstalled(installed, currentUserId); 14531 } 14532 // these install state changes will be persisted in the 14533 // upcoming call to mSettings.writeLPr(). 14534 } 14535 } 14536 // It's implied that when a user requests installation, they want the app to be 14537 // installed and enabled. 14538 if (userId != UserHandle.USER_ALL) { 14539 ps.setInstalled(true, userId); 14540 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14541 } 14542 } 14543 res.name = pkgName; 14544 res.uid = newPackage.applicationInfo.uid; 14545 res.pkg = newPackage; 14546 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14547 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14548 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14549 //to update install status 14550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14551 mSettings.writeLPr(); 14552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14553 } 14554 14555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14556 } 14557 14558 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14559 try { 14560 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14561 installPackageLI(args, res); 14562 } finally { 14563 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14564 } 14565 } 14566 14567 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14568 final int installFlags = args.installFlags; 14569 final String installerPackageName = args.installerPackageName; 14570 final String volumeUuid = args.volumeUuid; 14571 final File tmpPackageFile = new File(args.getCodePath()); 14572 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14573 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14574 || (args.volumeUuid != null)); 14575 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14576 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14577 boolean replace = false; 14578 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14579 if (args.move != null) { 14580 // moving a complete application; perform an initial scan on the new install location 14581 scanFlags |= SCAN_INITIAL; 14582 } 14583 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14584 scanFlags |= SCAN_DONT_KILL_APP; 14585 } 14586 14587 // Result object to be returned 14588 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14589 14590 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14591 14592 // Sanity check 14593 if (ephemeral && (forwardLocked || onExternal)) { 14594 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14595 + " external=" + onExternal); 14596 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14597 return; 14598 } 14599 14600 // Retrieve PackageSettings and parse package 14601 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14602 | PackageParser.PARSE_ENFORCE_CODE 14603 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14604 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14605 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14606 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14607 PackageParser pp = new PackageParser(); 14608 pp.setSeparateProcesses(mSeparateProcesses); 14609 pp.setDisplayMetrics(mMetrics); 14610 14611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14612 final PackageParser.Package pkg; 14613 try { 14614 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14615 } catch (PackageParserException e) { 14616 res.setError("Failed parse during installPackageLI", e); 14617 return; 14618 } finally { 14619 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14620 } 14621 14622 // If we are installing a clustered package add results for the children 14623 if (pkg.childPackages != null) { 14624 synchronized (mPackages) { 14625 final int childCount = pkg.childPackages.size(); 14626 for (int i = 0; i < childCount; i++) { 14627 PackageParser.Package childPkg = pkg.childPackages.get(i); 14628 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14629 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14630 childRes.pkg = childPkg; 14631 childRes.name = childPkg.packageName; 14632 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14633 if (childPs != null) { 14634 childRes.origUsers = childPs.queryInstalledUsers( 14635 sUserManager.getUserIds(), true); 14636 } 14637 if ((mPackages.containsKey(childPkg.packageName))) { 14638 childRes.removedInfo = new PackageRemovedInfo(); 14639 childRes.removedInfo.removedPackage = childPkg.packageName; 14640 } 14641 if (res.addedChildPackages == null) { 14642 res.addedChildPackages = new ArrayMap<>(); 14643 } 14644 res.addedChildPackages.put(childPkg.packageName, childRes); 14645 } 14646 } 14647 } 14648 14649 // If package doesn't declare API override, mark that we have an install 14650 // time CPU ABI override. 14651 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14652 pkg.cpuAbiOverride = args.abiOverride; 14653 } 14654 14655 String pkgName = res.name = pkg.packageName; 14656 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14657 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14658 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14659 return; 14660 } 14661 } 14662 14663 try { 14664 // either use what we've been given or parse directly from the APK 14665 if (args.certificates != null) { 14666 try { 14667 PackageParser.populateCertificates(pkg, args.certificates); 14668 } catch (PackageParserException e) { 14669 // there was something wrong with the certificates we were given; 14670 // try to pull them from the APK 14671 PackageParser.collectCertificates(pkg, parseFlags); 14672 } 14673 } else { 14674 PackageParser.collectCertificates(pkg, parseFlags); 14675 } 14676 } catch (PackageParserException e) { 14677 res.setError("Failed collect during installPackageLI", e); 14678 return; 14679 } 14680 14681 // Get rid of all references to package scan path via parser. 14682 pp = null; 14683 String oldCodePath = null; 14684 boolean systemApp = false; 14685 synchronized (mPackages) { 14686 // Check if installing already existing package 14687 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14688 String oldName = mSettings.mRenamedPackages.get(pkgName); 14689 if (pkg.mOriginalPackages != null 14690 && pkg.mOriginalPackages.contains(oldName) 14691 && mPackages.containsKey(oldName)) { 14692 // This package is derived from an original package, 14693 // and this device has been updating from that original 14694 // name. We must continue using the original name, so 14695 // rename the new package here. 14696 pkg.setPackageName(oldName); 14697 pkgName = pkg.packageName; 14698 replace = true; 14699 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14700 + oldName + " pkgName=" + pkgName); 14701 } else if (mPackages.containsKey(pkgName)) { 14702 // This package, under its official name, already exists 14703 // on the device; we should replace it. 14704 replace = true; 14705 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14706 } 14707 14708 // Child packages are installed through the parent package 14709 if (pkg.parentPackage != null) { 14710 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14711 "Package " + pkg.packageName + " is child of package " 14712 + pkg.parentPackage.parentPackage + ". Child packages " 14713 + "can be updated only through the parent package."); 14714 return; 14715 } 14716 14717 if (replace) { 14718 // Prevent apps opting out from runtime permissions 14719 PackageParser.Package oldPackage = mPackages.get(pkgName); 14720 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14721 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14722 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14723 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14724 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14725 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14726 + " doesn't support runtime permissions but the old" 14727 + " target SDK " + oldTargetSdk + " does."); 14728 return; 14729 } 14730 14731 // Prevent installing of child packages 14732 if (oldPackage.parentPackage != null) { 14733 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14734 "Package " + pkg.packageName + " is child of package " 14735 + oldPackage.parentPackage + ". Child packages " 14736 + "can be updated only through the parent package."); 14737 return; 14738 } 14739 } 14740 } 14741 14742 PackageSetting ps = mSettings.mPackages.get(pkgName); 14743 if (ps != null) { 14744 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14745 14746 // Quick sanity check that we're signed correctly if updating; 14747 // we'll check this again later when scanning, but we want to 14748 // bail early here before tripping over redefined permissions. 14749 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14750 if (!checkUpgradeKeySetLP(ps, pkg)) { 14751 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14752 + pkg.packageName + " upgrade keys do not match the " 14753 + "previously installed version"); 14754 return; 14755 } 14756 } else { 14757 try { 14758 verifySignaturesLP(ps, pkg); 14759 } catch (PackageManagerException e) { 14760 res.setError(e.error, e.getMessage()); 14761 return; 14762 } 14763 } 14764 14765 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14766 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14767 systemApp = (ps.pkg.applicationInfo.flags & 14768 ApplicationInfo.FLAG_SYSTEM) != 0; 14769 } 14770 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14771 } 14772 14773 // Check whether the newly-scanned package wants to define an already-defined perm 14774 int N = pkg.permissions.size(); 14775 for (int i = N-1; i >= 0; i--) { 14776 PackageParser.Permission perm = pkg.permissions.get(i); 14777 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14778 if (bp != null) { 14779 // If the defining package is signed with our cert, it's okay. This 14780 // also includes the "updating the same package" case, of course. 14781 // "updating same package" could also involve key-rotation. 14782 final boolean sigsOk; 14783 if (bp.sourcePackage.equals(pkg.packageName) 14784 && (bp.packageSetting instanceof PackageSetting) 14785 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14786 scanFlags))) { 14787 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14788 } else { 14789 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14790 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14791 } 14792 if (!sigsOk) { 14793 // If the owning package is the system itself, we log but allow 14794 // install to proceed; we fail the install on all other permission 14795 // redefinitions. 14796 if (!bp.sourcePackage.equals("android")) { 14797 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14798 + pkg.packageName + " attempting to redeclare permission " 14799 + perm.info.name + " already owned by " + bp.sourcePackage); 14800 res.origPermission = perm.info.name; 14801 res.origPackage = bp.sourcePackage; 14802 return; 14803 } else { 14804 Slog.w(TAG, "Package " + pkg.packageName 14805 + " attempting to redeclare system permission " 14806 + perm.info.name + "; ignoring new declaration"); 14807 pkg.permissions.remove(i); 14808 } 14809 } 14810 } 14811 } 14812 } 14813 14814 if (systemApp) { 14815 if (onExternal) { 14816 // Abort update; system app can't be replaced with app on sdcard 14817 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14818 "Cannot install updates to system apps on sdcard"); 14819 return; 14820 } else if (ephemeral) { 14821 // Abort update; system app can't be replaced with an ephemeral app 14822 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14823 "Cannot update a system app with an ephemeral app"); 14824 return; 14825 } 14826 } 14827 14828 if (args.move != null) { 14829 // We did an in-place move, so dex is ready to roll 14830 scanFlags |= SCAN_NO_DEX; 14831 scanFlags |= SCAN_MOVE; 14832 14833 synchronized (mPackages) { 14834 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14835 if (ps == null) { 14836 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14837 "Missing settings for moved package " + pkgName); 14838 } 14839 14840 // We moved the entire application as-is, so bring over the 14841 // previously derived ABI information. 14842 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14843 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14844 } 14845 14846 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14847 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14848 scanFlags |= SCAN_NO_DEX; 14849 14850 try { 14851 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14852 args.abiOverride : pkg.cpuAbiOverride); 14853 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14854 true /* extract libs */); 14855 } catch (PackageManagerException pme) { 14856 Slog.e(TAG, "Error deriving application ABI", pme); 14857 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14858 return; 14859 } 14860 14861 // Shared libraries for the package need to be updated. 14862 synchronized (mPackages) { 14863 try { 14864 updateSharedLibrariesLPw(pkg, null); 14865 } catch (PackageManagerException e) { 14866 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14867 } 14868 } 14869 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14870 // Do not run PackageDexOptimizer through the local performDexOpt 14871 // method because `pkg` is not in `mPackages` yet. 14872 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14873 null /* instructionSets */, false /* checkProfiles */, 14874 getCompilerFilterForReason(REASON_INSTALL)); 14875 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14876 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14877 String msg = "Extracting package failed for " + pkgName; 14878 res.setError(INSTALL_FAILED_DEXOPT, msg); 14879 return; 14880 } 14881 14882 // Notify BackgroundDexOptService that the package has been changed. 14883 // If this is an update of a package which used to fail to compile, 14884 // BDOS will remove it from its blacklist. 14885 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14886 } 14887 14888 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14889 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14890 return; 14891 } 14892 14893 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14894 14895 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14896 "installPackageLI")) { 14897 if (replace) { 14898 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14899 installerPackageName, res); 14900 } else { 14901 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14902 args.user, installerPackageName, volumeUuid, res); 14903 } 14904 } 14905 synchronized (mPackages) { 14906 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14907 if (ps != null) { 14908 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14909 } 14910 14911 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14912 for (int i = 0; i < childCount; i++) { 14913 PackageParser.Package childPkg = pkg.childPackages.get(i); 14914 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14915 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14916 if (childPs != null) { 14917 childRes.newUsers = childPs.queryInstalledUsers( 14918 sUserManager.getUserIds(), true); 14919 } 14920 } 14921 } 14922 } 14923 14924 private void startIntentFilterVerifications(int userId, boolean replacing, 14925 PackageParser.Package pkg) { 14926 if (mIntentFilterVerifierComponent == null) { 14927 Slog.w(TAG, "No IntentFilter verification will not be done as " 14928 + "there is no IntentFilterVerifier available!"); 14929 return; 14930 } 14931 14932 final int verifierUid = getPackageUid( 14933 mIntentFilterVerifierComponent.getPackageName(), 14934 MATCH_DEBUG_TRIAGED_MISSING, 14935 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14936 14937 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14938 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14939 mHandler.sendMessage(msg); 14940 14941 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14942 for (int i = 0; i < childCount; i++) { 14943 PackageParser.Package childPkg = pkg.childPackages.get(i); 14944 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14945 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14946 mHandler.sendMessage(msg); 14947 } 14948 } 14949 14950 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14951 PackageParser.Package pkg) { 14952 int size = pkg.activities.size(); 14953 if (size == 0) { 14954 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14955 "No activity, so no need to verify any IntentFilter!"); 14956 return; 14957 } 14958 14959 final boolean hasDomainURLs = hasDomainURLs(pkg); 14960 if (!hasDomainURLs) { 14961 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14962 "No domain URLs, so no need to verify any IntentFilter!"); 14963 return; 14964 } 14965 14966 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14967 + " if any IntentFilter from the " + size 14968 + " Activities needs verification ..."); 14969 14970 int count = 0; 14971 final String packageName = pkg.packageName; 14972 14973 synchronized (mPackages) { 14974 // If this is a new install and we see that we've already run verification for this 14975 // package, we have nothing to do: it means the state was restored from backup. 14976 if (!replacing) { 14977 IntentFilterVerificationInfo ivi = 14978 mSettings.getIntentFilterVerificationLPr(packageName); 14979 if (ivi != null) { 14980 if (DEBUG_DOMAIN_VERIFICATION) { 14981 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14982 + ivi.getStatusString()); 14983 } 14984 return; 14985 } 14986 } 14987 14988 // If any filters need to be verified, then all need to be. 14989 boolean needToVerify = false; 14990 for (PackageParser.Activity a : pkg.activities) { 14991 for (ActivityIntentInfo filter : a.intents) { 14992 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14993 if (DEBUG_DOMAIN_VERIFICATION) { 14994 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14995 } 14996 needToVerify = true; 14997 break; 14998 } 14999 } 15000 } 15001 15002 if (needToVerify) { 15003 final int verificationId = mIntentFilterVerificationToken++; 15004 for (PackageParser.Activity a : pkg.activities) { 15005 for (ActivityIntentInfo filter : a.intents) { 15006 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15007 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15008 "Verification needed for IntentFilter:" + filter.toString()); 15009 mIntentFilterVerifier.addOneIntentFilterVerification( 15010 verifierUid, userId, verificationId, filter, packageName); 15011 count++; 15012 } 15013 } 15014 } 15015 } 15016 } 15017 15018 if (count > 0) { 15019 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15020 + " IntentFilter verification" + (count > 1 ? "s" : "") 15021 + " for userId:" + userId); 15022 mIntentFilterVerifier.startVerifications(userId); 15023 } else { 15024 if (DEBUG_DOMAIN_VERIFICATION) { 15025 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15026 } 15027 } 15028 } 15029 15030 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15031 final ComponentName cn = filter.activity.getComponentName(); 15032 final String packageName = cn.getPackageName(); 15033 15034 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15035 packageName); 15036 if (ivi == null) { 15037 return true; 15038 } 15039 int status = ivi.getStatus(); 15040 switch (status) { 15041 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15042 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15043 return true; 15044 15045 default: 15046 // Nothing to do 15047 return false; 15048 } 15049 } 15050 15051 private static boolean isMultiArch(ApplicationInfo info) { 15052 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15053 } 15054 15055 private static boolean isExternal(PackageParser.Package pkg) { 15056 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15057 } 15058 15059 private static boolean isExternal(PackageSetting ps) { 15060 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15061 } 15062 15063 private static boolean isEphemeral(PackageParser.Package pkg) { 15064 return pkg.applicationInfo.isEphemeralApp(); 15065 } 15066 15067 private static boolean isEphemeral(PackageSetting ps) { 15068 return ps.pkg != null && isEphemeral(ps.pkg); 15069 } 15070 15071 private static boolean isSystemApp(PackageParser.Package pkg) { 15072 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15073 } 15074 15075 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15076 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15077 } 15078 15079 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15080 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15081 } 15082 15083 private static boolean isSystemApp(PackageSetting ps) { 15084 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15085 } 15086 15087 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15088 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15089 } 15090 15091 private int packageFlagsToInstallFlags(PackageSetting ps) { 15092 int installFlags = 0; 15093 if (isEphemeral(ps)) { 15094 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15095 } 15096 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15097 // This existing package was an external ASEC install when we have 15098 // the external flag without a UUID 15099 installFlags |= PackageManager.INSTALL_EXTERNAL; 15100 } 15101 if (ps.isForwardLocked()) { 15102 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15103 } 15104 return installFlags; 15105 } 15106 15107 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15108 if (isExternal(pkg)) { 15109 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15110 return StorageManager.UUID_PRIMARY_PHYSICAL; 15111 } else { 15112 return pkg.volumeUuid; 15113 } 15114 } else { 15115 return StorageManager.UUID_PRIVATE_INTERNAL; 15116 } 15117 } 15118 15119 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15120 if (isExternal(pkg)) { 15121 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15122 return mSettings.getExternalVersion(); 15123 } else { 15124 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15125 } 15126 } else { 15127 return mSettings.getInternalVersion(); 15128 } 15129 } 15130 15131 private void deleteTempPackageFiles() { 15132 final FilenameFilter filter = new FilenameFilter() { 15133 public boolean accept(File dir, String name) { 15134 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15135 } 15136 }; 15137 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15138 file.delete(); 15139 } 15140 } 15141 15142 @Override 15143 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15144 int flags) { 15145 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15146 flags); 15147 } 15148 15149 @Override 15150 public void deletePackage(final String packageName, 15151 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15152 mContext.enforceCallingOrSelfPermission( 15153 android.Manifest.permission.DELETE_PACKAGES, null); 15154 Preconditions.checkNotNull(packageName); 15155 Preconditions.checkNotNull(observer); 15156 final int uid = Binder.getCallingUid(); 15157 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15158 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15159 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15160 mContext.enforceCallingOrSelfPermission( 15161 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15162 "deletePackage for user " + userId); 15163 } 15164 15165 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15166 try { 15167 observer.onPackageDeleted(packageName, 15168 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15169 } catch (RemoteException re) { 15170 } 15171 return; 15172 } 15173 15174 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15175 try { 15176 observer.onPackageDeleted(packageName, 15177 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15178 } catch (RemoteException re) { 15179 } 15180 return; 15181 } 15182 15183 if (DEBUG_REMOVE) { 15184 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15185 + " deleteAllUsers: " + deleteAllUsers ); 15186 } 15187 // Queue up an async operation since the package deletion may take a little while. 15188 mHandler.post(new Runnable() { 15189 public void run() { 15190 mHandler.removeCallbacks(this); 15191 int returnCode; 15192 if (!deleteAllUsers) { 15193 returnCode = deletePackageX(packageName, userId, deleteFlags); 15194 } else { 15195 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15196 // If nobody is blocking uninstall, proceed with delete for all users 15197 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15198 returnCode = deletePackageX(packageName, userId, deleteFlags); 15199 } else { 15200 // Otherwise uninstall individually for users with blockUninstalls=false 15201 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15202 for (int userId : users) { 15203 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15204 returnCode = deletePackageX(packageName, userId, userFlags); 15205 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15206 Slog.w(TAG, "Package delete failed for user " + userId 15207 + ", returnCode " + returnCode); 15208 } 15209 } 15210 } 15211 // The app has only been marked uninstalled for certain users. 15212 // We still need to report that delete was blocked 15213 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15214 } 15215 } 15216 try { 15217 observer.onPackageDeleted(packageName, returnCode, null); 15218 } catch (RemoteException e) { 15219 Log.i(TAG, "Observer no longer exists."); 15220 } //end catch 15221 } //end run 15222 }); 15223 } 15224 15225 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15226 int[] result = EMPTY_INT_ARRAY; 15227 for (int userId : userIds) { 15228 if (getBlockUninstallForUser(packageName, userId)) { 15229 result = ArrayUtils.appendInt(result, userId); 15230 } 15231 } 15232 return result; 15233 } 15234 15235 @Override 15236 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15237 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15238 } 15239 15240 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15241 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15242 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15243 try { 15244 if (dpm != null) { 15245 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15246 /* callingUserOnly =*/ false); 15247 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15248 : deviceOwnerComponentName.getPackageName(); 15249 // Does the package contains the device owner? 15250 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15251 // this check is probably not needed, since DO should be registered as a device 15252 // admin on some user too. (Original bug for this: b/17657954) 15253 if (packageName.equals(deviceOwnerPackageName)) { 15254 return true; 15255 } 15256 // Does it contain a device admin for any user? 15257 int[] users; 15258 if (userId == UserHandle.USER_ALL) { 15259 users = sUserManager.getUserIds(); 15260 } else { 15261 users = new int[]{userId}; 15262 } 15263 for (int i = 0; i < users.length; ++i) { 15264 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15265 return true; 15266 } 15267 } 15268 } 15269 } catch (RemoteException e) { 15270 } 15271 return false; 15272 } 15273 15274 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15275 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15276 } 15277 15278 /** 15279 * This method is an internal method that could be get invoked either 15280 * to delete an installed package or to clean up a failed installation. 15281 * After deleting an installed package, a broadcast is sent to notify any 15282 * listeners that the package has been removed. For cleaning up a failed 15283 * installation, the broadcast is not necessary since the package's 15284 * installation wouldn't have sent the initial broadcast either 15285 * The key steps in deleting a package are 15286 * deleting the package information in internal structures like mPackages, 15287 * deleting the packages base directories through installd 15288 * updating mSettings to reflect current status 15289 * persisting settings for later use 15290 * sending a broadcast if necessary 15291 */ 15292 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15293 final PackageRemovedInfo info = new PackageRemovedInfo(); 15294 final boolean res; 15295 15296 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15297 ? UserHandle.ALL : new UserHandle(userId); 15298 15299 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15300 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15301 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15302 } 15303 15304 PackageSetting uninstalledPs = null; 15305 15306 // for the uninstall-updates case and restricted profiles, remember the per- 15307 // user handle installed state 15308 int[] allUsers; 15309 synchronized (mPackages) { 15310 uninstalledPs = mSettings.mPackages.get(packageName); 15311 if (uninstalledPs == null) { 15312 Slog.w(TAG, "Not removing non-existent package " + packageName); 15313 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15314 } 15315 allUsers = sUserManager.getUserIds(); 15316 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15317 } 15318 15319 synchronized (mInstallLock) { 15320 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15321 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15322 "deletePackageX")) { 15323 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15324 deleteFlags | REMOVE_CHATTY, info, true, null); 15325 } 15326 synchronized (mPackages) { 15327 if (res) { 15328 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15329 } 15330 } 15331 } 15332 15333 if (res) { 15334 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15335 info.sendPackageRemovedBroadcasts(killApp); 15336 info.sendSystemPackageUpdatedBroadcasts(); 15337 info.sendSystemPackageAppearedBroadcasts(); 15338 } 15339 // Force a gc here. 15340 Runtime.getRuntime().gc(); 15341 // Delete the resources here after sending the broadcast to let 15342 // other processes clean up before deleting resources. 15343 if (info.args != null) { 15344 synchronized (mInstallLock) { 15345 info.args.doPostDeleteLI(true); 15346 } 15347 } 15348 15349 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15350 } 15351 15352 class PackageRemovedInfo { 15353 String removedPackage; 15354 int uid = -1; 15355 int removedAppId = -1; 15356 int[] origUsers; 15357 int[] removedUsers = null; 15358 boolean isRemovedPackageSystemUpdate = false; 15359 boolean isUpdate; 15360 boolean dataRemoved; 15361 boolean removedForAllUsers; 15362 // Clean up resources deleted packages. 15363 InstallArgs args = null; 15364 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15365 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15366 15367 void sendPackageRemovedBroadcasts(boolean killApp) { 15368 sendPackageRemovedBroadcastInternal(killApp); 15369 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15370 for (int i = 0; i < childCount; i++) { 15371 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15372 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15373 } 15374 } 15375 15376 void sendSystemPackageUpdatedBroadcasts() { 15377 if (isRemovedPackageSystemUpdate) { 15378 sendSystemPackageUpdatedBroadcastsInternal(); 15379 final int childCount = (removedChildPackages != null) 15380 ? removedChildPackages.size() : 0; 15381 for (int i = 0; i < childCount; i++) { 15382 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15383 if (childInfo.isRemovedPackageSystemUpdate) { 15384 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15385 } 15386 } 15387 } 15388 } 15389 15390 void sendSystemPackageAppearedBroadcasts() { 15391 final int packageCount = (appearedChildPackages != null) 15392 ? appearedChildPackages.size() : 0; 15393 for (int i = 0; i < packageCount; i++) { 15394 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15395 for (int userId : installedInfo.newUsers) { 15396 sendPackageAddedForUser(installedInfo.name, true, 15397 UserHandle.getAppId(installedInfo.uid), userId); 15398 } 15399 } 15400 } 15401 15402 private void sendSystemPackageUpdatedBroadcastsInternal() { 15403 Bundle extras = new Bundle(2); 15404 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15405 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15406 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15407 extras, 0, null, null, null); 15408 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15409 extras, 0, null, null, null); 15410 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15411 null, 0, removedPackage, null, null); 15412 } 15413 15414 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15415 Bundle extras = new Bundle(2); 15416 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15417 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15418 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15419 if (isUpdate || isRemovedPackageSystemUpdate) { 15420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15421 } 15422 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15423 if (removedPackage != null) { 15424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15425 extras, 0, null, null, removedUsers); 15426 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15427 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15428 removedPackage, extras, 0, null, null, removedUsers); 15429 } 15430 } 15431 if (removedAppId >= 0) { 15432 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15433 removedUsers); 15434 } 15435 } 15436 } 15437 15438 /* 15439 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15440 * flag is not set, the data directory is removed as well. 15441 * make sure this flag is set for partially installed apps. If not its meaningless to 15442 * delete a partially installed application. 15443 */ 15444 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15445 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15446 String packageName = ps.name; 15447 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15448 // Retrieve object to delete permissions for shared user later on 15449 final PackageParser.Package deletedPkg; 15450 final PackageSetting deletedPs; 15451 // reader 15452 synchronized (mPackages) { 15453 deletedPkg = mPackages.get(packageName); 15454 deletedPs = mSettings.mPackages.get(packageName); 15455 if (outInfo != null) { 15456 outInfo.removedPackage = packageName; 15457 outInfo.removedUsers = deletedPs != null 15458 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15459 : null; 15460 } 15461 } 15462 15463 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15464 15465 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15466 final PackageParser.Package resolvedPkg; 15467 if (deletedPkg != null) { 15468 resolvedPkg = deletedPkg; 15469 } else { 15470 // We don't have a parsed package when it lives on an ejected 15471 // adopted storage device, so fake something together 15472 resolvedPkg = new PackageParser.Package(ps.name); 15473 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15474 } 15475 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15476 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15477 destroyAppProfilesLIF(resolvedPkg); 15478 if (outInfo != null) { 15479 outInfo.dataRemoved = true; 15480 } 15481 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15482 } 15483 15484 // writer 15485 synchronized (mPackages) { 15486 if (deletedPs != null) { 15487 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15488 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15489 clearDefaultBrowserIfNeeded(packageName); 15490 if (outInfo != null) { 15491 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15492 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15493 } 15494 updatePermissionsLPw(deletedPs.name, null, 0); 15495 if (deletedPs.sharedUser != null) { 15496 // Remove permissions associated with package. Since runtime 15497 // permissions are per user we have to kill the removed package 15498 // or packages running under the shared user of the removed 15499 // package if revoking the permissions requested only by the removed 15500 // package is successful and this causes a change in gids. 15501 for (int userId : UserManagerService.getInstance().getUserIds()) { 15502 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15503 userId); 15504 if (userIdToKill == UserHandle.USER_ALL 15505 || userIdToKill >= UserHandle.USER_SYSTEM) { 15506 // If gids changed for this user, kill all affected packages. 15507 mHandler.post(new Runnable() { 15508 @Override 15509 public void run() { 15510 // This has to happen with no lock held. 15511 killApplication(deletedPs.name, deletedPs.appId, 15512 KILL_APP_REASON_GIDS_CHANGED); 15513 } 15514 }); 15515 break; 15516 } 15517 } 15518 } 15519 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15520 } 15521 // make sure to preserve per-user disabled state if this removal was just 15522 // a downgrade of a system app to the factory package 15523 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15524 if (DEBUG_REMOVE) { 15525 Slog.d(TAG, "Propagating install state across downgrade"); 15526 } 15527 for (int userId : allUserHandles) { 15528 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15529 if (DEBUG_REMOVE) { 15530 Slog.d(TAG, " user " + userId + " => " + installed); 15531 } 15532 ps.setInstalled(installed, userId); 15533 } 15534 } 15535 } 15536 // can downgrade to reader 15537 if (writeSettings) { 15538 // Save settings now 15539 mSettings.writeLPr(); 15540 } 15541 } 15542 if (outInfo != null) { 15543 // A user ID was deleted here. Go through all users and remove it 15544 // from KeyStore. 15545 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15546 } 15547 } 15548 15549 static boolean locationIsPrivileged(File path) { 15550 try { 15551 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15552 .getCanonicalPath(); 15553 return path.getCanonicalPath().startsWith(privilegedAppDir); 15554 } catch (IOException e) { 15555 Slog.e(TAG, "Unable to access code path " + path); 15556 } 15557 return false; 15558 } 15559 15560 /* 15561 * Tries to delete system package. 15562 */ 15563 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15564 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15565 boolean writeSettings) { 15566 if (deletedPs.parentPackageName != null) { 15567 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15568 return false; 15569 } 15570 15571 final boolean applyUserRestrictions 15572 = (allUserHandles != null) && (outInfo.origUsers != null); 15573 final PackageSetting disabledPs; 15574 // Confirm if the system package has been updated 15575 // An updated system app can be deleted. This will also have to restore 15576 // the system pkg from system partition 15577 // reader 15578 synchronized (mPackages) { 15579 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15580 } 15581 15582 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15583 + " disabledPs=" + disabledPs); 15584 15585 if (disabledPs == null) { 15586 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15587 return false; 15588 } else if (DEBUG_REMOVE) { 15589 Slog.d(TAG, "Deleting system pkg from data partition"); 15590 } 15591 15592 if (DEBUG_REMOVE) { 15593 if (applyUserRestrictions) { 15594 Slog.d(TAG, "Remembering install states:"); 15595 for (int userId : allUserHandles) { 15596 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15597 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15598 } 15599 } 15600 } 15601 15602 // Delete the updated package 15603 outInfo.isRemovedPackageSystemUpdate = true; 15604 if (outInfo.removedChildPackages != null) { 15605 final int childCount = (deletedPs.childPackageNames != null) 15606 ? deletedPs.childPackageNames.size() : 0; 15607 for (int i = 0; i < childCount; i++) { 15608 String childPackageName = deletedPs.childPackageNames.get(i); 15609 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15610 .contains(childPackageName)) { 15611 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15612 childPackageName); 15613 if (childInfo != null) { 15614 childInfo.isRemovedPackageSystemUpdate = true; 15615 } 15616 } 15617 } 15618 } 15619 15620 if (disabledPs.versionCode < deletedPs.versionCode) { 15621 // Delete data for downgrades 15622 flags &= ~PackageManager.DELETE_KEEP_DATA; 15623 } else { 15624 // Preserve data by setting flag 15625 flags |= PackageManager.DELETE_KEEP_DATA; 15626 } 15627 15628 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15629 outInfo, writeSettings, disabledPs.pkg); 15630 if (!ret) { 15631 return false; 15632 } 15633 15634 // writer 15635 synchronized (mPackages) { 15636 // Reinstate the old system package 15637 enableSystemPackageLPw(disabledPs.pkg); 15638 // Remove any native libraries from the upgraded package. 15639 removeNativeBinariesLI(deletedPs); 15640 } 15641 15642 // Install the system package 15643 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15644 int parseFlags = mDefParseFlags 15645 | PackageParser.PARSE_MUST_BE_APK 15646 | PackageParser.PARSE_IS_SYSTEM 15647 | PackageParser.PARSE_IS_SYSTEM_DIR; 15648 if (locationIsPrivileged(disabledPs.codePath)) { 15649 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15650 } 15651 15652 final PackageParser.Package newPkg; 15653 try { 15654 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15655 } catch (PackageManagerException e) { 15656 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15657 + e.getMessage()); 15658 return false; 15659 } 15660 15661 prepareAppDataAfterInstallLIF(newPkg); 15662 15663 // writer 15664 synchronized (mPackages) { 15665 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15666 15667 // Propagate the permissions state as we do not want to drop on the floor 15668 // runtime permissions. The update permissions method below will take 15669 // care of removing obsolete permissions and grant install permissions. 15670 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15671 updatePermissionsLPw(newPkg.packageName, newPkg, 15672 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15673 15674 if (applyUserRestrictions) { 15675 if (DEBUG_REMOVE) { 15676 Slog.d(TAG, "Propagating install state across reinstall"); 15677 } 15678 for (int userId : allUserHandles) { 15679 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15680 if (DEBUG_REMOVE) { 15681 Slog.d(TAG, " user " + userId + " => " + installed); 15682 } 15683 ps.setInstalled(installed, userId); 15684 15685 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15686 } 15687 // Regardless of writeSettings we need to ensure that this restriction 15688 // state propagation is persisted 15689 mSettings.writeAllUsersPackageRestrictionsLPr(); 15690 } 15691 // can downgrade to reader here 15692 if (writeSettings) { 15693 mSettings.writeLPr(); 15694 } 15695 } 15696 return true; 15697 } 15698 15699 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15700 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15701 PackageRemovedInfo outInfo, boolean writeSettings, 15702 PackageParser.Package replacingPackage) { 15703 synchronized (mPackages) { 15704 if (outInfo != null) { 15705 outInfo.uid = ps.appId; 15706 } 15707 15708 if (outInfo != null && outInfo.removedChildPackages != null) { 15709 final int childCount = (ps.childPackageNames != null) 15710 ? ps.childPackageNames.size() : 0; 15711 for (int i = 0; i < childCount; i++) { 15712 String childPackageName = ps.childPackageNames.get(i); 15713 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15714 if (childPs == null) { 15715 return false; 15716 } 15717 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15718 childPackageName); 15719 if (childInfo != null) { 15720 childInfo.uid = childPs.appId; 15721 } 15722 } 15723 } 15724 } 15725 15726 // Delete package data from internal structures and also remove data if flag is set 15727 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15728 15729 // Delete the child packages data 15730 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15731 for (int i = 0; i < childCount; i++) { 15732 PackageSetting childPs; 15733 synchronized (mPackages) { 15734 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15735 } 15736 if (childPs != null) { 15737 PackageRemovedInfo childOutInfo = (outInfo != null 15738 && outInfo.removedChildPackages != null) 15739 ? outInfo.removedChildPackages.get(childPs.name) : null; 15740 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15741 && (replacingPackage != null 15742 && !replacingPackage.hasChildPackage(childPs.name)) 15743 ? flags & ~DELETE_KEEP_DATA : flags; 15744 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15745 deleteFlags, writeSettings); 15746 } 15747 } 15748 15749 // Delete application code and resources only for parent packages 15750 if (ps.parentPackageName == null) { 15751 if (deleteCodeAndResources && (outInfo != null)) { 15752 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15753 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15754 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15755 } 15756 } 15757 15758 return true; 15759 } 15760 15761 @Override 15762 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15763 int userId) { 15764 mContext.enforceCallingOrSelfPermission( 15765 android.Manifest.permission.DELETE_PACKAGES, null); 15766 synchronized (mPackages) { 15767 PackageSetting ps = mSettings.mPackages.get(packageName); 15768 if (ps == null) { 15769 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15770 return false; 15771 } 15772 if (!ps.getInstalled(userId)) { 15773 // Can't block uninstall for an app that is not installed or enabled. 15774 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15775 return false; 15776 } 15777 ps.setBlockUninstall(blockUninstall, userId); 15778 mSettings.writePackageRestrictionsLPr(userId); 15779 } 15780 return true; 15781 } 15782 15783 @Override 15784 public boolean getBlockUninstallForUser(String packageName, int userId) { 15785 synchronized (mPackages) { 15786 PackageSetting ps = mSettings.mPackages.get(packageName); 15787 if (ps == null) { 15788 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15789 return false; 15790 } 15791 return ps.getBlockUninstall(userId); 15792 } 15793 } 15794 15795 @Override 15796 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15797 int callingUid = Binder.getCallingUid(); 15798 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15799 throw new SecurityException( 15800 "setRequiredForSystemUser can only be run by the system or root"); 15801 } 15802 synchronized (mPackages) { 15803 PackageSetting ps = mSettings.mPackages.get(packageName); 15804 if (ps == null) { 15805 Log.w(TAG, "Package doesn't exist: " + packageName); 15806 return false; 15807 } 15808 if (systemUserApp) { 15809 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15810 } else { 15811 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15812 } 15813 mSettings.writeLPr(); 15814 } 15815 return true; 15816 } 15817 15818 /* 15819 * This method handles package deletion in general 15820 */ 15821 private boolean deletePackageLIF(String packageName, UserHandle user, 15822 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15823 PackageRemovedInfo outInfo, boolean writeSettings, 15824 PackageParser.Package replacingPackage) { 15825 if (packageName == null) { 15826 Slog.w(TAG, "Attempt to delete null packageName."); 15827 return false; 15828 } 15829 15830 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15831 15832 PackageSetting ps; 15833 15834 synchronized (mPackages) { 15835 ps = mSettings.mPackages.get(packageName); 15836 if (ps == null) { 15837 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15838 return false; 15839 } 15840 15841 if (ps.parentPackageName != null && (!isSystemApp(ps) 15842 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15843 if (DEBUG_REMOVE) { 15844 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15845 + ((user == null) ? UserHandle.USER_ALL : user)); 15846 } 15847 final int removedUserId = (user != null) ? user.getIdentifier() 15848 : UserHandle.USER_ALL; 15849 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15850 return false; 15851 } 15852 markPackageUninstalledForUserLPw(ps, user); 15853 scheduleWritePackageRestrictionsLocked(user); 15854 return true; 15855 } 15856 } 15857 15858 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15859 && user.getIdentifier() != UserHandle.USER_ALL)) { 15860 // The caller is asking that the package only be deleted for a single 15861 // user. To do this, we just mark its uninstalled state and delete 15862 // its data. If this is a system app, we only allow this to happen if 15863 // they have set the special DELETE_SYSTEM_APP which requests different 15864 // semantics than normal for uninstalling system apps. 15865 markPackageUninstalledForUserLPw(ps, user); 15866 15867 if (!isSystemApp(ps)) { 15868 // Do not uninstall the APK if an app should be cached 15869 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15870 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15871 // Other user still have this package installed, so all 15872 // we need to do is clear this user's data and save that 15873 // it is uninstalled. 15874 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15875 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15876 return false; 15877 } 15878 scheduleWritePackageRestrictionsLocked(user); 15879 return true; 15880 } else { 15881 // We need to set it back to 'installed' so the uninstall 15882 // broadcasts will be sent correctly. 15883 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15884 ps.setInstalled(true, user.getIdentifier()); 15885 } 15886 } else { 15887 // This is a system app, so we assume that the 15888 // other users still have this package installed, so all 15889 // we need to do is clear this user's data and save that 15890 // it is uninstalled. 15891 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15892 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15893 return false; 15894 } 15895 scheduleWritePackageRestrictionsLocked(user); 15896 return true; 15897 } 15898 } 15899 15900 // If we are deleting a composite package for all users, keep track 15901 // of result for each child. 15902 if (ps.childPackageNames != null && outInfo != null) { 15903 synchronized (mPackages) { 15904 final int childCount = ps.childPackageNames.size(); 15905 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15906 for (int i = 0; i < childCount; i++) { 15907 String childPackageName = ps.childPackageNames.get(i); 15908 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15909 childInfo.removedPackage = childPackageName; 15910 outInfo.removedChildPackages.put(childPackageName, childInfo); 15911 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15912 if (childPs != null) { 15913 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15914 } 15915 } 15916 } 15917 } 15918 15919 boolean ret = false; 15920 if (isSystemApp(ps)) { 15921 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15922 // When an updated system application is deleted we delete the existing resources 15923 // as well and fall back to existing code in system partition 15924 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15925 } else { 15926 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15927 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15928 outInfo, writeSettings, replacingPackage); 15929 } 15930 15931 // Take a note whether we deleted the package for all users 15932 if (outInfo != null) { 15933 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15934 if (outInfo.removedChildPackages != null) { 15935 synchronized (mPackages) { 15936 final int childCount = outInfo.removedChildPackages.size(); 15937 for (int i = 0; i < childCount; i++) { 15938 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15939 if (childInfo != null) { 15940 childInfo.removedForAllUsers = mPackages.get( 15941 childInfo.removedPackage) == null; 15942 } 15943 } 15944 } 15945 } 15946 // If we uninstalled an update to a system app there may be some 15947 // child packages that appeared as they are declared in the system 15948 // app but were not declared in the update. 15949 if (isSystemApp(ps)) { 15950 synchronized (mPackages) { 15951 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15952 final int childCount = (updatedPs.childPackageNames != null) 15953 ? updatedPs.childPackageNames.size() : 0; 15954 for (int i = 0; i < childCount; i++) { 15955 String childPackageName = updatedPs.childPackageNames.get(i); 15956 if (outInfo.removedChildPackages == null 15957 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15958 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15959 if (childPs == null) { 15960 continue; 15961 } 15962 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15963 installRes.name = childPackageName; 15964 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15965 installRes.pkg = mPackages.get(childPackageName); 15966 installRes.uid = childPs.pkg.applicationInfo.uid; 15967 if (outInfo.appearedChildPackages == null) { 15968 outInfo.appearedChildPackages = new ArrayMap<>(); 15969 } 15970 outInfo.appearedChildPackages.put(childPackageName, installRes); 15971 } 15972 } 15973 } 15974 } 15975 } 15976 15977 return ret; 15978 } 15979 15980 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15981 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15982 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15983 for (int nextUserId : userIds) { 15984 if (DEBUG_REMOVE) { 15985 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15986 } 15987 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15988 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15989 false /*hidden*/, false /*suspended*/, null, null, null, 15990 false /*blockUninstall*/, 15991 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15992 } 15993 } 15994 15995 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15996 PackageRemovedInfo outInfo) { 15997 final PackageParser.Package pkg; 15998 synchronized (mPackages) { 15999 pkg = mPackages.get(ps.name); 16000 } 16001 16002 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16003 : new int[] {userId}; 16004 for (int nextUserId : userIds) { 16005 if (DEBUG_REMOVE) { 16006 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16007 + nextUserId); 16008 } 16009 16010 destroyAppDataLIF(pkg, userId, 16011 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16012 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16013 schedulePackageCleaning(ps.name, nextUserId, false); 16014 synchronized (mPackages) { 16015 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16016 scheduleWritePackageRestrictionsLocked(nextUserId); 16017 } 16018 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16019 } 16020 } 16021 16022 if (outInfo != null) { 16023 outInfo.removedPackage = ps.name; 16024 outInfo.removedAppId = ps.appId; 16025 outInfo.removedUsers = userIds; 16026 } 16027 16028 return true; 16029 } 16030 16031 private final class ClearStorageConnection implements ServiceConnection { 16032 IMediaContainerService mContainerService; 16033 16034 @Override 16035 public void onServiceConnected(ComponentName name, IBinder service) { 16036 synchronized (this) { 16037 mContainerService = IMediaContainerService.Stub.asInterface(service); 16038 notifyAll(); 16039 } 16040 } 16041 16042 @Override 16043 public void onServiceDisconnected(ComponentName name) { 16044 } 16045 } 16046 16047 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16048 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16049 16050 final boolean mounted; 16051 if (Environment.isExternalStorageEmulated()) { 16052 mounted = true; 16053 } else { 16054 final String status = Environment.getExternalStorageState(); 16055 16056 mounted = status.equals(Environment.MEDIA_MOUNTED) 16057 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16058 } 16059 16060 if (!mounted) { 16061 return; 16062 } 16063 16064 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16065 int[] users; 16066 if (userId == UserHandle.USER_ALL) { 16067 users = sUserManager.getUserIds(); 16068 } else { 16069 users = new int[] { userId }; 16070 } 16071 final ClearStorageConnection conn = new ClearStorageConnection(); 16072 if (mContext.bindServiceAsUser( 16073 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16074 try { 16075 for (int curUser : users) { 16076 long timeout = SystemClock.uptimeMillis() + 5000; 16077 synchronized (conn) { 16078 long now = SystemClock.uptimeMillis(); 16079 while (conn.mContainerService == null && now < timeout) { 16080 try { 16081 conn.wait(timeout - now); 16082 } catch (InterruptedException e) { 16083 } 16084 } 16085 } 16086 if (conn.mContainerService == null) { 16087 return; 16088 } 16089 16090 final UserEnvironment userEnv = new UserEnvironment(curUser); 16091 clearDirectory(conn.mContainerService, 16092 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16093 if (allData) { 16094 clearDirectory(conn.mContainerService, 16095 userEnv.buildExternalStorageAppDataDirs(packageName)); 16096 clearDirectory(conn.mContainerService, 16097 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16098 } 16099 } 16100 } finally { 16101 mContext.unbindService(conn); 16102 } 16103 } 16104 } 16105 16106 @Override 16107 public void clearApplicationProfileData(String packageName) { 16108 enforceSystemOrRoot("Only the system can clear all profile data"); 16109 16110 final PackageParser.Package pkg; 16111 synchronized (mPackages) { 16112 pkg = mPackages.get(packageName); 16113 } 16114 16115 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16116 synchronized (mInstallLock) { 16117 clearAppProfilesLIF(pkg); 16118 } 16119 } 16120 } 16121 16122 @Override 16123 public void clearApplicationUserData(final String packageName, 16124 final IPackageDataObserver observer, final int userId) { 16125 mContext.enforceCallingOrSelfPermission( 16126 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16127 16128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16129 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16130 16131 final DevicePolicyManagerInternal dpmi = LocalServices 16132 .getService(DevicePolicyManagerInternal.class); 16133 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16134 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16135 } 16136 // Queue up an async operation since the package deletion may take a little while. 16137 mHandler.post(new Runnable() { 16138 public void run() { 16139 mHandler.removeCallbacks(this); 16140 final boolean succeeded; 16141 try (PackageFreezer freezer = freezePackage(packageName, 16142 "clearApplicationUserData")) { 16143 synchronized (mInstallLock) { 16144 succeeded = clearApplicationUserDataLIF(packageName, userId); 16145 } 16146 clearExternalStorageDataSync(packageName, userId, true); 16147 } 16148 if (succeeded) { 16149 // invoke DeviceStorageMonitor's update method to clear any notifications 16150 DeviceStorageMonitorInternal dsm = LocalServices 16151 .getService(DeviceStorageMonitorInternal.class); 16152 if (dsm != null) { 16153 dsm.checkMemory(); 16154 } 16155 } 16156 if(observer != null) { 16157 try { 16158 observer.onRemoveCompleted(packageName, succeeded); 16159 } catch (RemoteException e) { 16160 Log.i(TAG, "Observer no longer exists."); 16161 } 16162 } //end if observer 16163 } //end run 16164 }); 16165 } 16166 16167 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16168 if (packageName == null) { 16169 Slog.w(TAG, "Attempt to delete null packageName."); 16170 return false; 16171 } 16172 16173 // Try finding details about the requested package 16174 PackageParser.Package pkg; 16175 synchronized (mPackages) { 16176 pkg = mPackages.get(packageName); 16177 if (pkg == null) { 16178 final PackageSetting ps = mSettings.mPackages.get(packageName); 16179 if (ps != null) { 16180 pkg = ps.pkg; 16181 } 16182 } 16183 16184 if (pkg == null) { 16185 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16186 return false; 16187 } 16188 16189 PackageSetting ps = (PackageSetting) pkg.mExtras; 16190 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16191 } 16192 16193 clearAppDataLIF(pkg, userId, 16194 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16195 16196 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16197 removeKeystoreDataIfNeeded(userId, appId); 16198 16199 final UserManager um = mContext.getSystemService(UserManager.class); 16200 final int flags; 16201 if (um.isUserUnlockingOrUnlocked(userId)) { 16202 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16203 } else if (um.isUserRunning(userId)) { 16204 flags = StorageManager.FLAG_STORAGE_DE; 16205 } else { 16206 flags = 0; 16207 } 16208 prepareAppDataContentsLIF(pkg, userId, flags); 16209 16210 return true; 16211 } 16212 16213 /** 16214 * Reverts user permission state changes (permissions and flags) in 16215 * all packages for a given user. 16216 * 16217 * @param userId The device user for which to do a reset. 16218 */ 16219 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16220 final int packageCount = mPackages.size(); 16221 for (int i = 0; i < packageCount; i++) { 16222 PackageParser.Package pkg = mPackages.valueAt(i); 16223 PackageSetting ps = (PackageSetting) pkg.mExtras; 16224 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16225 } 16226 } 16227 16228 private void resetNetworkPolicies(int userId) { 16229 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16230 } 16231 16232 /** 16233 * Reverts user permission state changes (permissions and flags). 16234 * 16235 * @param ps The package for which to reset. 16236 * @param userId The device user for which to do a reset. 16237 */ 16238 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16239 final PackageSetting ps, final int userId) { 16240 if (ps.pkg == null) { 16241 return; 16242 } 16243 16244 // These are flags that can change base on user actions. 16245 final int userSettableMask = FLAG_PERMISSION_USER_SET 16246 | FLAG_PERMISSION_USER_FIXED 16247 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16248 | FLAG_PERMISSION_REVIEW_REQUIRED; 16249 16250 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16251 | FLAG_PERMISSION_POLICY_FIXED; 16252 16253 boolean writeInstallPermissions = false; 16254 boolean writeRuntimePermissions = false; 16255 16256 final int permissionCount = ps.pkg.requestedPermissions.size(); 16257 for (int i = 0; i < permissionCount; i++) { 16258 String permission = ps.pkg.requestedPermissions.get(i); 16259 16260 BasePermission bp = mSettings.mPermissions.get(permission); 16261 if (bp == null) { 16262 continue; 16263 } 16264 16265 // If shared user we just reset the state to which only this app contributed. 16266 if (ps.sharedUser != null) { 16267 boolean used = false; 16268 final int packageCount = ps.sharedUser.packages.size(); 16269 for (int j = 0; j < packageCount; j++) { 16270 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16271 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16272 && pkg.pkg.requestedPermissions.contains(permission)) { 16273 used = true; 16274 break; 16275 } 16276 } 16277 if (used) { 16278 continue; 16279 } 16280 } 16281 16282 PermissionsState permissionsState = ps.getPermissionsState(); 16283 16284 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16285 16286 // Always clear the user settable flags. 16287 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16288 bp.name) != null; 16289 // If permission review is enabled and this is a legacy app, mark the 16290 // permission as requiring a review as this is the initial state. 16291 int flags = 0; 16292 if (Build.PERMISSIONS_REVIEW_REQUIRED 16293 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16294 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16295 } 16296 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16297 if (hasInstallState) { 16298 writeInstallPermissions = true; 16299 } else { 16300 writeRuntimePermissions = true; 16301 } 16302 } 16303 16304 // Below is only runtime permission handling. 16305 if (!bp.isRuntime()) { 16306 continue; 16307 } 16308 16309 // Never clobber system or policy. 16310 if ((oldFlags & policyOrSystemFlags) != 0) { 16311 continue; 16312 } 16313 16314 // If this permission was granted by default, make sure it is. 16315 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16316 if (permissionsState.grantRuntimePermission(bp, userId) 16317 != PERMISSION_OPERATION_FAILURE) { 16318 writeRuntimePermissions = true; 16319 } 16320 // If permission review is enabled the permissions for a legacy apps 16321 // are represented as constantly granted runtime ones, so don't revoke. 16322 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16323 // Otherwise, reset the permission. 16324 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16325 switch (revokeResult) { 16326 case PERMISSION_OPERATION_SUCCESS: 16327 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16328 writeRuntimePermissions = true; 16329 final int appId = ps.appId; 16330 mHandler.post(new Runnable() { 16331 @Override 16332 public void run() { 16333 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16334 } 16335 }); 16336 } break; 16337 } 16338 } 16339 } 16340 16341 // Synchronously write as we are taking permissions away. 16342 if (writeRuntimePermissions) { 16343 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16344 } 16345 16346 // Synchronously write as we are taking permissions away. 16347 if (writeInstallPermissions) { 16348 mSettings.writeLPr(); 16349 } 16350 } 16351 16352 /** 16353 * Remove entries from the keystore daemon. Will only remove it if the 16354 * {@code appId} is valid. 16355 */ 16356 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16357 if (appId < 0) { 16358 return; 16359 } 16360 16361 final KeyStore keyStore = KeyStore.getInstance(); 16362 if (keyStore != null) { 16363 if (userId == UserHandle.USER_ALL) { 16364 for (final int individual : sUserManager.getUserIds()) { 16365 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16366 } 16367 } else { 16368 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16369 } 16370 } else { 16371 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16372 } 16373 } 16374 16375 @Override 16376 public void deleteApplicationCacheFiles(final String packageName, 16377 final IPackageDataObserver observer) { 16378 final int userId = UserHandle.getCallingUserId(); 16379 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16380 } 16381 16382 @Override 16383 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16384 final IPackageDataObserver observer) { 16385 mContext.enforceCallingOrSelfPermission( 16386 android.Manifest.permission.DELETE_CACHE_FILES, null); 16387 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16388 /* requireFullPermission= */ true, /* checkShell= */ false, 16389 "delete application cache files"); 16390 16391 final PackageParser.Package pkg; 16392 synchronized (mPackages) { 16393 pkg = mPackages.get(packageName); 16394 } 16395 16396 // Queue up an async operation since the package deletion may take a little while. 16397 mHandler.post(new Runnable() { 16398 public void run() { 16399 synchronized (mInstallLock) { 16400 final int flags = StorageManager.FLAG_STORAGE_DE 16401 | StorageManager.FLAG_STORAGE_CE; 16402 // We're only clearing cache files, so we don't care if the 16403 // app is unfrozen and still able to run 16404 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16405 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16406 } 16407 clearExternalStorageDataSync(packageName, userId, false); 16408 if (observer != null) { 16409 try { 16410 observer.onRemoveCompleted(packageName, true); 16411 } catch (RemoteException e) { 16412 Log.i(TAG, "Observer no longer exists."); 16413 } 16414 } 16415 } 16416 }); 16417 } 16418 16419 @Override 16420 public void getPackageSizeInfo(final String packageName, int userHandle, 16421 final IPackageStatsObserver observer) { 16422 mContext.enforceCallingOrSelfPermission( 16423 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16424 if (packageName == null) { 16425 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16426 } 16427 16428 PackageStats stats = new PackageStats(packageName, userHandle); 16429 16430 /* 16431 * Queue up an async operation since the package measurement may take a 16432 * little while. 16433 */ 16434 Message msg = mHandler.obtainMessage(INIT_COPY); 16435 msg.obj = new MeasureParams(stats, observer); 16436 mHandler.sendMessage(msg); 16437 } 16438 16439 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16440 final PackageSetting ps; 16441 synchronized (mPackages) { 16442 ps = mSettings.mPackages.get(packageName); 16443 if (ps == null) { 16444 Slog.w(TAG, "Failed to find settings for " + packageName); 16445 return false; 16446 } 16447 } 16448 try { 16449 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16450 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16451 ps.getCeDataInode(userId), ps.codePathString, stats); 16452 } catch (InstallerException e) { 16453 Slog.w(TAG, String.valueOf(e)); 16454 return false; 16455 } 16456 16457 // For now, ignore code size of packages on system partition 16458 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16459 stats.codeSize = 0; 16460 } 16461 16462 return true; 16463 } 16464 16465 private int getUidTargetSdkVersionLockedLPr(int uid) { 16466 Object obj = mSettings.getUserIdLPr(uid); 16467 if (obj instanceof SharedUserSetting) { 16468 final SharedUserSetting sus = (SharedUserSetting) obj; 16469 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16470 final Iterator<PackageSetting> it = sus.packages.iterator(); 16471 while (it.hasNext()) { 16472 final PackageSetting ps = it.next(); 16473 if (ps.pkg != null) { 16474 int v = ps.pkg.applicationInfo.targetSdkVersion; 16475 if (v < vers) vers = v; 16476 } 16477 } 16478 return vers; 16479 } else if (obj instanceof PackageSetting) { 16480 final PackageSetting ps = (PackageSetting) obj; 16481 if (ps.pkg != null) { 16482 return ps.pkg.applicationInfo.targetSdkVersion; 16483 } 16484 } 16485 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16486 } 16487 16488 @Override 16489 public void addPreferredActivity(IntentFilter filter, int match, 16490 ComponentName[] set, ComponentName activity, int userId) { 16491 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16492 "Adding preferred"); 16493 } 16494 16495 private void addPreferredActivityInternal(IntentFilter filter, int match, 16496 ComponentName[] set, ComponentName activity, boolean always, int userId, 16497 String opname) { 16498 // writer 16499 int callingUid = Binder.getCallingUid(); 16500 enforceCrossUserPermission(callingUid, userId, 16501 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16502 if (filter.countActions() == 0) { 16503 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16504 return; 16505 } 16506 synchronized (mPackages) { 16507 if (mContext.checkCallingOrSelfPermission( 16508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16509 != PackageManager.PERMISSION_GRANTED) { 16510 if (getUidTargetSdkVersionLockedLPr(callingUid) 16511 < Build.VERSION_CODES.FROYO) { 16512 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16513 + callingUid); 16514 return; 16515 } 16516 mContext.enforceCallingOrSelfPermission( 16517 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16518 } 16519 16520 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16521 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16522 + userId + ":"); 16523 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16524 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16525 scheduleWritePackageRestrictionsLocked(userId); 16526 } 16527 } 16528 16529 @Override 16530 public void replacePreferredActivity(IntentFilter filter, int match, 16531 ComponentName[] set, ComponentName activity, int userId) { 16532 if (filter.countActions() != 1) { 16533 throw new IllegalArgumentException( 16534 "replacePreferredActivity expects filter to have only 1 action."); 16535 } 16536 if (filter.countDataAuthorities() != 0 16537 || filter.countDataPaths() != 0 16538 || filter.countDataSchemes() > 1 16539 || filter.countDataTypes() != 0) { 16540 throw new IllegalArgumentException( 16541 "replacePreferredActivity expects filter to have no data authorities, " + 16542 "paths, or types; and at most one scheme."); 16543 } 16544 16545 final int callingUid = Binder.getCallingUid(); 16546 enforceCrossUserPermission(callingUid, userId, 16547 true /* requireFullPermission */, false /* checkShell */, 16548 "replace preferred activity"); 16549 synchronized (mPackages) { 16550 if (mContext.checkCallingOrSelfPermission( 16551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16552 != PackageManager.PERMISSION_GRANTED) { 16553 if (getUidTargetSdkVersionLockedLPr(callingUid) 16554 < Build.VERSION_CODES.FROYO) { 16555 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16556 + Binder.getCallingUid()); 16557 return; 16558 } 16559 mContext.enforceCallingOrSelfPermission( 16560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16561 } 16562 16563 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16564 if (pir != null) { 16565 // Get all of the existing entries that exactly match this filter. 16566 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16567 if (existing != null && existing.size() == 1) { 16568 PreferredActivity cur = existing.get(0); 16569 if (DEBUG_PREFERRED) { 16570 Slog.i(TAG, "Checking replace of preferred:"); 16571 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16572 if (!cur.mPref.mAlways) { 16573 Slog.i(TAG, " -- CUR; not mAlways!"); 16574 } else { 16575 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16576 Slog.i(TAG, " -- CUR: mSet=" 16577 + Arrays.toString(cur.mPref.mSetComponents)); 16578 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16579 Slog.i(TAG, " -- NEW: mMatch=" 16580 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16581 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16582 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16583 } 16584 } 16585 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16586 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16587 && cur.mPref.sameSet(set)) { 16588 // Setting the preferred activity to what it happens to be already 16589 if (DEBUG_PREFERRED) { 16590 Slog.i(TAG, "Replacing with same preferred activity " 16591 + cur.mPref.mShortComponent + " for user " 16592 + userId + ":"); 16593 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16594 } 16595 return; 16596 } 16597 } 16598 16599 if (existing != null) { 16600 if (DEBUG_PREFERRED) { 16601 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16602 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16603 } 16604 for (int i = 0; i < existing.size(); i++) { 16605 PreferredActivity pa = existing.get(i); 16606 if (DEBUG_PREFERRED) { 16607 Slog.i(TAG, "Removing existing preferred activity " 16608 + pa.mPref.mComponent + ":"); 16609 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16610 } 16611 pir.removeFilter(pa); 16612 } 16613 } 16614 } 16615 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16616 "Replacing preferred"); 16617 } 16618 } 16619 16620 @Override 16621 public void clearPackagePreferredActivities(String packageName) { 16622 final int uid = Binder.getCallingUid(); 16623 // writer 16624 synchronized (mPackages) { 16625 PackageParser.Package pkg = mPackages.get(packageName); 16626 if (pkg == null || pkg.applicationInfo.uid != uid) { 16627 if (mContext.checkCallingOrSelfPermission( 16628 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16629 != PackageManager.PERMISSION_GRANTED) { 16630 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16631 < Build.VERSION_CODES.FROYO) { 16632 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16633 + Binder.getCallingUid()); 16634 return; 16635 } 16636 mContext.enforceCallingOrSelfPermission( 16637 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16638 } 16639 } 16640 16641 int user = UserHandle.getCallingUserId(); 16642 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16643 scheduleWritePackageRestrictionsLocked(user); 16644 } 16645 } 16646 } 16647 16648 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16649 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16650 ArrayList<PreferredActivity> removed = null; 16651 boolean changed = false; 16652 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16653 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16654 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16655 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16656 continue; 16657 } 16658 Iterator<PreferredActivity> it = pir.filterIterator(); 16659 while (it.hasNext()) { 16660 PreferredActivity pa = it.next(); 16661 // Mark entry for removal only if it matches the package name 16662 // and the entry is of type "always". 16663 if (packageName == null || 16664 (pa.mPref.mComponent.getPackageName().equals(packageName) 16665 && pa.mPref.mAlways)) { 16666 if (removed == null) { 16667 removed = new ArrayList<PreferredActivity>(); 16668 } 16669 removed.add(pa); 16670 } 16671 } 16672 if (removed != null) { 16673 for (int j=0; j<removed.size(); j++) { 16674 PreferredActivity pa = removed.get(j); 16675 pir.removeFilter(pa); 16676 } 16677 changed = true; 16678 } 16679 } 16680 return changed; 16681 } 16682 16683 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16684 private void clearIntentFilterVerificationsLPw(int userId) { 16685 final int packageCount = mPackages.size(); 16686 for (int i = 0; i < packageCount; i++) { 16687 PackageParser.Package pkg = mPackages.valueAt(i); 16688 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16689 } 16690 } 16691 16692 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16693 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16694 if (userId == UserHandle.USER_ALL) { 16695 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16696 sUserManager.getUserIds())) { 16697 for (int oneUserId : sUserManager.getUserIds()) { 16698 scheduleWritePackageRestrictionsLocked(oneUserId); 16699 } 16700 } 16701 } else { 16702 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16703 scheduleWritePackageRestrictionsLocked(userId); 16704 } 16705 } 16706 } 16707 16708 void clearDefaultBrowserIfNeeded(String packageName) { 16709 for (int oneUserId : sUserManager.getUserIds()) { 16710 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16711 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16712 if (packageName.equals(defaultBrowserPackageName)) { 16713 setDefaultBrowserPackageName(null, oneUserId); 16714 } 16715 } 16716 } 16717 16718 @Override 16719 public void resetApplicationPreferences(int userId) { 16720 mContext.enforceCallingOrSelfPermission( 16721 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16722 final long identity = Binder.clearCallingIdentity(); 16723 // writer 16724 try { 16725 synchronized (mPackages) { 16726 clearPackagePreferredActivitiesLPw(null, userId); 16727 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16728 // TODO: We have to reset the default SMS and Phone. This requires 16729 // significant refactoring to keep all default apps in the package 16730 // manager (cleaner but more work) or have the services provide 16731 // callbacks to the package manager to request a default app reset. 16732 applyFactoryDefaultBrowserLPw(userId); 16733 clearIntentFilterVerificationsLPw(userId); 16734 primeDomainVerificationsLPw(userId); 16735 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16736 scheduleWritePackageRestrictionsLocked(userId); 16737 } 16738 resetNetworkPolicies(userId); 16739 } finally { 16740 Binder.restoreCallingIdentity(identity); 16741 } 16742 } 16743 16744 @Override 16745 public int getPreferredActivities(List<IntentFilter> outFilters, 16746 List<ComponentName> outActivities, String packageName) { 16747 16748 int num = 0; 16749 final int userId = UserHandle.getCallingUserId(); 16750 // reader 16751 synchronized (mPackages) { 16752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16753 if (pir != null) { 16754 final Iterator<PreferredActivity> it = pir.filterIterator(); 16755 while (it.hasNext()) { 16756 final PreferredActivity pa = it.next(); 16757 if (packageName == null 16758 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16759 && pa.mPref.mAlways)) { 16760 if (outFilters != null) { 16761 outFilters.add(new IntentFilter(pa)); 16762 } 16763 if (outActivities != null) { 16764 outActivities.add(pa.mPref.mComponent); 16765 } 16766 } 16767 } 16768 } 16769 } 16770 16771 return num; 16772 } 16773 16774 @Override 16775 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16776 int userId) { 16777 int callingUid = Binder.getCallingUid(); 16778 if (callingUid != Process.SYSTEM_UID) { 16779 throw new SecurityException( 16780 "addPersistentPreferredActivity can only be run by the system"); 16781 } 16782 if (filter.countActions() == 0) { 16783 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16784 return; 16785 } 16786 synchronized (mPackages) { 16787 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16788 ":"); 16789 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16790 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16791 new PersistentPreferredActivity(filter, activity)); 16792 scheduleWritePackageRestrictionsLocked(userId); 16793 } 16794 } 16795 16796 @Override 16797 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16798 int callingUid = Binder.getCallingUid(); 16799 if (callingUid != Process.SYSTEM_UID) { 16800 throw new SecurityException( 16801 "clearPackagePersistentPreferredActivities can only be run by the system"); 16802 } 16803 ArrayList<PersistentPreferredActivity> removed = null; 16804 boolean changed = false; 16805 synchronized (mPackages) { 16806 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16807 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16808 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16809 .valueAt(i); 16810 if (userId != thisUserId) { 16811 continue; 16812 } 16813 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16814 while (it.hasNext()) { 16815 PersistentPreferredActivity ppa = it.next(); 16816 // Mark entry for removal only if it matches the package name. 16817 if (ppa.mComponent.getPackageName().equals(packageName)) { 16818 if (removed == null) { 16819 removed = new ArrayList<PersistentPreferredActivity>(); 16820 } 16821 removed.add(ppa); 16822 } 16823 } 16824 if (removed != null) { 16825 for (int j=0; j<removed.size(); j++) { 16826 PersistentPreferredActivity ppa = removed.get(j); 16827 ppir.removeFilter(ppa); 16828 } 16829 changed = true; 16830 } 16831 } 16832 16833 if (changed) { 16834 scheduleWritePackageRestrictionsLocked(userId); 16835 } 16836 } 16837 } 16838 16839 /** 16840 * Common machinery for picking apart a restored XML blob and passing 16841 * it to a caller-supplied functor to be applied to the running system. 16842 */ 16843 private void restoreFromXml(XmlPullParser parser, int userId, 16844 String expectedStartTag, BlobXmlRestorer functor) 16845 throws IOException, XmlPullParserException { 16846 int type; 16847 while ((type = parser.next()) != XmlPullParser.START_TAG 16848 && type != XmlPullParser.END_DOCUMENT) { 16849 } 16850 if (type != XmlPullParser.START_TAG) { 16851 // oops didn't find a start tag?! 16852 if (DEBUG_BACKUP) { 16853 Slog.e(TAG, "Didn't find start tag during restore"); 16854 } 16855 return; 16856 } 16857Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16858 // this is supposed to be TAG_PREFERRED_BACKUP 16859 if (!expectedStartTag.equals(parser.getName())) { 16860 if (DEBUG_BACKUP) { 16861 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16862 } 16863 return; 16864 } 16865 16866 // skip interfering stuff, then we're aligned with the backing implementation 16867 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16868Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16869 functor.apply(parser, userId); 16870 } 16871 16872 private interface BlobXmlRestorer { 16873 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16874 } 16875 16876 /** 16877 * Non-Binder method, support for the backup/restore mechanism: write the 16878 * full set of preferred activities in its canonical XML format. Returns the 16879 * XML output as a byte array, or null if there is none. 16880 */ 16881 @Override 16882 public byte[] getPreferredActivityBackup(int userId) { 16883 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16884 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16885 } 16886 16887 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16888 try { 16889 final XmlSerializer serializer = new FastXmlSerializer(); 16890 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16891 serializer.startDocument(null, true); 16892 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16893 16894 synchronized (mPackages) { 16895 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16896 } 16897 16898 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16899 serializer.endDocument(); 16900 serializer.flush(); 16901 } catch (Exception e) { 16902 if (DEBUG_BACKUP) { 16903 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16904 } 16905 return null; 16906 } 16907 16908 return dataStream.toByteArray(); 16909 } 16910 16911 @Override 16912 public void restorePreferredActivities(byte[] backup, int userId) { 16913 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16914 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16915 } 16916 16917 try { 16918 final XmlPullParser parser = Xml.newPullParser(); 16919 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16920 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16921 new BlobXmlRestorer() { 16922 @Override 16923 public void apply(XmlPullParser parser, int userId) 16924 throws XmlPullParserException, IOException { 16925 synchronized (mPackages) { 16926 mSettings.readPreferredActivitiesLPw(parser, userId); 16927 } 16928 } 16929 } ); 16930 } catch (Exception e) { 16931 if (DEBUG_BACKUP) { 16932 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16933 } 16934 } 16935 } 16936 16937 /** 16938 * Non-Binder method, support for the backup/restore mechanism: write the 16939 * default browser (etc) settings in its canonical XML format. Returns the default 16940 * browser XML representation as a byte array, or null if there is none. 16941 */ 16942 @Override 16943 public byte[] getDefaultAppsBackup(int userId) { 16944 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16945 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16946 } 16947 16948 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16949 try { 16950 final XmlSerializer serializer = new FastXmlSerializer(); 16951 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16952 serializer.startDocument(null, true); 16953 serializer.startTag(null, TAG_DEFAULT_APPS); 16954 16955 synchronized (mPackages) { 16956 mSettings.writeDefaultAppsLPr(serializer, userId); 16957 } 16958 16959 serializer.endTag(null, TAG_DEFAULT_APPS); 16960 serializer.endDocument(); 16961 serializer.flush(); 16962 } catch (Exception e) { 16963 if (DEBUG_BACKUP) { 16964 Slog.e(TAG, "Unable to write default apps for backup", e); 16965 } 16966 return null; 16967 } 16968 16969 return dataStream.toByteArray(); 16970 } 16971 16972 @Override 16973 public void restoreDefaultApps(byte[] backup, int userId) { 16974 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16975 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16976 } 16977 16978 try { 16979 final XmlPullParser parser = Xml.newPullParser(); 16980 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16981 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16982 new BlobXmlRestorer() { 16983 @Override 16984 public void apply(XmlPullParser parser, int userId) 16985 throws XmlPullParserException, IOException { 16986 synchronized (mPackages) { 16987 mSettings.readDefaultAppsLPw(parser, userId); 16988 } 16989 } 16990 } ); 16991 } catch (Exception e) { 16992 if (DEBUG_BACKUP) { 16993 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16994 } 16995 } 16996 } 16997 16998 @Override 16999 public byte[] getIntentFilterVerificationBackup(int userId) { 17000 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17001 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17002 } 17003 17004 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17005 try { 17006 final XmlSerializer serializer = new FastXmlSerializer(); 17007 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17008 serializer.startDocument(null, true); 17009 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17010 17011 synchronized (mPackages) { 17012 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17013 } 17014 17015 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17016 serializer.endDocument(); 17017 serializer.flush(); 17018 } catch (Exception e) { 17019 if (DEBUG_BACKUP) { 17020 Slog.e(TAG, "Unable to write default apps for backup", e); 17021 } 17022 return null; 17023 } 17024 17025 return dataStream.toByteArray(); 17026 } 17027 17028 @Override 17029 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17030 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17031 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17032 } 17033 17034 try { 17035 final XmlPullParser parser = Xml.newPullParser(); 17036 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17037 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17038 new BlobXmlRestorer() { 17039 @Override 17040 public void apply(XmlPullParser parser, int userId) 17041 throws XmlPullParserException, IOException { 17042 synchronized (mPackages) { 17043 mSettings.readAllDomainVerificationsLPr(parser, userId); 17044 mSettings.writeLPr(); 17045 } 17046 } 17047 } ); 17048 } catch (Exception e) { 17049 if (DEBUG_BACKUP) { 17050 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17051 } 17052 } 17053 } 17054 17055 @Override 17056 public byte[] getPermissionGrantBackup(int userId) { 17057 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17058 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17059 } 17060 17061 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17062 try { 17063 final XmlSerializer serializer = new FastXmlSerializer(); 17064 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17065 serializer.startDocument(null, true); 17066 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17067 17068 synchronized (mPackages) { 17069 serializeRuntimePermissionGrantsLPr(serializer, userId); 17070 } 17071 17072 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17073 serializer.endDocument(); 17074 serializer.flush(); 17075 } catch (Exception e) { 17076 if (DEBUG_BACKUP) { 17077 Slog.e(TAG, "Unable to write default apps for backup", e); 17078 } 17079 return null; 17080 } 17081 17082 return dataStream.toByteArray(); 17083 } 17084 17085 @Override 17086 public void restorePermissionGrants(byte[] backup, int userId) { 17087 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17088 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17089 } 17090 17091 try { 17092 final XmlPullParser parser = Xml.newPullParser(); 17093 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17094 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17095 new BlobXmlRestorer() { 17096 @Override 17097 public void apply(XmlPullParser parser, int userId) 17098 throws XmlPullParserException, IOException { 17099 synchronized (mPackages) { 17100 processRestoredPermissionGrantsLPr(parser, userId); 17101 } 17102 } 17103 } ); 17104 } catch (Exception e) { 17105 if (DEBUG_BACKUP) { 17106 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17107 } 17108 } 17109 } 17110 17111 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17112 throws IOException { 17113 serializer.startTag(null, TAG_ALL_GRANTS); 17114 17115 final int N = mSettings.mPackages.size(); 17116 for (int i = 0; i < N; i++) { 17117 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17118 boolean pkgGrantsKnown = false; 17119 17120 PermissionsState packagePerms = ps.getPermissionsState(); 17121 17122 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17123 final int grantFlags = state.getFlags(); 17124 // only look at grants that are not system/policy fixed 17125 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17126 final boolean isGranted = state.isGranted(); 17127 // And only back up the user-twiddled state bits 17128 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17129 final String packageName = mSettings.mPackages.keyAt(i); 17130 if (!pkgGrantsKnown) { 17131 serializer.startTag(null, TAG_GRANT); 17132 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17133 pkgGrantsKnown = true; 17134 } 17135 17136 final boolean userSet = 17137 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17138 final boolean userFixed = 17139 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17140 final boolean revoke = 17141 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17142 17143 serializer.startTag(null, TAG_PERMISSION); 17144 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17145 if (isGranted) { 17146 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17147 } 17148 if (userSet) { 17149 serializer.attribute(null, ATTR_USER_SET, "true"); 17150 } 17151 if (userFixed) { 17152 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17153 } 17154 if (revoke) { 17155 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17156 } 17157 serializer.endTag(null, TAG_PERMISSION); 17158 } 17159 } 17160 } 17161 17162 if (pkgGrantsKnown) { 17163 serializer.endTag(null, TAG_GRANT); 17164 } 17165 } 17166 17167 serializer.endTag(null, TAG_ALL_GRANTS); 17168 } 17169 17170 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17171 throws XmlPullParserException, IOException { 17172 String pkgName = null; 17173 int outerDepth = parser.getDepth(); 17174 int type; 17175 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17176 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17177 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17178 continue; 17179 } 17180 17181 final String tagName = parser.getName(); 17182 if (tagName.equals(TAG_GRANT)) { 17183 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17184 if (DEBUG_BACKUP) { 17185 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17186 } 17187 } else if (tagName.equals(TAG_PERMISSION)) { 17188 17189 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17190 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17191 17192 int newFlagSet = 0; 17193 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17194 newFlagSet |= FLAG_PERMISSION_USER_SET; 17195 } 17196 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17197 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17198 } 17199 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17200 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17201 } 17202 if (DEBUG_BACKUP) { 17203 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17204 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17205 } 17206 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17207 if (ps != null) { 17208 // Already installed so we apply the grant immediately 17209 if (DEBUG_BACKUP) { 17210 Slog.v(TAG, " + already installed; applying"); 17211 } 17212 PermissionsState perms = ps.getPermissionsState(); 17213 BasePermission bp = mSettings.mPermissions.get(permName); 17214 if (bp != null) { 17215 if (isGranted) { 17216 perms.grantRuntimePermission(bp, userId); 17217 } 17218 if (newFlagSet != 0) { 17219 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17220 } 17221 } 17222 } else { 17223 // Need to wait for post-restore install to apply the grant 17224 if (DEBUG_BACKUP) { 17225 Slog.v(TAG, " - not yet installed; saving for later"); 17226 } 17227 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17228 isGranted, newFlagSet, userId); 17229 } 17230 } else { 17231 PackageManagerService.reportSettingsProblem(Log.WARN, 17232 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17233 XmlUtils.skipCurrentTag(parser); 17234 } 17235 } 17236 17237 scheduleWriteSettingsLocked(); 17238 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17239 } 17240 17241 @Override 17242 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17243 int sourceUserId, int targetUserId, int flags) { 17244 mContext.enforceCallingOrSelfPermission( 17245 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17246 int callingUid = Binder.getCallingUid(); 17247 enforceOwnerRights(ownerPackage, callingUid); 17248 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17249 if (intentFilter.countActions() == 0) { 17250 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17251 return; 17252 } 17253 synchronized (mPackages) { 17254 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17255 ownerPackage, targetUserId, flags); 17256 CrossProfileIntentResolver resolver = 17257 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17258 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17259 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17260 if (existing != null) { 17261 int size = existing.size(); 17262 for (int i = 0; i < size; i++) { 17263 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17264 return; 17265 } 17266 } 17267 } 17268 resolver.addFilter(newFilter); 17269 scheduleWritePackageRestrictionsLocked(sourceUserId); 17270 } 17271 } 17272 17273 @Override 17274 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17275 mContext.enforceCallingOrSelfPermission( 17276 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17277 int callingUid = Binder.getCallingUid(); 17278 enforceOwnerRights(ownerPackage, callingUid); 17279 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17280 synchronized (mPackages) { 17281 CrossProfileIntentResolver resolver = 17282 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17283 ArraySet<CrossProfileIntentFilter> set = 17284 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17285 for (CrossProfileIntentFilter filter : set) { 17286 if (filter.getOwnerPackage().equals(ownerPackage)) { 17287 resolver.removeFilter(filter); 17288 } 17289 } 17290 scheduleWritePackageRestrictionsLocked(sourceUserId); 17291 } 17292 } 17293 17294 // Enforcing that callingUid is owning pkg on userId 17295 private void enforceOwnerRights(String pkg, int callingUid) { 17296 // The system owns everything. 17297 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17298 return; 17299 } 17300 int callingUserId = UserHandle.getUserId(callingUid); 17301 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17302 if (pi == null) { 17303 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17304 + callingUserId); 17305 } 17306 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17307 throw new SecurityException("Calling uid " + callingUid 17308 + " does not own package " + pkg); 17309 } 17310 } 17311 17312 @Override 17313 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17314 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17315 } 17316 17317 private Intent getHomeIntent() { 17318 Intent intent = new Intent(Intent.ACTION_MAIN); 17319 intent.addCategory(Intent.CATEGORY_HOME); 17320 return intent; 17321 } 17322 17323 private IntentFilter getHomeFilter() { 17324 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17325 filter.addCategory(Intent.CATEGORY_HOME); 17326 filter.addCategory(Intent.CATEGORY_DEFAULT); 17327 return filter; 17328 } 17329 17330 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17331 int userId) { 17332 Intent intent = getHomeIntent(); 17333 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17334 PackageManager.GET_META_DATA, userId); 17335 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17336 true, false, false, userId); 17337 17338 allHomeCandidates.clear(); 17339 if (list != null) { 17340 for (ResolveInfo ri : list) { 17341 allHomeCandidates.add(ri); 17342 } 17343 } 17344 return (preferred == null || preferred.activityInfo == null) 17345 ? null 17346 : new ComponentName(preferred.activityInfo.packageName, 17347 preferred.activityInfo.name); 17348 } 17349 17350 @Override 17351 public void setHomeActivity(ComponentName comp, int userId) { 17352 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17353 getHomeActivitiesAsUser(homeActivities, userId); 17354 17355 boolean found = false; 17356 17357 final int size = homeActivities.size(); 17358 final ComponentName[] set = new ComponentName[size]; 17359 for (int i = 0; i < size; i++) { 17360 final ResolveInfo candidate = homeActivities.get(i); 17361 final ActivityInfo info = candidate.activityInfo; 17362 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17363 set[i] = activityName; 17364 if (!found && activityName.equals(comp)) { 17365 found = true; 17366 } 17367 } 17368 if (!found) { 17369 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17370 + userId); 17371 } 17372 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17373 set, comp, userId); 17374 } 17375 17376 private @Nullable String getSetupWizardPackageName() { 17377 final Intent intent = new Intent(Intent.ACTION_MAIN); 17378 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17379 17380 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17381 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17382 | MATCH_DISABLED_COMPONENTS, 17383 UserHandle.myUserId()); 17384 if (matches.size() == 1) { 17385 return matches.get(0).getComponentInfo().packageName; 17386 } else { 17387 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17388 + ": matches=" + matches); 17389 return null; 17390 } 17391 } 17392 17393 @Override 17394 public void setApplicationEnabledSetting(String appPackageName, 17395 int newState, int flags, int userId, String callingPackage) { 17396 if (!sUserManager.exists(userId)) return; 17397 if (callingPackage == null) { 17398 callingPackage = Integer.toString(Binder.getCallingUid()); 17399 } 17400 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17401 } 17402 17403 @Override 17404 public void setComponentEnabledSetting(ComponentName componentName, 17405 int newState, int flags, int userId) { 17406 if (!sUserManager.exists(userId)) return; 17407 setEnabledSetting(componentName.getPackageName(), 17408 componentName.getClassName(), newState, flags, userId, null); 17409 } 17410 17411 private void setEnabledSetting(final String packageName, String className, int newState, 17412 final int flags, int userId, String callingPackage) { 17413 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17414 || newState == COMPONENT_ENABLED_STATE_ENABLED 17415 || newState == COMPONENT_ENABLED_STATE_DISABLED 17416 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17417 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17418 throw new IllegalArgumentException("Invalid new component state: " 17419 + newState); 17420 } 17421 PackageSetting pkgSetting; 17422 final int uid = Binder.getCallingUid(); 17423 final int permission; 17424 if (uid == Process.SYSTEM_UID) { 17425 permission = PackageManager.PERMISSION_GRANTED; 17426 } else { 17427 permission = mContext.checkCallingOrSelfPermission( 17428 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17429 } 17430 enforceCrossUserPermission(uid, userId, 17431 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17432 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17433 boolean sendNow = false; 17434 boolean isApp = (className == null); 17435 String componentName = isApp ? packageName : className; 17436 int packageUid = -1; 17437 ArrayList<String> components; 17438 17439 // writer 17440 synchronized (mPackages) { 17441 pkgSetting = mSettings.mPackages.get(packageName); 17442 if (pkgSetting == null) { 17443 if (className == null) { 17444 throw new IllegalArgumentException("Unknown package: " + packageName); 17445 } 17446 throw new IllegalArgumentException( 17447 "Unknown component: " + packageName + "/" + className); 17448 } 17449 // Allow root and verify that userId is not being specified by a different user 17450 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17451 throw new SecurityException( 17452 "Permission Denial: attempt to change component state from pid=" 17453 + Binder.getCallingPid() 17454 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17455 } 17456 if (className == null) { 17457 // We're dealing with an application/package level state change 17458 if (pkgSetting.getEnabled(userId) == newState) { 17459 // Nothing to do 17460 return; 17461 } 17462 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17463 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17464 // Don't care about who enables an app. 17465 callingPackage = null; 17466 } 17467 pkgSetting.setEnabled(newState, userId, callingPackage); 17468 // pkgSetting.pkg.mSetEnabled = newState; 17469 } else { 17470 // We're dealing with a component level state change 17471 // First, verify that this is a valid class name. 17472 PackageParser.Package pkg = pkgSetting.pkg; 17473 if (pkg == null || !pkg.hasComponentClassName(className)) { 17474 if (pkg != null && 17475 pkg.applicationInfo.targetSdkVersion >= 17476 Build.VERSION_CODES.JELLY_BEAN) { 17477 throw new IllegalArgumentException("Component class " + className 17478 + " does not exist in " + packageName); 17479 } else { 17480 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17481 + className + " does not exist in " + packageName); 17482 } 17483 } 17484 switch (newState) { 17485 case COMPONENT_ENABLED_STATE_ENABLED: 17486 if (!pkgSetting.enableComponentLPw(className, userId)) { 17487 return; 17488 } 17489 break; 17490 case COMPONENT_ENABLED_STATE_DISABLED: 17491 if (!pkgSetting.disableComponentLPw(className, userId)) { 17492 return; 17493 } 17494 break; 17495 case COMPONENT_ENABLED_STATE_DEFAULT: 17496 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17497 return; 17498 } 17499 break; 17500 default: 17501 Slog.e(TAG, "Invalid new component state: " + newState); 17502 return; 17503 } 17504 } 17505 scheduleWritePackageRestrictionsLocked(userId); 17506 components = mPendingBroadcasts.get(userId, packageName); 17507 final boolean newPackage = components == null; 17508 if (newPackage) { 17509 components = new ArrayList<String>(); 17510 } 17511 if (!components.contains(componentName)) { 17512 components.add(componentName); 17513 } 17514 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17515 sendNow = true; 17516 // Purge entry from pending broadcast list if another one exists already 17517 // since we are sending one right away. 17518 mPendingBroadcasts.remove(userId, packageName); 17519 } else { 17520 if (newPackage) { 17521 mPendingBroadcasts.put(userId, packageName, components); 17522 } 17523 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17524 // Schedule a message 17525 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17526 } 17527 } 17528 } 17529 17530 long callingId = Binder.clearCallingIdentity(); 17531 try { 17532 if (sendNow) { 17533 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17534 sendPackageChangedBroadcast(packageName, 17535 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17536 } 17537 } finally { 17538 Binder.restoreCallingIdentity(callingId); 17539 } 17540 } 17541 17542 @Override 17543 public void flushPackageRestrictionsAsUser(int userId) { 17544 if (!sUserManager.exists(userId)) { 17545 return; 17546 } 17547 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17548 false /* checkShell */, "flushPackageRestrictions"); 17549 synchronized (mPackages) { 17550 mSettings.writePackageRestrictionsLPr(userId); 17551 mDirtyUsers.remove(userId); 17552 if (mDirtyUsers.isEmpty()) { 17553 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17554 } 17555 } 17556 } 17557 17558 private void sendPackageChangedBroadcast(String packageName, 17559 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17560 if (DEBUG_INSTALL) 17561 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17562 + componentNames); 17563 Bundle extras = new Bundle(4); 17564 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17565 String nameList[] = new String[componentNames.size()]; 17566 componentNames.toArray(nameList); 17567 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17568 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17569 extras.putInt(Intent.EXTRA_UID, packageUid); 17570 // If this is not reporting a change of the overall package, then only send it 17571 // to registered receivers. We don't want to launch a swath of apps for every 17572 // little component state change. 17573 final int flags = !componentNames.contains(packageName) 17574 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17575 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17576 new int[] {UserHandle.getUserId(packageUid)}); 17577 } 17578 17579 @Override 17580 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17581 if (!sUserManager.exists(userId)) return; 17582 final int uid = Binder.getCallingUid(); 17583 final int permission = mContext.checkCallingOrSelfPermission( 17584 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17585 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17586 enforceCrossUserPermission(uid, userId, 17587 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17588 // writer 17589 synchronized (mPackages) { 17590 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17591 allowedByPermission, uid, userId)) { 17592 scheduleWritePackageRestrictionsLocked(userId); 17593 } 17594 } 17595 } 17596 17597 @Override 17598 public String getInstallerPackageName(String packageName) { 17599 // reader 17600 synchronized (mPackages) { 17601 return mSettings.getInstallerPackageNameLPr(packageName); 17602 } 17603 } 17604 17605 public boolean isOrphaned(String packageName) { 17606 // reader 17607 synchronized (mPackages) { 17608 return mSettings.isOrphaned(packageName); 17609 } 17610 } 17611 17612 @Override 17613 public int getApplicationEnabledSetting(String packageName, int userId) { 17614 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17615 int uid = Binder.getCallingUid(); 17616 enforceCrossUserPermission(uid, userId, 17617 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17618 // reader 17619 synchronized (mPackages) { 17620 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17621 } 17622 } 17623 17624 @Override 17625 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17626 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17627 int uid = Binder.getCallingUid(); 17628 enforceCrossUserPermission(uid, userId, 17629 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17630 // reader 17631 synchronized (mPackages) { 17632 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17633 } 17634 } 17635 17636 @Override 17637 public void enterSafeMode() { 17638 enforceSystemOrRoot("Only the system can request entering safe mode"); 17639 17640 if (!mSystemReady) { 17641 mSafeMode = true; 17642 } 17643 } 17644 17645 @Override 17646 public void systemReady() { 17647 mSystemReady = true; 17648 17649 // Read the compatibilty setting when the system is ready. 17650 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17651 mContext.getContentResolver(), 17652 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17653 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17654 if (DEBUG_SETTINGS) { 17655 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17656 } 17657 17658 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17659 17660 synchronized (mPackages) { 17661 // Verify that all of the preferred activity components actually 17662 // exist. It is possible for applications to be updated and at 17663 // that point remove a previously declared activity component that 17664 // had been set as a preferred activity. We try to clean this up 17665 // the next time we encounter that preferred activity, but it is 17666 // possible for the user flow to never be able to return to that 17667 // situation so here we do a sanity check to make sure we haven't 17668 // left any junk around. 17669 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17670 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17671 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17672 removed.clear(); 17673 for (PreferredActivity pa : pir.filterSet()) { 17674 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17675 removed.add(pa); 17676 } 17677 } 17678 if (removed.size() > 0) { 17679 for (int r=0; r<removed.size(); r++) { 17680 PreferredActivity pa = removed.get(r); 17681 Slog.w(TAG, "Removing dangling preferred activity: " 17682 + pa.mPref.mComponent); 17683 pir.removeFilter(pa); 17684 } 17685 mSettings.writePackageRestrictionsLPr( 17686 mSettings.mPreferredActivities.keyAt(i)); 17687 } 17688 } 17689 17690 for (int userId : UserManagerService.getInstance().getUserIds()) { 17691 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17692 grantPermissionsUserIds = ArrayUtils.appendInt( 17693 grantPermissionsUserIds, userId); 17694 } 17695 } 17696 } 17697 sUserManager.systemReady(); 17698 17699 // If we upgraded grant all default permissions before kicking off. 17700 for (int userId : grantPermissionsUserIds) { 17701 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17702 } 17703 17704 // Kick off any messages waiting for system ready 17705 if (mPostSystemReadyMessages != null) { 17706 for (Message msg : mPostSystemReadyMessages) { 17707 msg.sendToTarget(); 17708 } 17709 mPostSystemReadyMessages = null; 17710 } 17711 17712 // Watch for external volumes that come and go over time 17713 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17714 storage.registerListener(mStorageListener); 17715 17716 mInstallerService.systemReady(); 17717 mPackageDexOptimizer.systemReady(); 17718 17719 MountServiceInternal mountServiceInternal = LocalServices.getService( 17720 MountServiceInternal.class); 17721 mountServiceInternal.addExternalStoragePolicy( 17722 new MountServiceInternal.ExternalStorageMountPolicy() { 17723 @Override 17724 public int getMountMode(int uid, String packageName) { 17725 if (Process.isIsolated(uid)) { 17726 return Zygote.MOUNT_EXTERNAL_NONE; 17727 } 17728 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17729 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17730 } 17731 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17732 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17733 } 17734 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17735 return Zygote.MOUNT_EXTERNAL_READ; 17736 } 17737 return Zygote.MOUNT_EXTERNAL_WRITE; 17738 } 17739 17740 @Override 17741 public boolean hasExternalStorage(int uid, String packageName) { 17742 return true; 17743 } 17744 }); 17745 17746 // Now that we're mostly running, clean up stale users and apps 17747 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17748 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17749 } 17750 17751 @Override 17752 public boolean isSafeMode() { 17753 return mSafeMode; 17754 } 17755 17756 @Override 17757 public boolean hasSystemUidErrors() { 17758 return mHasSystemUidErrors; 17759 } 17760 17761 static String arrayToString(int[] array) { 17762 StringBuffer buf = new StringBuffer(128); 17763 buf.append('['); 17764 if (array != null) { 17765 for (int i=0; i<array.length; i++) { 17766 if (i > 0) buf.append(", "); 17767 buf.append(array[i]); 17768 } 17769 } 17770 buf.append(']'); 17771 return buf.toString(); 17772 } 17773 17774 static class DumpState { 17775 public static final int DUMP_LIBS = 1 << 0; 17776 public static final int DUMP_FEATURES = 1 << 1; 17777 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17778 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17779 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17780 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17781 public static final int DUMP_PERMISSIONS = 1 << 6; 17782 public static final int DUMP_PACKAGES = 1 << 7; 17783 public static final int DUMP_SHARED_USERS = 1 << 8; 17784 public static final int DUMP_MESSAGES = 1 << 9; 17785 public static final int DUMP_PROVIDERS = 1 << 10; 17786 public static final int DUMP_VERIFIERS = 1 << 11; 17787 public static final int DUMP_PREFERRED = 1 << 12; 17788 public static final int DUMP_PREFERRED_XML = 1 << 13; 17789 public static final int DUMP_KEYSETS = 1 << 14; 17790 public static final int DUMP_VERSION = 1 << 15; 17791 public static final int DUMP_INSTALLS = 1 << 16; 17792 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17793 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17794 public static final int DUMP_FROZEN = 1 << 19; 17795 17796 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17797 17798 private int mTypes; 17799 17800 private int mOptions; 17801 17802 private boolean mTitlePrinted; 17803 17804 private SharedUserSetting mSharedUser; 17805 17806 public boolean isDumping(int type) { 17807 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17808 return true; 17809 } 17810 17811 return (mTypes & type) != 0; 17812 } 17813 17814 public void setDump(int type) { 17815 mTypes |= type; 17816 } 17817 17818 public boolean isOptionEnabled(int option) { 17819 return (mOptions & option) != 0; 17820 } 17821 17822 public void setOptionEnabled(int option) { 17823 mOptions |= option; 17824 } 17825 17826 public boolean onTitlePrinted() { 17827 final boolean printed = mTitlePrinted; 17828 mTitlePrinted = true; 17829 return printed; 17830 } 17831 17832 public boolean getTitlePrinted() { 17833 return mTitlePrinted; 17834 } 17835 17836 public void setTitlePrinted(boolean enabled) { 17837 mTitlePrinted = enabled; 17838 } 17839 17840 public SharedUserSetting getSharedUser() { 17841 return mSharedUser; 17842 } 17843 17844 public void setSharedUser(SharedUserSetting user) { 17845 mSharedUser = user; 17846 } 17847 } 17848 17849 @Override 17850 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17851 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17852 (new PackageManagerShellCommand(this)).exec( 17853 this, in, out, err, args, resultReceiver); 17854 } 17855 17856 @Override 17857 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17858 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17859 != PackageManager.PERMISSION_GRANTED) { 17860 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17861 + Binder.getCallingPid() 17862 + ", uid=" + Binder.getCallingUid() 17863 + " without permission " 17864 + android.Manifest.permission.DUMP); 17865 return; 17866 } 17867 17868 DumpState dumpState = new DumpState(); 17869 boolean fullPreferred = false; 17870 boolean checkin = false; 17871 17872 String packageName = null; 17873 ArraySet<String> permissionNames = null; 17874 17875 int opti = 0; 17876 while (opti < args.length) { 17877 String opt = args[opti]; 17878 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17879 break; 17880 } 17881 opti++; 17882 17883 if ("-a".equals(opt)) { 17884 // Right now we only know how to print all. 17885 } else if ("-h".equals(opt)) { 17886 pw.println("Package manager dump options:"); 17887 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17888 pw.println(" --checkin: dump for a checkin"); 17889 pw.println(" -f: print details of intent filters"); 17890 pw.println(" -h: print this help"); 17891 pw.println(" cmd may be one of:"); 17892 pw.println(" l[ibraries]: list known shared libraries"); 17893 pw.println(" f[eatures]: list device features"); 17894 pw.println(" k[eysets]: print known keysets"); 17895 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17896 pw.println(" perm[issions]: dump permissions"); 17897 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17898 pw.println(" pref[erred]: print preferred package settings"); 17899 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17900 pw.println(" prov[iders]: dump content providers"); 17901 pw.println(" p[ackages]: dump installed packages"); 17902 pw.println(" s[hared-users]: dump shared user IDs"); 17903 pw.println(" m[essages]: print collected runtime messages"); 17904 pw.println(" v[erifiers]: print package verifier info"); 17905 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17906 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17907 pw.println(" version: print database version info"); 17908 pw.println(" write: write current settings now"); 17909 pw.println(" installs: details about install sessions"); 17910 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17911 pw.println(" <package.name>: info about given package"); 17912 return; 17913 } else if ("--checkin".equals(opt)) { 17914 checkin = true; 17915 } else if ("-f".equals(opt)) { 17916 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17917 } else { 17918 pw.println("Unknown argument: " + opt + "; use -h for help"); 17919 } 17920 } 17921 17922 // Is the caller requesting to dump a particular piece of data? 17923 if (opti < args.length) { 17924 String cmd = args[opti]; 17925 opti++; 17926 // Is this a package name? 17927 if ("android".equals(cmd) || cmd.contains(".")) { 17928 packageName = cmd; 17929 // When dumping a single package, we always dump all of its 17930 // filter information since the amount of data will be reasonable. 17931 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17932 } else if ("check-permission".equals(cmd)) { 17933 if (opti >= args.length) { 17934 pw.println("Error: check-permission missing permission argument"); 17935 return; 17936 } 17937 String perm = args[opti]; 17938 opti++; 17939 if (opti >= args.length) { 17940 pw.println("Error: check-permission missing package argument"); 17941 return; 17942 } 17943 String pkg = args[opti]; 17944 opti++; 17945 int user = UserHandle.getUserId(Binder.getCallingUid()); 17946 if (opti < args.length) { 17947 try { 17948 user = Integer.parseInt(args[opti]); 17949 } catch (NumberFormatException e) { 17950 pw.println("Error: check-permission user argument is not a number: " 17951 + args[opti]); 17952 return; 17953 } 17954 } 17955 pw.println(checkPermission(perm, pkg, user)); 17956 return; 17957 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17958 dumpState.setDump(DumpState.DUMP_LIBS); 17959 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17960 dumpState.setDump(DumpState.DUMP_FEATURES); 17961 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17962 if (opti >= args.length) { 17963 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17964 | DumpState.DUMP_SERVICE_RESOLVERS 17965 | DumpState.DUMP_RECEIVER_RESOLVERS 17966 | DumpState.DUMP_CONTENT_RESOLVERS); 17967 } else { 17968 while (opti < args.length) { 17969 String name = args[opti]; 17970 if ("a".equals(name) || "activity".equals(name)) { 17971 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17972 } else if ("s".equals(name) || "service".equals(name)) { 17973 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17974 } else if ("r".equals(name) || "receiver".equals(name)) { 17975 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17976 } else if ("c".equals(name) || "content".equals(name)) { 17977 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17978 } else { 17979 pw.println("Error: unknown resolver table type: " + name); 17980 return; 17981 } 17982 opti++; 17983 } 17984 } 17985 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17986 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17987 } else if ("permission".equals(cmd)) { 17988 if (opti >= args.length) { 17989 pw.println("Error: permission requires permission name"); 17990 return; 17991 } 17992 permissionNames = new ArraySet<>(); 17993 while (opti < args.length) { 17994 permissionNames.add(args[opti]); 17995 opti++; 17996 } 17997 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17998 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17999 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18000 dumpState.setDump(DumpState.DUMP_PREFERRED); 18001 } else if ("preferred-xml".equals(cmd)) { 18002 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18003 if (opti < args.length && "--full".equals(args[opti])) { 18004 fullPreferred = true; 18005 opti++; 18006 } 18007 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18008 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18009 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18010 dumpState.setDump(DumpState.DUMP_PACKAGES); 18011 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18012 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18013 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18014 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18015 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18016 dumpState.setDump(DumpState.DUMP_MESSAGES); 18017 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18018 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18019 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18020 || "intent-filter-verifiers".equals(cmd)) { 18021 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18022 } else if ("version".equals(cmd)) { 18023 dumpState.setDump(DumpState.DUMP_VERSION); 18024 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18025 dumpState.setDump(DumpState.DUMP_KEYSETS); 18026 } else if ("installs".equals(cmd)) { 18027 dumpState.setDump(DumpState.DUMP_INSTALLS); 18028 } else if ("frozen".equals(cmd)) { 18029 dumpState.setDump(DumpState.DUMP_FROZEN); 18030 } else if ("write".equals(cmd)) { 18031 synchronized (mPackages) { 18032 mSettings.writeLPr(); 18033 pw.println("Settings written."); 18034 return; 18035 } 18036 } 18037 } 18038 18039 if (checkin) { 18040 pw.println("vers,1"); 18041 } 18042 18043 // reader 18044 synchronized (mPackages) { 18045 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18046 if (!checkin) { 18047 if (dumpState.onTitlePrinted()) 18048 pw.println(); 18049 pw.println("Database versions:"); 18050 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18051 } 18052 } 18053 18054 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18055 if (!checkin) { 18056 if (dumpState.onTitlePrinted()) 18057 pw.println(); 18058 pw.println("Verifiers:"); 18059 pw.print(" Required: "); 18060 pw.print(mRequiredVerifierPackage); 18061 pw.print(" (uid="); 18062 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18063 UserHandle.USER_SYSTEM)); 18064 pw.println(")"); 18065 } else if (mRequiredVerifierPackage != null) { 18066 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18067 pw.print(","); 18068 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18069 UserHandle.USER_SYSTEM)); 18070 } 18071 } 18072 18073 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18074 packageName == null) { 18075 if (mIntentFilterVerifierComponent != null) { 18076 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18077 if (!checkin) { 18078 if (dumpState.onTitlePrinted()) 18079 pw.println(); 18080 pw.println("Intent Filter Verifier:"); 18081 pw.print(" Using: "); 18082 pw.print(verifierPackageName); 18083 pw.print(" (uid="); 18084 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18085 UserHandle.USER_SYSTEM)); 18086 pw.println(")"); 18087 } else if (verifierPackageName != null) { 18088 pw.print("ifv,"); pw.print(verifierPackageName); 18089 pw.print(","); 18090 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18091 UserHandle.USER_SYSTEM)); 18092 } 18093 } else { 18094 pw.println(); 18095 pw.println("No Intent Filter Verifier available!"); 18096 } 18097 } 18098 18099 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18100 boolean printedHeader = false; 18101 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18102 while (it.hasNext()) { 18103 String name = it.next(); 18104 SharedLibraryEntry ent = mSharedLibraries.get(name); 18105 if (!checkin) { 18106 if (!printedHeader) { 18107 if (dumpState.onTitlePrinted()) 18108 pw.println(); 18109 pw.println("Libraries:"); 18110 printedHeader = true; 18111 } 18112 pw.print(" "); 18113 } else { 18114 pw.print("lib,"); 18115 } 18116 pw.print(name); 18117 if (!checkin) { 18118 pw.print(" -> "); 18119 } 18120 if (ent.path != null) { 18121 if (!checkin) { 18122 pw.print("(jar) "); 18123 pw.print(ent.path); 18124 } else { 18125 pw.print(",jar,"); 18126 pw.print(ent.path); 18127 } 18128 } else { 18129 if (!checkin) { 18130 pw.print("(apk) "); 18131 pw.print(ent.apk); 18132 } else { 18133 pw.print(",apk,"); 18134 pw.print(ent.apk); 18135 } 18136 } 18137 pw.println(); 18138 } 18139 } 18140 18141 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18142 if (dumpState.onTitlePrinted()) 18143 pw.println(); 18144 if (!checkin) { 18145 pw.println("Features:"); 18146 } 18147 18148 for (FeatureInfo feat : mAvailableFeatures.values()) { 18149 if (checkin) { 18150 pw.print("feat,"); 18151 pw.print(feat.name); 18152 pw.print(","); 18153 pw.println(feat.version); 18154 } else { 18155 pw.print(" "); 18156 pw.print(feat.name); 18157 if (feat.version > 0) { 18158 pw.print(" version="); 18159 pw.print(feat.version); 18160 } 18161 pw.println(); 18162 } 18163 } 18164 } 18165 18166 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18167 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18168 : "Activity Resolver Table:", " ", packageName, 18169 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18170 dumpState.setTitlePrinted(true); 18171 } 18172 } 18173 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18174 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18175 : "Receiver Resolver Table:", " ", packageName, 18176 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18177 dumpState.setTitlePrinted(true); 18178 } 18179 } 18180 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18181 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18182 : "Service Resolver Table:", " ", packageName, 18183 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18184 dumpState.setTitlePrinted(true); 18185 } 18186 } 18187 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18188 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18189 : "Provider Resolver Table:", " ", packageName, 18190 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18191 dumpState.setTitlePrinted(true); 18192 } 18193 } 18194 18195 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18196 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18197 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18198 int user = mSettings.mPreferredActivities.keyAt(i); 18199 if (pir.dump(pw, 18200 dumpState.getTitlePrinted() 18201 ? "\nPreferred Activities User " + user + ":" 18202 : "Preferred Activities User " + user + ":", " ", 18203 packageName, true, false)) { 18204 dumpState.setTitlePrinted(true); 18205 } 18206 } 18207 } 18208 18209 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18210 pw.flush(); 18211 FileOutputStream fout = new FileOutputStream(fd); 18212 BufferedOutputStream str = new BufferedOutputStream(fout); 18213 XmlSerializer serializer = new FastXmlSerializer(); 18214 try { 18215 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18216 serializer.startDocument(null, true); 18217 serializer.setFeature( 18218 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18219 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18220 serializer.endDocument(); 18221 serializer.flush(); 18222 } catch (IllegalArgumentException e) { 18223 pw.println("Failed writing: " + e); 18224 } catch (IllegalStateException e) { 18225 pw.println("Failed writing: " + e); 18226 } catch (IOException e) { 18227 pw.println("Failed writing: " + e); 18228 } 18229 } 18230 18231 if (!checkin 18232 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18233 && packageName == null) { 18234 pw.println(); 18235 int count = mSettings.mPackages.size(); 18236 if (count == 0) { 18237 pw.println("No applications!"); 18238 pw.println(); 18239 } else { 18240 final String prefix = " "; 18241 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18242 if (allPackageSettings.size() == 0) { 18243 pw.println("No domain preferred apps!"); 18244 pw.println(); 18245 } else { 18246 pw.println("App verification status:"); 18247 pw.println(); 18248 count = 0; 18249 for (PackageSetting ps : allPackageSettings) { 18250 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18251 if (ivi == null || ivi.getPackageName() == null) continue; 18252 pw.println(prefix + "Package: " + ivi.getPackageName()); 18253 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18254 pw.println(prefix + "Status: " + ivi.getStatusString()); 18255 pw.println(); 18256 count++; 18257 } 18258 if (count == 0) { 18259 pw.println(prefix + "No app verification established."); 18260 pw.println(); 18261 } 18262 for (int userId : sUserManager.getUserIds()) { 18263 pw.println("App linkages for user " + userId + ":"); 18264 pw.println(); 18265 count = 0; 18266 for (PackageSetting ps : allPackageSettings) { 18267 final long status = ps.getDomainVerificationStatusForUser(userId); 18268 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18269 continue; 18270 } 18271 pw.println(prefix + "Package: " + ps.name); 18272 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18273 String statusStr = IntentFilterVerificationInfo. 18274 getStatusStringFromValue(status); 18275 pw.println(prefix + "Status: " + statusStr); 18276 pw.println(); 18277 count++; 18278 } 18279 if (count == 0) { 18280 pw.println(prefix + "No configured app linkages."); 18281 pw.println(); 18282 } 18283 } 18284 } 18285 } 18286 } 18287 18288 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18289 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18290 if (packageName == null && permissionNames == null) { 18291 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18292 if (iperm == 0) { 18293 if (dumpState.onTitlePrinted()) 18294 pw.println(); 18295 pw.println("AppOp Permissions:"); 18296 } 18297 pw.print(" AppOp Permission "); 18298 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18299 pw.println(":"); 18300 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18301 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18302 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18303 } 18304 } 18305 } 18306 } 18307 18308 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18309 boolean printedSomething = false; 18310 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18311 if (packageName != null && !packageName.equals(p.info.packageName)) { 18312 continue; 18313 } 18314 if (!printedSomething) { 18315 if (dumpState.onTitlePrinted()) 18316 pw.println(); 18317 pw.println("Registered ContentProviders:"); 18318 printedSomething = true; 18319 } 18320 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18321 pw.print(" "); pw.println(p.toString()); 18322 } 18323 printedSomething = false; 18324 for (Map.Entry<String, PackageParser.Provider> entry : 18325 mProvidersByAuthority.entrySet()) { 18326 PackageParser.Provider p = entry.getValue(); 18327 if (packageName != null && !packageName.equals(p.info.packageName)) { 18328 continue; 18329 } 18330 if (!printedSomething) { 18331 if (dumpState.onTitlePrinted()) 18332 pw.println(); 18333 pw.println("ContentProvider Authorities:"); 18334 printedSomething = true; 18335 } 18336 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18337 pw.print(" "); pw.println(p.toString()); 18338 if (p.info != null && p.info.applicationInfo != null) { 18339 final String appInfo = p.info.applicationInfo.toString(); 18340 pw.print(" applicationInfo="); pw.println(appInfo); 18341 } 18342 } 18343 } 18344 18345 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18346 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18347 } 18348 18349 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18350 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18351 } 18352 18353 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18354 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18355 } 18356 18357 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18358 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18359 } 18360 18361 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18362 // XXX should handle packageName != null by dumping only install data that 18363 // the given package is involved with. 18364 if (dumpState.onTitlePrinted()) pw.println(); 18365 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18366 } 18367 18368 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18369 // XXX should handle packageName != null by dumping only install data that 18370 // the given package is involved with. 18371 if (dumpState.onTitlePrinted()) pw.println(); 18372 18373 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18374 ipw.println(); 18375 ipw.println("Frozen packages:"); 18376 ipw.increaseIndent(); 18377 if (mFrozenPackages.size() == 0) { 18378 ipw.println("(none)"); 18379 } else { 18380 for (int i = 0; i < mFrozenPackages.size(); i++) { 18381 ipw.println(mFrozenPackages.valueAt(i)); 18382 } 18383 } 18384 ipw.decreaseIndent(); 18385 } 18386 18387 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18388 if (dumpState.onTitlePrinted()) pw.println(); 18389 mSettings.dumpReadMessagesLPr(pw, dumpState); 18390 18391 pw.println(); 18392 pw.println("Package warning messages:"); 18393 BufferedReader in = null; 18394 String line = null; 18395 try { 18396 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18397 while ((line = in.readLine()) != null) { 18398 if (line.contains("ignored: updated version")) continue; 18399 pw.println(line); 18400 } 18401 } catch (IOException ignored) { 18402 } finally { 18403 IoUtils.closeQuietly(in); 18404 } 18405 } 18406 18407 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18408 BufferedReader in = null; 18409 String line = null; 18410 try { 18411 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18412 while ((line = in.readLine()) != null) { 18413 if (line.contains("ignored: updated version")) continue; 18414 pw.print("msg,"); 18415 pw.println(line); 18416 } 18417 } catch (IOException ignored) { 18418 } finally { 18419 IoUtils.closeQuietly(in); 18420 } 18421 } 18422 } 18423 } 18424 18425 private String dumpDomainString(String packageName) { 18426 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18427 .getList(); 18428 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18429 18430 ArraySet<String> result = new ArraySet<>(); 18431 if (iviList.size() > 0) { 18432 for (IntentFilterVerificationInfo ivi : iviList) { 18433 for (String host : ivi.getDomains()) { 18434 result.add(host); 18435 } 18436 } 18437 } 18438 if (filters != null && filters.size() > 0) { 18439 for (IntentFilter filter : filters) { 18440 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18441 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18442 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18443 result.addAll(filter.getHostsList()); 18444 } 18445 } 18446 } 18447 18448 StringBuilder sb = new StringBuilder(result.size() * 16); 18449 for (String domain : result) { 18450 if (sb.length() > 0) sb.append(" "); 18451 sb.append(domain); 18452 } 18453 return sb.toString(); 18454 } 18455 18456 // ------- apps on sdcard specific code ------- 18457 static final boolean DEBUG_SD_INSTALL = false; 18458 18459 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18460 18461 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18462 18463 private boolean mMediaMounted = false; 18464 18465 static String getEncryptKey() { 18466 try { 18467 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18468 SD_ENCRYPTION_KEYSTORE_NAME); 18469 if (sdEncKey == null) { 18470 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18471 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18472 if (sdEncKey == null) { 18473 Slog.e(TAG, "Failed to create encryption keys"); 18474 return null; 18475 } 18476 } 18477 return sdEncKey; 18478 } catch (NoSuchAlgorithmException nsae) { 18479 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18480 return null; 18481 } catch (IOException ioe) { 18482 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18483 return null; 18484 } 18485 } 18486 18487 /* 18488 * Update media status on PackageManager. 18489 */ 18490 @Override 18491 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18492 int callingUid = Binder.getCallingUid(); 18493 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18494 throw new SecurityException("Media status can only be updated by the system"); 18495 } 18496 // reader; this apparently protects mMediaMounted, but should probably 18497 // be a different lock in that case. 18498 synchronized (mPackages) { 18499 Log.i(TAG, "Updating external media status from " 18500 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18501 + (mediaStatus ? "mounted" : "unmounted")); 18502 if (DEBUG_SD_INSTALL) 18503 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18504 + ", mMediaMounted=" + mMediaMounted); 18505 if (mediaStatus == mMediaMounted) { 18506 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18507 : 0, -1); 18508 mHandler.sendMessage(msg); 18509 return; 18510 } 18511 mMediaMounted = mediaStatus; 18512 } 18513 // Queue up an async operation since the package installation may take a 18514 // little while. 18515 mHandler.post(new Runnable() { 18516 public void run() { 18517 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18518 } 18519 }); 18520 } 18521 18522 /** 18523 * Called by MountService when the initial ASECs to scan are available. 18524 * Should block until all the ASEC containers are finished being scanned. 18525 */ 18526 public void scanAvailableAsecs() { 18527 updateExternalMediaStatusInner(true, false, false); 18528 } 18529 18530 /* 18531 * Collect information of applications on external media, map them against 18532 * existing containers and update information based on current mount status. 18533 * Please note that we always have to report status if reportStatus has been 18534 * set to true especially when unloading packages. 18535 */ 18536 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18537 boolean externalStorage) { 18538 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18539 int[] uidArr = EmptyArray.INT; 18540 18541 final String[] list = PackageHelper.getSecureContainerList(); 18542 if (ArrayUtils.isEmpty(list)) { 18543 Log.i(TAG, "No secure containers found"); 18544 } else { 18545 // Process list of secure containers and categorize them 18546 // as active or stale based on their package internal state. 18547 18548 // reader 18549 synchronized (mPackages) { 18550 for (String cid : list) { 18551 // Leave stages untouched for now; installer service owns them 18552 if (PackageInstallerService.isStageName(cid)) continue; 18553 18554 if (DEBUG_SD_INSTALL) 18555 Log.i(TAG, "Processing container " + cid); 18556 String pkgName = getAsecPackageName(cid); 18557 if (pkgName == null) { 18558 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18559 continue; 18560 } 18561 if (DEBUG_SD_INSTALL) 18562 Log.i(TAG, "Looking for pkg : " + pkgName); 18563 18564 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18565 if (ps == null) { 18566 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18567 continue; 18568 } 18569 18570 /* 18571 * Skip packages that are not external if we're unmounting 18572 * external storage. 18573 */ 18574 if (externalStorage && !isMounted && !isExternal(ps)) { 18575 continue; 18576 } 18577 18578 final AsecInstallArgs args = new AsecInstallArgs(cid, 18579 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18580 // The package status is changed only if the code path 18581 // matches between settings and the container id. 18582 if (ps.codePathString != null 18583 && ps.codePathString.startsWith(args.getCodePath())) { 18584 if (DEBUG_SD_INSTALL) { 18585 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18586 + " at code path: " + ps.codePathString); 18587 } 18588 18589 // We do have a valid package installed on sdcard 18590 processCids.put(args, ps.codePathString); 18591 final int uid = ps.appId; 18592 if (uid != -1) { 18593 uidArr = ArrayUtils.appendInt(uidArr, uid); 18594 } 18595 } else { 18596 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18597 + ps.codePathString); 18598 } 18599 } 18600 } 18601 18602 Arrays.sort(uidArr); 18603 } 18604 18605 // Process packages with valid entries. 18606 if (isMounted) { 18607 if (DEBUG_SD_INSTALL) 18608 Log.i(TAG, "Loading packages"); 18609 loadMediaPackages(processCids, uidArr, externalStorage); 18610 startCleaningPackages(); 18611 mInstallerService.onSecureContainersAvailable(); 18612 } else { 18613 if (DEBUG_SD_INSTALL) 18614 Log.i(TAG, "Unloading packages"); 18615 unloadMediaPackages(processCids, uidArr, reportStatus); 18616 } 18617 } 18618 18619 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18620 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18621 final int size = infos.size(); 18622 final String[] packageNames = new String[size]; 18623 final int[] packageUids = new int[size]; 18624 for (int i = 0; i < size; i++) { 18625 final ApplicationInfo info = infos.get(i); 18626 packageNames[i] = info.packageName; 18627 packageUids[i] = info.uid; 18628 } 18629 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18630 finishedReceiver); 18631 } 18632 18633 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18634 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18635 sendResourcesChangedBroadcast(mediaStatus, replacing, 18636 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18637 } 18638 18639 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18640 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18641 int size = pkgList.length; 18642 if (size > 0) { 18643 // Send broadcasts here 18644 Bundle extras = new Bundle(); 18645 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18646 if (uidArr != null) { 18647 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18648 } 18649 if (replacing) { 18650 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18651 } 18652 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18653 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18654 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18655 } 18656 } 18657 18658 /* 18659 * Look at potentially valid container ids from processCids If package 18660 * information doesn't match the one on record or package scanning fails, 18661 * the cid is added to list of removeCids. We currently don't delete stale 18662 * containers. 18663 */ 18664 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18665 boolean externalStorage) { 18666 ArrayList<String> pkgList = new ArrayList<String>(); 18667 Set<AsecInstallArgs> keys = processCids.keySet(); 18668 18669 for (AsecInstallArgs args : keys) { 18670 String codePath = processCids.get(args); 18671 if (DEBUG_SD_INSTALL) 18672 Log.i(TAG, "Loading container : " + args.cid); 18673 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18674 try { 18675 // Make sure there are no container errors first. 18676 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18677 Slog.e(TAG, "Failed to mount cid : " + args.cid 18678 + " when installing from sdcard"); 18679 continue; 18680 } 18681 // Check code path here. 18682 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18683 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18684 + " does not match one in settings " + codePath); 18685 continue; 18686 } 18687 // Parse package 18688 int parseFlags = mDefParseFlags; 18689 if (args.isExternalAsec()) { 18690 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18691 } 18692 if (args.isFwdLocked()) { 18693 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18694 } 18695 18696 synchronized (mInstallLock) { 18697 PackageParser.Package pkg = null; 18698 try { 18699 // Sadly we don't know the package name yet to freeze it 18700 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18701 SCAN_IGNORE_FROZEN, 0, null); 18702 } catch (PackageManagerException e) { 18703 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18704 } 18705 // Scan the package 18706 if (pkg != null) { 18707 /* 18708 * TODO why is the lock being held? doPostInstall is 18709 * called in other places without the lock. This needs 18710 * to be straightened out. 18711 */ 18712 // writer 18713 synchronized (mPackages) { 18714 retCode = PackageManager.INSTALL_SUCCEEDED; 18715 pkgList.add(pkg.packageName); 18716 // Post process args 18717 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18718 pkg.applicationInfo.uid); 18719 } 18720 } else { 18721 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18722 } 18723 } 18724 18725 } finally { 18726 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18727 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18728 } 18729 } 18730 } 18731 // writer 18732 synchronized (mPackages) { 18733 // If the platform SDK has changed since the last time we booted, 18734 // we need to re-grant app permission to catch any new ones that 18735 // appear. This is really a hack, and means that apps can in some 18736 // cases get permissions that the user didn't initially explicitly 18737 // allow... it would be nice to have some better way to handle 18738 // this situation. 18739 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18740 : mSettings.getInternalVersion(); 18741 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18742 : StorageManager.UUID_PRIVATE_INTERNAL; 18743 18744 int updateFlags = UPDATE_PERMISSIONS_ALL; 18745 if (ver.sdkVersion != mSdkVersion) { 18746 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18747 + mSdkVersion + "; regranting permissions for external"); 18748 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18749 } 18750 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18751 18752 // Yay, everything is now upgraded 18753 ver.forceCurrent(); 18754 18755 // can downgrade to reader 18756 // Persist settings 18757 mSettings.writeLPr(); 18758 } 18759 // Send a broadcast to let everyone know we are done processing 18760 if (pkgList.size() > 0) { 18761 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18762 } 18763 } 18764 18765 /* 18766 * Utility method to unload a list of specified containers 18767 */ 18768 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18769 // Just unmount all valid containers. 18770 for (AsecInstallArgs arg : cidArgs) { 18771 synchronized (mInstallLock) { 18772 arg.doPostDeleteLI(false); 18773 } 18774 } 18775 } 18776 18777 /* 18778 * Unload packages mounted on external media. This involves deleting package 18779 * data from internal structures, sending broadcasts about disabled packages, 18780 * gc'ing to free up references, unmounting all secure containers 18781 * corresponding to packages on external media, and posting a 18782 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18783 * that we always have to post this message if status has been requested no 18784 * matter what. 18785 */ 18786 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18787 final boolean reportStatus) { 18788 if (DEBUG_SD_INSTALL) 18789 Log.i(TAG, "unloading media packages"); 18790 ArrayList<String> pkgList = new ArrayList<String>(); 18791 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18792 final Set<AsecInstallArgs> keys = processCids.keySet(); 18793 for (AsecInstallArgs args : keys) { 18794 String pkgName = args.getPackageName(); 18795 if (DEBUG_SD_INSTALL) 18796 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18797 // Delete package internally 18798 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18799 synchronized (mInstallLock) { 18800 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18801 final boolean res; 18802 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18803 "unloadMediaPackages")) { 18804 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18805 null); 18806 } 18807 if (res) { 18808 pkgList.add(pkgName); 18809 } else { 18810 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18811 failedList.add(args); 18812 } 18813 } 18814 } 18815 18816 // reader 18817 synchronized (mPackages) { 18818 // We didn't update the settings after removing each package; 18819 // write them now for all packages. 18820 mSettings.writeLPr(); 18821 } 18822 18823 // We have to absolutely send UPDATED_MEDIA_STATUS only 18824 // after confirming that all the receivers processed the ordered 18825 // broadcast when packages get disabled, force a gc to clean things up. 18826 // and unload all the containers. 18827 if (pkgList.size() > 0) { 18828 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18829 new IIntentReceiver.Stub() { 18830 public void performReceive(Intent intent, int resultCode, String data, 18831 Bundle extras, boolean ordered, boolean sticky, 18832 int sendingUser) throws RemoteException { 18833 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18834 reportStatus ? 1 : 0, 1, keys); 18835 mHandler.sendMessage(msg); 18836 } 18837 }); 18838 } else { 18839 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18840 keys); 18841 mHandler.sendMessage(msg); 18842 } 18843 } 18844 18845 private void loadPrivatePackages(final VolumeInfo vol) { 18846 mHandler.post(new Runnable() { 18847 @Override 18848 public void run() { 18849 loadPrivatePackagesInner(vol); 18850 } 18851 }); 18852 } 18853 18854 private void loadPrivatePackagesInner(VolumeInfo vol) { 18855 final String volumeUuid = vol.fsUuid; 18856 if (TextUtils.isEmpty(volumeUuid)) { 18857 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18858 return; 18859 } 18860 18861 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18862 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18863 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18864 18865 final VersionInfo ver; 18866 final List<PackageSetting> packages; 18867 synchronized (mPackages) { 18868 ver = mSettings.findOrCreateVersion(volumeUuid); 18869 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18870 } 18871 18872 for (PackageSetting ps : packages) { 18873 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18874 synchronized (mInstallLock) { 18875 final PackageParser.Package pkg; 18876 try { 18877 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18878 loaded.add(pkg.applicationInfo); 18879 18880 } catch (PackageManagerException e) { 18881 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18882 } 18883 18884 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18885 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18886 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18887 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18888 } 18889 } 18890 } 18891 18892 // Reconcile app data for all started/unlocked users 18893 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18894 final UserManager um = mContext.getSystemService(UserManager.class); 18895 for (UserInfo user : um.getUsers()) { 18896 final int flags; 18897 if (um.isUserUnlockingOrUnlocked(user.id)) { 18898 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18899 } else if (um.isUserRunning(user.id)) { 18900 flags = StorageManager.FLAG_STORAGE_DE; 18901 } else { 18902 continue; 18903 } 18904 18905 try { 18906 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18907 synchronized (mInstallLock) { 18908 reconcileAppsDataLI(volumeUuid, user.id, flags); 18909 } 18910 } catch (IllegalStateException e) { 18911 // Device was probably ejected, and we'll process that event momentarily 18912 Slog.w(TAG, "Failed to prepare storage: " + e); 18913 } 18914 } 18915 18916 synchronized (mPackages) { 18917 int updateFlags = UPDATE_PERMISSIONS_ALL; 18918 if (ver.sdkVersion != mSdkVersion) { 18919 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18920 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18921 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18922 } 18923 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18924 18925 // Yay, everything is now upgraded 18926 ver.forceCurrent(); 18927 18928 mSettings.writeLPr(); 18929 } 18930 18931 for (PackageFreezer freezer : freezers) { 18932 freezer.close(); 18933 } 18934 18935 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18936 sendResourcesChangedBroadcast(true, false, loaded, null); 18937 } 18938 18939 private void unloadPrivatePackages(final VolumeInfo vol) { 18940 mHandler.post(new Runnable() { 18941 @Override 18942 public void run() { 18943 unloadPrivatePackagesInner(vol); 18944 } 18945 }); 18946 } 18947 18948 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18949 final String volumeUuid = vol.fsUuid; 18950 if (TextUtils.isEmpty(volumeUuid)) { 18951 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18952 return; 18953 } 18954 18955 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18956 synchronized (mInstallLock) { 18957 synchronized (mPackages) { 18958 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18959 for (PackageSetting ps : packages) { 18960 if (ps.pkg == null) continue; 18961 18962 final ApplicationInfo info = ps.pkg.applicationInfo; 18963 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18964 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18965 18966 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18967 "unloadPrivatePackagesInner")) { 18968 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18969 false, null)) { 18970 unloaded.add(info); 18971 } else { 18972 Slog.w(TAG, "Failed to unload " + ps.codePath); 18973 } 18974 } 18975 } 18976 18977 mSettings.writeLPr(); 18978 } 18979 } 18980 18981 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18982 sendResourcesChangedBroadcast(false, false, unloaded, null); 18983 } 18984 18985 /** 18986 * Prepare storage areas for given user on all mounted devices. 18987 */ 18988 void prepareUserData(int userId, int userSerial, int flags) { 18989 synchronized (mInstallLock) { 18990 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18991 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18992 final String volumeUuid = vol.getFsUuid(); 18993 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18994 } 18995 } 18996 } 18997 18998 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18999 boolean allowRecover) { 19000 // Prepare storage and verify that serial numbers are consistent; if 19001 // there's a mismatch we need to destroy to avoid leaking data 19002 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19003 try { 19004 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19005 19006 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19007 UserManagerService.enforceSerialNumber( 19008 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19009 } 19010 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19011 UserManagerService.enforceSerialNumber( 19012 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19013 } 19014 19015 synchronized (mInstallLock) { 19016 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19017 } 19018 } catch (Exception e) { 19019 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19020 + " because we failed to prepare: " + e); 19021 destroyUserDataLI(volumeUuid, userId, 19022 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19023 19024 if (allowRecover) { 19025 // Try one last time; if we fail again we're really in trouble 19026 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19027 } 19028 } 19029 } 19030 19031 /** 19032 * Destroy storage areas for given user on all mounted devices. 19033 */ 19034 void destroyUserData(int userId, int flags) { 19035 synchronized (mInstallLock) { 19036 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19037 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19038 final String volumeUuid = vol.getFsUuid(); 19039 destroyUserDataLI(volumeUuid, userId, flags); 19040 } 19041 } 19042 } 19043 19044 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19045 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19046 try { 19047 // Clean up app data, profile data, and media data 19048 mInstaller.destroyUserData(volumeUuid, userId, flags); 19049 19050 // Clean up system data 19051 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19052 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19053 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19054 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19055 } 19056 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19057 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19058 } 19059 } 19060 19061 // Data with special labels is now gone, so finish the job 19062 storage.destroyUserStorage(volumeUuid, userId, flags); 19063 19064 } catch (Exception e) { 19065 logCriticalInfo(Log.WARN, 19066 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19067 } 19068 } 19069 19070 /** 19071 * Examine all users present on given mounted volume, and destroy data 19072 * belonging to users that are no longer valid, or whose user ID has been 19073 * recycled. 19074 */ 19075 private void reconcileUsers(String volumeUuid) { 19076 final List<File> files = new ArrayList<>(); 19077 Collections.addAll(files, FileUtils 19078 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19079 Collections.addAll(files, FileUtils 19080 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19081 for (File file : files) { 19082 if (!file.isDirectory()) continue; 19083 19084 final int userId; 19085 final UserInfo info; 19086 try { 19087 userId = Integer.parseInt(file.getName()); 19088 info = sUserManager.getUserInfo(userId); 19089 } catch (NumberFormatException e) { 19090 Slog.w(TAG, "Invalid user directory " + file); 19091 continue; 19092 } 19093 19094 boolean destroyUser = false; 19095 if (info == null) { 19096 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19097 + " because no matching user was found"); 19098 destroyUser = true; 19099 } else if (!mOnlyCore) { 19100 try { 19101 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19102 } catch (IOException e) { 19103 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19104 + " because we failed to enforce serial number: " + e); 19105 destroyUser = true; 19106 } 19107 } 19108 19109 if (destroyUser) { 19110 synchronized (mInstallLock) { 19111 destroyUserDataLI(volumeUuid, userId, 19112 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19113 } 19114 } 19115 } 19116 } 19117 19118 private void assertPackageKnown(String volumeUuid, String packageName) 19119 throws PackageManagerException { 19120 synchronized (mPackages) { 19121 final PackageSetting ps = mSettings.mPackages.get(packageName); 19122 if (ps == null) { 19123 throw new PackageManagerException("Package " + packageName + " is unknown"); 19124 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19125 throw new PackageManagerException( 19126 "Package " + packageName + " found on unknown volume " + volumeUuid 19127 + "; expected volume " + ps.volumeUuid); 19128 } 19129 } 19130 } 19131 19132 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19133 throws PackageManagerException { 19134 synchronized (mPackages) { 19135 final PackageSetting ps = mSettings.mPackages.get(packageName); 19136 if (ps == null) { 19137 throw new PackageManagerException("Package " + packageName + " is unknown"); 19138 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19139 throw new PackageManagerException( 19140 "Package " + packageName + " found on unknown volume " + volumeUuid 19141 + "; expected volume " + ps.volumeUuid); 19142 } else if (!ps.getInstalled(userId)) { 19143 throw new PackageManagerException( 19144 "Package " + packageName + " not installed for user " + userId); 19145 } 19146 } 19147 } 19148 19149 /** 19150 * Examine all apps present on given mounted volume, and destroy apps that 19151 * aren't expected, either due to uninstallation or reinstallation on 19152 * another volume. 19153 */ 19154 private void reconcileApps(String volumeUuid) { 19155 final File[] files = FileUtils 19156 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19157 for (File file : files) { 19158 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19159 && !PackageInstallerService.isStageName(file.getName()); 19160 if (!isPackage) { 19161 // Ignore entries which are not packages 19162 continue; 19163 } 19164 19165 try { 19166 final PackageLite pkg = PackageParser.parsePackageLite(file, 19167 PackageParser.PARSE_MUST_BE_APK); 19168 assertPackageKnown(volumeUuid, pkg.packageName); 19169 19170 } catch (PackageParserException | PackageManagerException e) { 19171 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19172 synchronized (mInstallLock) { 19173 removeCodePathLI(file); 19174 } 19175 } 19176 } 19177 } 19178 19179 /** 19180 * Reconcile all app data for the given user. 19181 * <p> 19182 * Verifies that directories exist and that ownership and labeling is 19183 * correct for all installed apps on all mounted volumes. 19184 */ 19185 void reconcileAppsData(int userId, int flags) { 19186 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19187 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19188 final String volumeUuid = vol.getFsUuid(); 19189 synchronized (mInstallLock) { 19190 reconcileAppsDataLI(volumeUuid, userId, flags); 19191 } 19192 } 19193 } 19194 19195 /** 19196 * Reconcile all app data on given mounted volume. 19197 * <p> 19198 * Destroys app data that isn't expected, either due to uninstallation or 19199 * reinstallation on another volume. 19200 * <p> 19201 * Verifies that directories exist and that ownership and labeling is 19202 * correct for all installed apps. 19203 */ 19204 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19205 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19206 + Integer.toHexString(flags)); 19207 19208 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19209 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19210 19211 boolean restoreconNeeded = false; 19212 19213 // First look for stale data that doesn't belong, and check if things 19214 // have changed since we did our last restorecon 19215 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19216 if (StorageManager.isFileEncryptedNativeOrEmulated() 19217 && !StorageManager.isUserKeyUnlocked(userId)) { 19218 throw new RuntimeException( 19219 "Yikes, someone asked us to reconcile CE storage while " + userId 19220 + " was still locked; this would have caused massive data loss!"); 19221 } 19222 19223 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19224 19225 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19226 for (File file : files) { 19227 final String packageName = file.getName(); 19228 try { 19229 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19230 } catch (PackageManagerException e) { 19231 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19232 try { 19233 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19234 StorageManager.FLAG_STORAGE_CE, 0); 19235 } catch (InstallerException e2) { 19236 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19237 } 19238 } 19239 } 19240 } 19241 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19242 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19243 19244 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19245 for (File file : files) { 19246 final String packageName = file.getName(); 19247 try { 19248 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19249 } catch (PackageManagerException e) { 19250 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19251 try { 19252 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19253 StorageManager.FLAG_STORAGE_DE, 0); 19254 } catch (InstallerException e2) { 19255 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19256 } 19257 } 19258 } 19259 } 19260 19261 // Ensure that data directories are ready to roll for all packages 19262 // installed for this volume and user 19263 final List<PackageSetting> packages; 19264 synchronized (mPackages) { 19265 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19266 } 19267 int preparedCount = 0; 19268 for (PackageSetting ps : packages) { 19269 final String packageName = ps.name; 19270 if (ps.pkg == null) { 19271 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19272 // TODO: might be due to legacy ASEC apps; we should circle back 19273 // and reconcile again once they're scanned 19274 continue; 19275 } 19276 19277 if (ps.getInstalled(userId)) { 19278 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19279 19280 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19281 // We may have just shuffled around app data directories, so 19282 // prepare them one more time 19283 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19284 } 19285 19286 preparedCount++; 19287 } 19288 } 19289 19290 if (restoreconNeeded) { 19291 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19292 SELinuxMMAC.setRestoreconDone(ceDir); 19293 } 19294 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19295 SELinuxMMAC.setRestoreconDone(deDir); 19296 } 19297 } 19298 19299 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19300 + " packages; restoreconNeeded was " + restoreconNeeded); 19301 } 19302 19303 /** 19304 * Prepare app data for the given app just after it was installed or 19305 * upgraded. This method carefully only touches users that it's installed 19306 * for, and it forces a restorecon to handle any seinfo changes. 19307 * <p> 19308 * Verifies that directories exist and that ownership and labeling is 19309 * correct for all installed apps. If there is an ownership mismatch, it 19310 * will try recovering system apps by wiping data; third-party app data is 19311 * left intact. 19312 * <p> 19313 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19314 */ 19315 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19316 final PackageSetting ps; 19317 synchronized (mPackages) { 19318 ps = mSettings.mPackages.get(pkg.packageName); 19319 mSettings.writeKernelMappingLPr(ps); 19320 } 19321 19322 final UserManager um = mContext.getSystemService(UserManager.class); 19323 for (UserInfo user : um.getUsers()) { 19324 final int flags; 19325 if (um.isUserUnlockingOrUnlocked(user.id)) { 19326 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19327 } else if (um.isUserRunning(user.id)) { 19328 flags = StorageManager.FLAG_STORAGE_DE; 19329 } else { 19330 continue; 19331 } 19332 19333 if (ps.getInstalled(user.id)) { 19334 // Whenever an app changes, force a restorecon of its data 19335 // TODO: when user data is locked, mark that we're still dirty 19336 prepareAppDataLIF(pkg, user.id, flags, true); 19337 } 19338 } 19339 } 19340 19341 /** 19342 * Prepare app data for the given app. 19343 * <p> 19344 * Verifies that directories exist and that ownership and labeling is 19345 * correct for all installed apps. If there is an ownership mismatch, this 19346 * will try recovering system apps by wiping data; third-party app data is 19347 * left intact. 19348 */ 19349 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19350 boolean restoreconNeeded) { 19351 if (pkg == null) { 19352 Slog.wtf(TAG, "Package was null!", new Throwable()); 19353 return; 19354 } 19355 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19357 for (int i = 0; i < childCount; i++) { 19358 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19359 } 19360 } 19361 19362 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19363 boolean restoreconNeeded) { 19364 if (DEBUG_APP_DATA) { 19365 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19366 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19367 } 19368 19369 final String volumeUuid = pkg.volumeUuid; 19370 final String packageName = pkg.packageName; 19371 final ApplicationInfo app = pkg.applicationInfo; 19372 final int appId = UserHandle.getAppId(app.uid); 19373 19374 Preconditions.checkNotNull(app.seinfo); 19375 19376 try { 19377 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19378 appId, app.seinfo, app.targetSdkVersion); 19379 } catch (InstallerException e) { 19380 if (app.isSystemApp()) { 19381 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19382 + ", but trying to recover: " + e); 19383 destroyAppDataLeafLIF(pkg, userId, flags); 19384 try { 19385 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19386 appId, app.seinfo, app.targetSdkVersion); 19387 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19388 } catch (InstallerException e2) { 19389 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19390 } 19391 } else { 19392 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19393 } 19394 } 19395 19396 if (restoreconNeeded) { 19397 try { 19398 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19399 app.seinfo); 19400 } catch (InstallerException e) { 19401 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19402 } 19403 } 19404 19405 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19406 try { 19407 // CE storage is unlocked right now, so read out the inode and 19408 // remember for use later when it's locked 19409 // TODO: mark this structure as dirty so we persist it! 19410 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19411 StorageManager.FLAG_STORAGE_CE); 19412 synchronized (mPackages) { 19413 final PackageSetting ps = mSettings.mPackages.get(packageName); 19414 if (ps != null) { 19415 ps.setCeDataInode(ceDataInode, userId); 19416 } 19417 } 19418 } catch (InstallerException e) { 19419 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19420 } 19421 } 19422 19423 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19424 } 19425 19426 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19427 if (pkg == null) { 19428 Slog.wtf(TAG, "Package was null!", new Throwable()); 19429 return; 19430 } 19431 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19432 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19433 for (int i = 0; i < childCount; i++) { 19434 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19435 } 19436 } 19437 19438 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19439 final String volumeUuid = pkg.volumeUuid; 19440 final String packageName = pkg.packageName; 19441 final ApplicationInfo app = pkg.applicationInfo; 19442 19443 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19444 // Create a native library symlink only if we have native libraries 19445 // and if the native libraries are 32 bit libraries. We do not provide 19446 // this symlink for 64 bit libraries. 19447 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19448 final String nativeLibPath = app.nativeLibraryDir; 19449 try { 19450 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19451 nativeLibPath, userId); 19452 } catch (InstallerException e) { 19453 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19454 } 19455 } 19456 } 19457 } 19458 19459 /** 19460 * For system apps on non-FBE devices, this method migrates any existing 19461 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19462 * requested by the app. 19463 */ 19464 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19465 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19466 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19467 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19468 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19469 try { 19470 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19471 storageTarget); 19472 } catch (InstallerException e) { 19473 logCriticalInfo(Log.WARN, 19474 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19475 } 19476 return true; 19477 } else { 19478 return false; 19479 } 19480 } 19481 19482 public PackageFreezer freezePackage(String packageName, String killReason) { 19483 return new PackageFreezer(packageName, killReason); 19484 } 19485 19486 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19487 String killReason) { 19488 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19489 return new PackageFreezer(); 19490 } else { 19491 return freezePackage(packageName, killReason); 19492 } 19493 } 19494 19495 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19496 String killReason) { 19497 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19498 return new PackageFreezer(); 19499 } else { 19500 return freezePackage(packageName, killReason); 19501 } 19502 } 19503 19504 /** 19505 * Class that freezes and kills the given package upon creation, and 19506 * unfreezes it upon closing. This is typically used when doing surgery on 19507 * app code/data to prevent the app from running while you're working. 19508 */ 19509 private class PackageFreezer implements AutoCloseable { 19510 private final String mPackageName; 19511 private final PackageFreezer[] mChildren; 19512 19513 private final boolean mWeFroze; 19514 19515 private final AtomicBoolean mClosed = new AtomicBoolean(); 19516 private final CloseGuard mCloseGuard = CloseGuard.get(); 19517 19518 /** 19519 * Create and return a stub freezer that doesn't actually do anything, 19520 * typically used when someone requested 19521 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19522 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19523 */ 19524 public PackageFreezer() { 19525 mPackageName = null; 19526 mChildren = null; 19527 mWeFroze = false; 19528 mCloseGuard.open("close"); 19529 } 19530 19531 public PackageFreezer(String packageName, String killReason) { 19532 synchronized (mPackages) { 19533 mPackageName = packageName; 19534 mWeFroze = mFrozenPackages.add(mPackageName); 19535 19536 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19537 if (ps != null) { 19538 killApplication(ps.name, ps.appId, killReason); 19539 } 19540 19541 final PackageParser.Package p = mPackages.get(packageName); 19542 if (p != null && p.childPackages != null) { 19543 final int N = p.childPackages.size(); 19544 mChildren = new PackageFreezer[N]; 19545 for (int i = 0; i < N; i++) { 19546 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19547 killReason); 19548 } 19549 } else { 19550 mChildren = null; 19551 } 19552 } 19553 mCloseGuard.open("close"); 19554 } 19555 19556 @Override 19557 protected void finalize() throws Throwable { 19558 try { 19559 mCloseGuard.warnIfOpen(); 19560 close(); 19561 } finally { 19562 super.finalize(); 19563 } 19564 } 19565 19566 @Override 19567 public void close() { 19568 mCloseGuard.close(); 19569 if (mClosed.compareAndSet(false, true)) { 19570 synchronized (mPackages) { 19571 if (mWeFroze) { 19572 mFrozenPackages.remove(mPackageName); 19573 } 19574 19575 if (mChildren != null) { 19576 for (PackageFreezer freezer : mChildren) { 19577 freezer.close(); 19578 } 19579 } 19580 } 19581 } 19582 } 19583 } 19584 19585 /** 19586 * Verify that given package is currently frozen. 19587 */ 19588 private void checkPackageFrozen(String packageName) { 19589 synchronized (mPackages) { 19590 if (!mFrozenPackages.contains(packageName)) { 19591 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19592 } 19593 } 19594 } 19595 19596 @Override 19597 public int movePackage(final String packageName, final String volumeUuid) { 19598 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19599 19600 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19601 final int moveId = mNextMoveId.getAndIncrement(); 19602 mHandler.post(new Runnable() { 19603 @Override 19604 public void run() { 19605 try { 19606 movePackageInternal(packageName, volumeUuid, moveId, user); 19607 } catch (PackageManagerException e) { 19608 Slog.w(TAG, "Failed to move " + packageName, e); 19609 mMoveCallbacks.notifyStatusChanged(moveId, 19610 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19611 } 19612 } 19613 }); 19614 return moveId; 19615 } 19616 19617 private void movePackageInternal(final String packageName, final String volumeUuid, 19618 final int moveId, UserHandle user) throws PackageManagerException { 19619 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19620 final PackageManager pm = mContext.getPackageManager(); 19621 19622 final boolean currentAsec; 19623 final String currentVolumeUuid; 19624 final File codeFile; 19625 final String installerPackageName; 19626 final String packageAbiOverride; 19627 final int appId; 19628 final String seinfo; 19629 final String label; 19630 final int targetSdkVersion; 19631 final PackageFreezer freezer; 19632 final int[] installedUserIds; 19633 19634 // reader 19635 synchronized (mPackages) { 19636 final PackageParser.Package pkg = mPackages.get(packageName); 19637 final PackageSetting ps = mSettings.mPackages.get(packageName); 19638 if (pkg == null || ps == null) { 19639 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19640 } 19641 19642 if (pkg.applicationInfo.isSystemApp()) { 19643 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19644 "Cannot move system application"); 19645 } 19646 19647 if (pkg.applicationInfo.isExternalAsec()) { 19648 currentAsec = true; 19649 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19650 } else if (pkg.applicationInfo.isForwardLocked()) { 19651 currentAsec = true; 19652 currentVolumeUuid = "forward_locked"; 19653 } else { 19654 currentAsec = false; 19655 currentVolumeUuid = ps.volumeUuid; 19656 19657 final File probe = new File(pkg.codePath); 19658 final File probeOat = new File(probe, "oat"); 19659 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19660 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19661 "Move only supported for modern cluster style installs"); 19662 } 19663 } 19664 19665 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19666 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19667 "Package already moved to " + volumeUuid); 19668 } 19669 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19670 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19671 "Device admin cannot be moved"); 19672 } 19673 19674 if (mFrozenPackages.contains(packageName)) { 19675 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19676 "Failed to move already frozen package"); 19677 } 19678 19679 codeFile = new File(pkg.codePath); 19680 installerPackageName = ps.installerPackageName; 19681 packageAbiOverride = ps.cpuAbiOverrideString; 19682 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19683 seinfo = pkg.applicationInfo.seinfo; 19684 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19685 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19686 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19687 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19688 } 19689 19690 final Bundle extras = new Bundle(); 19691 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19692 extras.putString(Intent.EXTRA_TITLE, label); 19693 mMoveCallbacks.notifyCreated(moveId, extras); 19694 19695 int installFlags; 19696 final boolean moveCompleteApp; 19697 final File measurePath; 19698 19699 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19700 installFlags = INSTALL_INTERNAL; 19701 moveCompleteApp = !currentAsec; 19702 measurePath = Environment.getDataAppDirectory(volumeUuid); 19703 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19704 installFlags = INSTALL_EXTERNAL; 19705 moveCompleteApp = false; 19706 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19707 } else { 19708 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19709 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19710 || !volume.isMountedWritable()) { 19711 freezer.close(); 19712 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19713 "Move location not mounted private volume"); 19714 } 19715 19716 Preconditions.checkState(!currentAsec); 19717 19718 installFlags = INSTALL_INTERNAL; 19719 moveCompleteApp = true; 19720 measurePath = Environment.getDataAppDirectory(volumeUuid); 19721 } 19722 19723 final PackageStats stats = new PackageStats(null, -1); 19724 synchronized (mInstaller) { 19725 for (int userId : installedUserIds) { 19726 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19727 freezer.close(); 19728 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19729 "Failed to measure package size"); 19730 } 19731 } 19732 } 19733 19734 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19735 + stats.dataSize); 19736 19737 final long startFreeBytes = measurePath.getFreeSpace(); 19738 final long sizeBytes; 19739 if (moveCompleteApp) { 19740 sizeBytes = stats.codeSize + stats.dataSize; 19741 } else { 19742 sizeBytes = stats.codeSize; 19743 } 19744 19745 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19746 freezer.close(); 19747 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19748 "Not enough free space to move"); 19749 } 19750 19751 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19752 19753 final CountDownLatch installedLatch = new CountDownLatch(1); 19754 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19755 @Override 19756 public void onUserActionRequired(Intent intent) throws RemoteException { 19757 throw new IllegalStateException(); 19758 } 19759 19760 @Override 19761 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19762 Bundle extras) throws RemoteException { 19763 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19764 + PackageManager.installStatusToString(returnCode, msg)); 19765 19766 installedLatch.countDown(); 19767 freezer.close(); 19768 19769 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19770 switch (status) { 19771 case PackageInstaller.STATUS_SUCCESS: 19772 mMoveCallbacks.notifyStatusChanged(moveId, 19773 PackageManager.MOVE_SUCCEEDED); 19774 break; 19775 case PackageInstaller.STATUS_FAILURE_STORAGE: 19776 mMoveCallbacks.notifyStatusChanged(moveId, 19777 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19778 break; 19779 default: 19780 mMoveCallbacks.notifyStatusChanged(moveId, 19781 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19782 break; 19783 } 19784 } 19785 }; 19786 19787 final MoveInfo move; 19788 if (moveCompleteApp) { 19789 // Kick off a thread to report progress estimates 19790 new Thread() { 19791 @Override 19792 public void run() { 19793 while (true) { 19794 try { 19795 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19796 break; 19797 } 19798 } catch (InterruptedException ignored) { 19799 } 19800 19801 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19802 final int progress = 10 + (int) MathUtils.constrain( 19803 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19804 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19805 } 19806 } 19807 }.start(); 19808 19809 final String dataAppName = codeFile.getName(); 19810 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19811 dataAppName, appId, seinfo, targetSdkVersion); 19812 } else { 19813 move = null; 19814 } 19815 19816 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19817 19818 final Message msg = mHandler.obtainMessage(INIT_COPY); 19819 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19820 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19821 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19822 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19823 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19824 msg.obj = params; 19825 19826 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19827 System.identityHashCode(msg.obj)); 19828 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19829 System.identityHashCode(msg.obj)); 19830 19831 mHandler.sendMessage(msg); 19832 } 19833 19834 @Override 19835 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19837 19838 final int realMoveId = mNextMoveId.getAndIncrement(); 19839 final Bundle extras = new Bundle(); 19840 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19841 mMoveCallbacks.notifyCreated(realMoveId, extras); 19842 19843 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19844 @Override 19845 public void onCreated(int moveId, Bundle extras) { 19846 // Ignored 19847 } 19848 19849 @Override 19850 public void onStatusChanged(int moveId, int status, long estMillis) { 19851 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19852 } 19853 }; 19854 19855 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19856 storage.setPrimaryStorageUuid(volumeUuid, callback); 19857 return realMoveId; 19858 } 19859 19860 @Override 19861 public int getMoveStatus(int moveId) { 19862 mContext.enforceCallingOrSelfPermission( 19863 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19864 return mMoveCallbacks.mLastStatus.get(moveId); 19865 } 19866 19867 @Override 19868 public void registerMoveCallback(IPackageMoveObserver callback) { 19869 mContext.enforceCallingOrSelfPermission( 19870 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19871 mMoveCallbacks.register(callback); 19872 } 19873 19874 @Override 19875 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19876 mContext.enforceCallingOrSelfPermission( 19877 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19878 mMoveCallbacks.unregister(callback); 19879 } 19880 19881 @Override 19882 public boolean setInstallLocation(int loc) { 19883 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19884 null); 19885 if (getInstallLocation() == loc) { 19886 return true; 19887 } 19888 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19889 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19890 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19891 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19892 return true; 19893 } 19894 return false; 19895 } 19896 19897 @Override 19898 public int getInstallLocation() { 19899 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19900 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19901 PackageHelper.APP_INSTALL_AUTO); 19902 } 19903 19904 /** Called by UserManagerService */ 19905 void cleanUpUser(UserManagerService userManager, int userHandle) { 19906 synchronized (mPackages) { 19907 mDirtyUsers.remove(userHandle); 19908 mUserNeedsBadging.delete(userHandle); 19909 mSettings.removeUserLPw(userHandle); 19910 mPendingBroadcasts.remove(userHandle); 19911 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19912 removeUnusedPackagesLPw(userManager, userHandle); 19913 } 19914 } 19915 19916 /** 19917 * We're removing userHandle and would like to remove any downloaded packages 19918 * that are no longer in use by any other user. 19919 * @param userHandle the user being removed 19920 */ 19921 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19922 final boolean DEBUG_CLEAN_APKS = false; 19923 int [] users = userManager.getUserIds(); 19924 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19925 while (psit.hasNext()) { 19926 PackageSetting ps = psit.next(); 19927 if (ps.pkg == null) { 19928 continue; 19929 } 19930 final String packageName = ps.pkg.packageName; 19931 // Skip over if system app 19932 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19933 continue; 19934 } 19935 if (DEBUG_CLEAN_APKS) { 19936 Slog.i(TAG, "Checking package " + packageName); 19937 } 19938 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19939 if (keep) { 19940 if (DEBUG_CLEAN_APKS) { 19941 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19942 } 19943 } else { 19944 for (int i = 0; i < users.length; i++) { 19945 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19946 keep = true; 19947 if (DEBUG_CLEAN_APKS) { 19948 Slog.i(TAG, " Keeping package " + packageName + " for user " 19949 + users[i]); 19950 } 19951 break; 19952 } 19953 } 19954 } 19955 if (!keep) { 19956 if (DEBUG_CLEAN_APKS) { 19957 Slog.i(TAG, " Removing package " + packageName); 19958 } 19959 mHandler.post(new Runnable() { 19960 public void run() { 19961 deletePackageX(packageName, userHandle, 0); 19962 } //end run 19963 }); 19964 } 19965 } 19966 } 19967 19968 /** Called by UserManagerService */ 19969 void createNewUser(int userHandle) { 19970 synchronized (mInstallLock) { 19971 mSettings.createNewUserLI(this, mInstaller, userHandle); 19972 } 19973 synchronized (mPackages) { 19974 applyFactoryDefaultBrowserLPw(userHandle); 19975 primeDomainVerificationsLPw(userHandle); 19976 } 19977 } 19978 19979 void newUserCreated(final int userHandle) { 19980 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19981 // If permission review for legacy apps is required, we represent 19982 // dagerous permissions for such apps as always granted runtime 19983 // permissions to keep per user flag state whether review is needed. 19984 // Hence, if a new user is added we have to propagate dangerous 19985 // permission grants for these legacy apps. 19986 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19987 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19988 | UPDATE_PERMISSIONS_REPLACE_ALL); 19989 } 19990 } 19991 19992 @Override 19993 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19994 mContext.enforceCallingOrSelfPermission( 19995 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19996 "Only package verification agents can read the verifier device identity"); 19997 19998 synchronized (mPackages) { 19999 return mSettings.getVerifierDeviceIdentityLPw(); 20000 } 20001 } 20002 20003 @Override 20004 public void setPermissionEnforced(String permission, boolean enforced) { 20005 // TODO: Now that we no longer change GID for storage, this should to away. 20006 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20007 "setPermissionEnforced"); 20008 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20009 synchronized (mPackages) { 20010 if (mSettings.mReadExternalStorageEnforced == null 20011 || mSettings.mReadExternalStorageEnforced != enforced) { 20012 mSettings.mReadExternalStorageEnforced = enforced; 20013 mSettings.writeLPr(); 20014 } 20015 } 20016 // kill any non-foreground processes so we restart them and 20017 // grant/revoke the GID. 20018 final IActivityManager am = ActivityManagerNative.getDefault(); 20019 if (am != null) { 20020 final long token = Binder.clearCallingIdentity(); 20021 try { 20022 am.killProcessesBelowForeground("setPermissionEnforcement"); 20023 } catch (RemoteException e) { 20024 } finally { 20025 Binder.restoreCallingIdentity(token); 20026 } 20027 } 20028 } else { 20029 throw new IllegalArgumentException("No selective enforcement for " + permission); 20030 } 20031 } 20032 20033 @Override 20034 @Deprecated 20035 public boolean isPermissionEnforced(String permission) { 20036 return true; 20037 } 20038 20039 @Override 20040 public boolean isStorageLow() { 20041 final long token = Binder.clearCallingIdentity(); 20042 try { 20043 final DeviceStorageMonitorInternal 20044 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20045 if (dsm != null) { 20046 return dsm.isMemoryLow(); 20047 } else { 20048 return false; 20049 } 20050 } finally { 20051 Binder.restoreCallingIdentity(token); 20052 } 20053 } 20054 20055 @Override 20056 public IPackageInstaller getPackageInstaller() { 20057 return mInstallerService; 20058 } 20059 20060 private boolean userNeedsBadging(int userId) { 20061 int index = mUserNeedsBadging.indexOfKey(userId); 20062 if (index < 0) { 20063 final UserInfo userInfo; 20064 final long token = Binder.clearCallingIdentity(); 20065 try { 20066 userInfo = sUserManager.getUserInfo(userId); 20067 } finally { 20068 Binder.restoreCallingIdentity(token); 20069 } 20070 final boolean b; 20071 if (userInfo != null && userInfo.isManagedProfile()) { 20072 b = true; 20073 } else { 20074 b = false; 20075 } 20076 mUserNeedsBadging.put(userId, b); 20077 return b; 20078 } 20079 return mUserNeedsBadging.valueAt(index); 20080 } 20081 20082 @Override 20083 public KeySet getKeySetByAlias(String packageName, String alias) { 20084 if (packageName == null || alias == null) { 20085 return null; 20086 } 20087 synchronized(mPackages) { 20088 final PackageParser.Package pkg = mPackages.get(packageName); 20089 if (pkg == null) { 20090 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20091 throw new IllegalArgumentException("Unknown package: " + packageName); 20092 } 20093 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20094 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20095 } 20096 } 20097 20098 @Override 20099 public KeySet getSigningKeySet(String packageName) { 20100 if (packageName == null) { 20101 return null; 20102 } 20103 synchronized(mPackages) { 20104 final PackageParser.Package pkg = mPackages.get(packageName); 20105 if (pkg == null) { 20106 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20107 throw new IllegalArgumentException("Unknown package: " + packageName); 20108 } 20109 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20110 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20111 throw new SecurityException("May not access signing KeySet of other apps."); 20112 } 20113 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20114 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20115 } 20116 } 20117 20118 @Override 20119 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20120 if (packageName == null || ks == null) { 20121 return false; 20122 } 20123 synchronized(mPackages) { 20124 final PackageParser.Package pkg = mPackages.get(packageName); 20125 if (pkg == null) { 20126 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20127 throw new IllegalArgumentException("Unknown package: " + packageName); 20128 } 20129 IBinder ksh = ks.getToken(); 20130 if (ksh instanceof KeySetHandle) { 20131 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20132 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20133 } 20134 return false; 20135 } 20136 } 20137 20138 @Override 20139 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20140 if (packageName == null || ks == null) { 20141 return false; 20142 } 20143 synchronized(mPackages) { 20144 final PackageParser.Package pkg = mPackages.get(packageName); 20145 if (pkg == null) { 20146 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20147 throw new IllegalArgumentException("Unknown package: " + packageName); 20148 } 20149 IBinder ksh = ks.getToken(); 20150 if (ksh instanceof KeySetHandle) { 20151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20152 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20153 } 20154 return false; 20155 } 20156 } 20157 20158 private void deletePackageIfUnusedLPr(final String packageName) { 20159 PackageSetting ps = mSettings.mPackages.get(packageName); 20160 if (ps == null) { 20161 return; 20162 } 20163 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20164 // TODO Implement atomic delete if package is unused 20165 // It is currently possible that the package will be deleted even if it is installed 20166 // after this method returns. 20167 mHandler.post(new Runnable() { 20168 public void run() { 20169 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20170 } 20171 }); 20172 } 20173 } 20174 20175 /** 20176 * Check and throw if the given before/after packages would be considered a 20177 * downgrade. 20178 */ 20179 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20180 throws PackageManagerException { 20181 if (after.versionCode < before.mVersionCode) { 20182 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20183 "Update version code " + after.versionCode + " is older than current " 20184 + before.mVersionCode); 20185 } else if (after.versionCode == before.mVersionCode) { 20186 if (after.baseRevisionCode < before.baseRevisionCode) { 20187 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20188 "Update base revision code " + after.baseRevisionCode 20189 + " is older than current " + before.baseRevisionCode); 20190 } 20191 20192 if (!ArrayUtils.isEmpty(after.splitNames)) { 20193 for (int i = 0; i < after.splitNames.length; i++) { 20194 final String splitName = after.splitNames[i]; 20195 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20196 if (j != -1) { 20197 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20198 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20199 "Update split " + splitName + " revision code " 20200 + after.splitRevisionCodes[i] + " is older than current " 20201 + before.splitRevisionCodes[j]); 20202 } 20203 } 20204 } 20205 } 20206 } 20207 } 20208 20209 private static class MoveCallbacks extends Handler { 20210 private static final int MSG_CREATED = 1; 20211 private static final int MSG_STATUS_CHANGED = 2; 20212 20213 private final RemoteCallbackList<IPackageMoveObserver> 20214 mCallbacks = new RemoteCallbackList<>(); 20215 20216 private final SparseIntArray mLastStatus = new SparseIntArray(); 20217 20218 public MoveCallbacks(Looper looper) { 20219 super(looper); 20220 } 20221 20222 public void register(IPackageMoveObserver callback) { 20223 mCallbacks.register(callback); 20224 } 20225 20226 public void unregister(IPackageMoveObserver callback) { 20227 mCallbacks.unregister(callback); 20228 } 20229 20230 @Override 20231 public void handleMessage(Message msg) { 20232 final SomeArgs args = (SomeArgs) msg.obj; 20233 final int n = mCallbacks.beginBroadcast(); 20234 for (int i = 0; i < n; i++) { 20235 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20236 try { 20237 invokeCallback(callback, msg.what, args); 20238 } catch (RemoteException ignored) { 20239 } 20240 } 20241 mCallbacks.finishBroadcast(); 20242 args.recycle(); 20243 } 20244 20245 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20246 throws RemoteException { 20247 switch (what) { 20248 case MSG_CREATED: { 20249 callback.onCreated(args.argi1, (Bundle) args.arg2); 20250 break; 20251 } 20252 case MSG_STATUS_CHANGED: { 20253 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20254 break; 20255 } 20256 } 20257 } 20258 20259 private void notifyCreated(int moveId, Bundle extras) { 20260 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20261 20262 final SomeArgs args = SomeArgs.obtain(); 20263 args.argi1 = moveId; 20264 args.arg2 = extras; 20265 obtainMessage(MSG_CREATED, args).sendToTarget(); 20266 } 20267 20268 private void notifyStatusChanged(int moveId, int status) { 20269 notifyStatusChanged(moveId, status, -1); 20270 } 20271 20272 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20273 Slog.v(TAG, "Move " + moveId + " status " + status); 20274 20275 final SomeArgs args = SomeArgs.obtain(); 20276 args.argi1 = moveId; 20277 args.argi2 = status; 20278 args.arg3 = estMillis; 20279 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20280 20281 synchronized (mLastStatus) { 20282 mLastStatus.put(moveId, status); 20283 } 20284 } 20285 } 20286 20287 private final static class OnPermissionChangeListeners extends Handler { 20288 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20289 20290 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20291 new RemoteCallbackList<>(); 20292 20293 public OnPermissionChangeListeners(Looper looper) { 20294 super(looper); 20295 } 20296 20297 @Override 20298 public void handleMessage(Message msg) { 20299 switch (msg.what) { 20300 case MSG_ON_PERMISSIONS_CHANGED: { 20301 final int uid = msg.arg1; 20302 handleOnPermissionsChanged(uid); 20303 } break; 20304 } 20305 } 20306 20307 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20308 mPermissionListeners.register(listener); 20309 20310 } 20311 20312 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20313 mPermissionListeners.unregister(listener); 20314 } 20315 20316 public void onPermissionsChanged(int uid) { 20317 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20318 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20319 } 20320 } 20321 20322 private void handleOnPermissionsChanged(int uid) { 20323 final int count = mPermissionListeners.beginBroadcast(); 20324 try { 20325 for (int i = 0; i < count; i++) { 20326 IOnPermissionsChangeListener callback = mPermissionListeners 20327 .getBroadcastItem(i); 20328 try { 20329 callback.onPermissionsChanged(uid); 20330 } catch (RemoteException e) { 20331 Log.e(TAG, "Permission listener is dead", e); 20332 } 20333 } 20334 } finally { 20335 mPermissionListeners.finishBroadcast(); 20336 } 20337 } 20338 } 20339 20340 private class PackageManagerInternalImpl extends PackageManagerInternal { 20341 @Override 20342 public void setLocationPackagesProvider(PackagesProvider provider) { 20343 synchronized (mPackages) { 20344 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20345 } 20346 } 20347 20348 @Override 20349 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20350 synchronized (mPackages) { 20351 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20352 } 20353 } 20354 20355 @Override 20356 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20357 synchronized (mPackages) { 20358 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20359 } 20360 } 20361 20362 @Override 20363 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20364 synchronized (mPackages) { 20365 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20366 } 20367 } 20368 20369 @Override 20370 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20371 synchronized (mPackages) { 20372 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20373 } 20374 } 20375 20376 @Override 20377 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20378 synchronized (mPackages) { 20379 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20380 } 20381 } 20382 20383 @Override 20384 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20385 synchronized (mPackages) { 20386 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20387 packageName, userId); 20388 } 20389 } 20390 20391 @Override 20392 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20393 synchronized (mPackages) { 20394 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20395 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20396 packageName, userId); 20397 } 20398 } 20399 20400 @Override 20401 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20402 synchronized (mPackages) { 20403 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20404 packageName, userId); 20405 } 20406 } 20407 20408 @Override 20409 public void setKeepUninstalledPackages(final List<String> packageList) { 20410 Preconditions.checkNotNull(packageList); 20411 List<String> removedFromList = null; 20412 synchronized (mPackages) { 20413 if (mKeepUninstalledPackages != null) { 20414 final int packagesCount = mKeepUninstalledPackages.size(); 20415 for (int i = 0; i < packagesCount; i++) { 20416 String oldPackage = mKeepUninstalledPackages.get(i); 20417 if (packageList != null && packageList.contains(oldPackage)) { 20418 continue; 20419 } 20420 if (removedFromList == null) { 20421 removedFromList = new ArrayList<>(); 20422 } 20423 removedFromList.add(oldPackage); 20424 } 20425 } 20426 mKeepUninstalledPackages = new ArrayList<>(packageList); 20427 if (removedFromList != null) { 20428 final int removedCount = removedFromList.size(); 20429 for (int i = 0; i < removedCount; i++) { 20430 deletePackageIfUnusedLPr(removedFromList.get(i)); 20431 } 20432 } 20433 } 20434 } 20435 20436 @Override 20437 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20438 synchronized (mPackages) { 20439 // If we do not support permission review, done. 20440 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20441 return false; 20442 } 20443 20444 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20445 if (packageSetting == null) { 20446 return false; 20447 } 20448 20449 // Permission review applies only to apps not supporting the new permission model. 20450 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20451 return false; 20452 } 20453 20454 // Legacy apps have the permission and get user consent on launch. 20455 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20456 return permissionsState.isPermissionReviewRequired(userId); 20457 } 20458 } 20459 20460 @Override 20461 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20462 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20463 } 20464 20465 @Override 20466 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20467 int userId) { 20468 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20469 } 20470 } 20471 20472 @Override 20473 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20474 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20475 synchronized (mPackages) { 20476 final long identity = Binder.clearCallingIdentity(); 20477 try { 20478 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20479 packageNames, userId); 20480 } finally { 20481 Binder.restoreCallingIdentity(identity); 20482 } 20483 } 20484 } 20485 20486 private static void enforceSystemOrPhoneCaller(String tag) { 20487 int callingUid = Binder.getCallingUid(); 20488 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20489 throw new SecurityException( 20490 "Cannot call " + tag + " from UID " + callingUid); 20491 } 20492 } 20493 20494 boolean isHistoricalPackageUsageAvailable() { 20495 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20496 } 20497 20498 /** 20499 * Return a <b>copy</b> of the collection of packages known to the package manager. 20500 * @return A copy of the values of mPackages. 20501 */ 20502 Collection<PackageParser.Package> getPackages() { 20503 synchronized (mPackages) { 20504 return new ArrayList<>(mPackages.values()); 20505 } 20506 } 20507 20508 /** 20509 * Logs process start information (including base APK hash) to the security log. 20510 * @hide 20511 */ 20512 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20513 String apkFile, int pid) { 20514 if (!SecurityLog.isLoggingEnabled()) { 20515 return; 20516 } 20517 Bundle data = new Bundle(); 20518 data.putLong("startTimestamp", System.currentTimeMillis()); 20519 data.putString("processName", processName); 20520 data.putInt("uid", uid); 20521 data.putString("seinfo", seinfo); 20522 data.putString("apkFile", apkFile); 20523 data.putInt("pid", pid); 20524 Message msg = mProcessLoggingHandler.obtainMessage( 20525 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20526 msg.setData(data); 20527 mProcessLoggingHandler.sendMessage(msg); 20528 } 20529} 20530