PackageManagerService.java revision 380f3b12a4725a0534d62ada7c6f3bd67ebd0d01
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.ResourcesManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 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.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 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 static final int WRITE_PACKAGE_LIST = 19; 1048 1049 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1050 1051 // Delay time in millisecs 1052 static final int BROADCAST_DELAY = 10 * 1000; 1053 1054 static UserManagerService sUserManager; 1055 1056 // Stores a list of users whose package restrictions file needs to be updated 1057 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1058 1059 final private DefaultContainerConnection mDefContainerConn = 1060 new DefaultContainerConnection(); 1061 class DefaultContainerConnection implements ServiceConnection { 1062 public void onServiceConnected(ComponentName name, IBinder service) { 1063 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1064 IMediaContainerService imcs = 1065 IMediaContainerService.Stub.asInterface(service); 1066 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1067 } 1068 1069 public void onServiceDisconnected(ComponentName name) { 1070 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1071 } 1072 } 1073 1074 // Recordkeeping of restore-after-install operations that are currently in flight 1075 // between the Package Manager and the Backup Manager 1076 static class PostInstallData { 1077 public InstallArgs args; 1078 public PackageInstalledInfo res; 1079 1080 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1081 args = _a; 1082 res = _r; 1083 } 1084 } 1085 1086 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1087 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1088 1089 // XML tags for backup/restore of various bits of state 1090 private static final String TAG_PREFERRED_BACKUP = "pa"; 1091 private static final String TAG_DEFAULT_APPS = "da"; 1092 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1093 1094 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1095 private static final String TAG_ALL_GRANTS = "rt-grants"; 1096 private static final String TAG_GRANT = "grant"; 1097 private static final String ATTR_PACKAGE_NAME = "pkg"; 1098 1099 private static final String TAG_PERMISSION = "perm"; 1100 private static final String ATTR_PERMISSION_NAME = "name"; 1101 private static final String ATTR_IS_GRANTED = "g"; 1102 private static final String ATTR_USER_SET = "set"; 1103 private static final String ATTR_USER_FIXED = "fixed"; 1104 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1105 1106 // System/policy permission grants are not backed up 1107 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1108 FLAG_PERMISSION_POLICY_FIXED 1109 | FLAG_PERMISSION_SYSTEM_FIXED 1110 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1111 1112 // And we back up these user-adjusted states 1113 private static final int USER_RUNTIME_GRANT_MASK = 1114 FLAG_PERMISSION_USER_SET 1115 | FLAG_PERMISSION_USER_FIXED 1116 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1117 1118 final @Nullable String mRequiredVerifierPackage; 1119 final @NonNull String mRequiredInstallerPackage; 1120 final @Nullable String mSetupWizardPackage; 1121 final @NonNull String mServicesSystemSharedLibraryPackageName; 1122 final @NonNull String mSharedSystemSharedLibraryPackageName; 1123 1124 private final PackageUsage mPackageUsage = new PackageUsage(); 1125 1126 private class PackageUsage { 1127 private static final int WRITE_INTERVAL 1128 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1129 1130 private final Object mFileLock = new Object(); 1131 private final AtomicLong mLastWritten = new AtomicLong(0); 1132 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1133 1134 private boolean mIsHistoricalPackageUsageAvailable = true; 1135 1136 boolean isHistoricalPackageUsageAvailable() { 1137 return mIsHistoricalPackageUsageAvailable; 1138 } 1139 1140 void write(boolean force) { 1141 if (force) { 1142 writeInternal(); 1143 return; 1144 } 1145 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1146 && !DEBUG_DEXOPT) { 1147 return; 1148 } 1149 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1150 new Thread("PackageUsage_DiskWriter") { 1151 @Override 1152 public void run() { 1153 try { 1154 writeInternal(); 1155 } finally { 1156 mBackgroundWriteRunning.set(false); 1157 } 1158 } 1159 }.start(); 1160 } 1161 } 1162 1163 private void writeInternal() { 1164 synchronized (mPackages) { 1165 synchronized (mFileLock) { 1166 AtomicFile file = getFile(); 1167 FileOutputStream f = null; 1168 try { 1169 f = file.startWrite(); 1170 BufferedOutputStream out = new BufferedOutputStream(f); 1171 FileUtils.setPermissions(file.getBaseFile().getPath(), 1172 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1173 StringBuilder sb = new StringBuilder(); 1174 1175 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1176 sb.append('\n'); 1177 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1178 1179 for (PackageParser.Package pkg : mPackages.values()) { 1180 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1181 continue; 1182 } 1183 sb.setLength(0); 1184 sb.append(pkg.packageName); 1185 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1186 sb.append(' '); 1187 sb.append(usageTimeInMillis); 1188 } 1189 sb.append('\n'); 1190 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1191 } 1192 out.flush(); 1193 file.finishWrite(f); 1194 } catch (IOException e) { 1195 if (f != null) { 1196 file.failWrite(f); 1197 } 1198 Log.e(TAG, "Failed to write package usage times", e); 1199 } 1200 } 1201 } 1202 mLastWritten.set(SystemClock.elapsedRealtime()); 1203 } 1204 1205 void readLP() { 1206 synchronized (mFileLock) { 1207 AtomicFile file = getFile(); 1208 BufferedInputStream in = null; 1209 try { 1210 in = new BufferedInputStream(file.openRead()); 1211 StringBuffer sb = new StringBuffer(); 1212 1213 String firstLine = readLine(in, sb); 1214 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1215 readVersion1LP(in, sb); 1216 } else { 1217 readVersion0LP(in, sb, firstLine); 1218 } 1219 } catch (FileNotFoundException expected) { 1220 mIsHistoricalPackageUsageAvailable = false; 1221 } catch (IOException e) { 1222 Log.w(TAG, "Failed to read package usage times", e); 1223 } finally { 1224 IoUtils.closeQuietly(in); 1225 } 1226 } 1227 mLastWritten.set(SystemClock.elapsedRealtime()); 1228 } 1229 1230 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1231 throws IOException { 1232 // Initial version of the file had no version number and stored one 1233 // package-timestamp pair per line. 1234 // Note that the first line has already been read from the InputStream. 1235 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1236 String[] tokens = line.split(" "); 1237 if (tokens.length != 2) { 1238 throw new IOException("Failed to parse " + line + 1239 " as package-timestamp pair."); 1240 } 1241 1242 String packageName = tokens[0]; 1243 PackageParser.Package pkg = mPackages.get(packageName); 1244 if (pkg == null) { 1245 continue; 1246 } 1247 1248 long timestamp = parseAsLong(tokens[1]); 1249 for (int reason = 0; 1250 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1251 reason++) { 1252 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1253 } 1254 } 1255 } 1256 1257 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1258 // Version 1 of the file started with the corresponding version 1259 // number and then stored a package name and eight timestamps per line. 1260 String line; 1261 while ((line = readLine(in, sb)) != null) { 1262 String[] tokens = line.split(" "); 1263 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1264 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1265 } 1266 1267 String packageName = tokens[0]; 1268 PackageParser.Package pkg = mPackages.get(packageName); 1269 if (pkg == null) { 1270 continue; 1271 } 1272 1273 for (int reason = 0; 1274 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1275 reason++) { 1276 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1277 } 1278 } 1279 } 1280 1281 private long parseAsLong(String token) throws IOException { 1282 try { 1283 return Long.parseLong(token); 1284 } catch (NumberFormatException e) { 1285 throw new IOException("Failed to parse " + token + " as a long.", e); 1286 } 1287 } 1288 1289 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1290 return readToken(in, sb, '\n'); 1291 } 1292 1293 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1294 throws IOException { 1295 sb.setLength(0); 1296 while (true) { 1297 int ch = in.read(); 1298 if (ch == -1) { 1299 if (sb.length() == 0) { 1300 return null; 1301 } 1302 throw new IOException("Unexpected EOF"); 1303 } 1304 if (ch == endOfToken) { 1305 return sb.toString(); 1306 } 1307 sb.append((char)ch); 1308 } 1309 } 1310 1311 private AtomicFile getFile() { 1312 File dataDir = Environment.getDataDirectory(); 1313 File systemDir = new File(dataDir, "system"); 1314 File fname = new File(systemDir, "package-usage.list"); 1315 return new AtomicFile(fname); 1316 } 1317 1318 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1319 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1320 } 1321 1322 class PackageHandler extends Handler { 1323 private boolean mBound = false; 1324 final ArrayList<HandlerParams> mPendingInstalls = 1325 new ArrayList<HandlerParams>(); 1326 1327 private boolean connectToService() { 1328 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1329 " DefaultContainerService"); 1330 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1331 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1332 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1333 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1334 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1335 mBound = true; 1336 return true; 1337 } 1338 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1339 return false; 1340 } 1341 1342 private void disconnectService() { 1343 mContainerService = null; 1344 mBound = false; 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1346 mContext.unbindService(mDefContainerConn); 1347 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1348 } 1349 1350 PackageHandler(Looper looper) { 1351 super(looper); 1352 } 1353 1354 public void handleMessage(Message msg) { 1355 try { 1356 doHandleMessage(msg); 1357 } finally { 1358 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1359 } 1360 } 1361 1362 void doHandleMessage(Message msg) { 1363 switch (msg.what) { 1364 case INIT_COPY: { 1365 HandlerParams params = (HandlerParams) msg.obj; 1366 int idx = mPendingInstalls.size(); 1367 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1368 // If a bind was already initiated we dont really 1369 // need to do anything. The pending install 1370 // will be processed later on. 1371 if (!mBound) { 1372 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1373 System.identityHashCode(mHandler)); 1374 // If this is the only one pending we might 1375 // have to bind to the service again. 1376 if (!connectToService()) { 1377 Slog.e(TAG, "Failed to bind to media container service"); 1378 params.serviceError(); 1379 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1380 System.identityHashCode(mHandler)); 1381 if (params.traceMethod != null) { 1382 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1383 params.traceCookie); 1384 } 1385 return; 1386 } else { 1387 // Once we bind to the service, the first 1388 // pending request will be processed. 1389 mPendingInstalls.add(idx, params); 1390 } 1391 } else { 1392 mPendingInstalls.add(idx, params); 1393 // Already bound to the service. Just make 1394 // sure we trigger off processing the first request. 1395 if (idx == 0) { 1396 mHandler.sendEmptyMessage(MCS_BOUND); 1397 } 1398 } 1399 break; 1400 } 1401 case MCS_BOUND: { 1402 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1403 if (msg.obj != null) { 1404 mContainerService = (IMediaContainerService) msg.obj; 1405 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1406 System.identityHashCode(mHandler)); 1407 } 1408 if (mContainerService == null) { 1409 if (!mBound) { 1410 // Something seriously wrong since we are not bound and we are not 1411 // waiting for connection. Bail out. 1412 Slog.e(TAG, "Cannot bind to media container service"); 1413 for (HandlerParams params : mPendingInstalls) { 1414 // Indicate service bind error 1415 params.serviceError(); 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1417 System.identityHashCode(params)); 1418 if (params.traceMethod != null) { 1419 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1420 params.traceMethod, params.traceCookie); 1421 } 1422 return; 1423 } 1424 mPendingInstalls.clear(); 1425 } else { 1426 Slog.w(TAG, "Waiting to connect to media container service"); 1427 } 1428 } else if (mPendingInstalls.size() > 0) { 1429 HandlerParams params = mPendingInstalls.get(0); 1430 if (params != null) { 1431 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1432 System.identityHashCode(params)); 1433 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1434 if (params.startCopy()) { 1435 // We are done... look for more work or to 1436 // go idle. 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, 1438 "Checking for more work or unbind..."); 1439 // Delete pending install 1440 if (mPendingInstalls.size() > 0) { 1441 mPendingInstalls.remove(0); 1442 } 1443 if (mPendingInstalls.size() == 0) { 1444 if (mBound) { 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, 1446 "Posting delayed MCS_UNBIND"); 1447 removeMessages(MCS_UNBIND); 1448 Message ubmsg = obtainMessage(MCS_UNBIND); 1449 // Unbind after a little delay, to avoid 1450 // continual thrashing. 1451 sendMessageDelayed(ubmsg, 10000); 1452 } 1453 } else { 1454 // There are more pending requests in queue. 1455 // Just post MCS_BOUND message to trigger processing 1456 // of next pending install. 1457 if (DEBUG_SD_INSTALL) Log.i(TAG, 1458 "Posting MCS_BOUND for next work"); 1459 mHandler.sendEmptyMessage(MCS_BOUND); 1460 } 1461 } 1462 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1463 } 1464 } else { 1465 // Should never happen ideally. 1466 Slog.w(TAG, "Empty queue"); 1467 } 1468 break; 1469 } 1470 case MCS_RECONNECT: { 1471 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1472 if (mPendingInstalls.size() > 0) { 1473 if (mBound) { 1474 disconnectService(); 1475 } 1476 if (!connectToService()) { 1477 Slog.e(TAG, "Failed to bind to media container service"); 1478 for (HandlerParams params : mPendingInstalls) { 1479 // Indicate service bind error 1480 params.serviceError(); 1481 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1482 System.identityHashCode(params)); 1483 } 1484 mPendingInstalls.clear(); 1485 } 1486 } 1487 break; 1488 } 1489 case MCS_UNBIND: { 1490 // If there is no actual work left, then time to unbind. 1491 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1492 1493 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1494 if (mBound) { 1495 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1496 1497 disconnectService(); 1498 } 1499 } else if (mPendingInstalls.size() > 0) { 1500 // There are more pending requests in queue. 1501 // Just post MCS_BOUND message to trigger processing 1502 // of next pending install. 1503 mHandler.sendEmptyMessage(MCS_BOUND); 1504 } 1505 1506 break; 1507 } 1508 case MCS_GIVE_UP: { 1509 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1510 HandlerParams params = mPendingInstalls.remove(0); 1511 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1512 System.identityHashCode(params)); 1513 break; 1514 } 1515 case SEND_PENDING_BROADCAST: { 1516 String packages[]; 1517 ArrayList<String> components[]; 1518 int size = 0; 1519 int uids[]; 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1521 synchronized (mPackages) { 1522 if (mPendingBroadcasts == null) { 1523 return; 1524 } 1525 size = mPendingBroadcasts.size(); 1526 if (size <= 0) { 1527 // Nothing to be done. Just return 1528 return; 1529 } 1530 packages = new String[size]; 1531 components = new ArrayList[size]; 1532 uids = new int[size]; 1533 int i = 0; // filling out the above arrays 1534 1535 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1536 int packageUserId = mPendingBroadcasts.userIdAt(n); 1537 Iterator<Map.Entry<String, ArrayList<String>>> it 1538 = mPendingBroadcasts.packagesForUserId(packageUserId) 1539 .entrySet().iterator(); 1540 while (it.hasNext() && i < size) { 1541 Map.Entry<String, ArrayList<String>> ent = it.next(); 1542 packages[i] = ent.getKey(); 1543 components[i] = ent.getValue(); 1544 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1545 uids[i] = (ps != null) 1546 ? UserHandle.getUid(packageUserId, ps.appId) 1547 : -1; 1548 i++; 1549 } 1550 } 1551 size = i; 1552 mPendingBroadcasts.clear(); 1553 } 1554 // Send broadcasts 1555 for (int i = 0; i < size; i++) { 1556 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1557 } 1558 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1559 break; 1560 } 1561 case START_CLEANING_PACKAGE: { 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1563 final String packageName = (String)msg.obj; 1564 final int userId = msg.arg1; 1565 final boolean andCode = msg.arg2 != 0; 1566 synchronized (mPackages) { 1567 if (userId == UserHandle.USER_ALL) { 1568 int[] users = sUserManager.getUserIds(); 1569 for (int user : users) { 1570 mSettings.addPackageToCleanLPw( 1571 new PackageCleanItem(user, packageName, andCode)); 1572 } 1573 } else { 1574 mSettings.addPackageToCleanLPw( 1575 new PackageCleanItem(userId, packageName, andCode)); 1576 } 1577 } 1578 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1579 startCleaningPackages(); 1580 } break; 1581 case POST_INSTALL: { 1582 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1583 1584 PostInstallData data = mRunningInstalls.get(msg.arg1); 1585 final boolean didRestore = (msg.arg2 != 0); 1586 mRunningInstalls.delete(msg.arg1); 1587 1588 if (data != null) { 1589 InstallArgs args = data.args; 1590 PackageInstalledInfo parentRes = data.res; 1591 1592 final boolean grantPermissions = (args.installFlags 1593 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1594 final boolean killApp = (args.installFlags 1595 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1596 final String[] grantedPermissions = args.installGrantPermissions; 1597 1598 // Handle the parent package 1599 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1600 grantedPermissions, didRestore, args.installerPackageName, 1601 args.observer); 1602 1603 // Handle the child packages 1604 final int childCount = (parentRes.addedChildPackages != null) 1605 ? parentRes.addedChildPackages.size() : 0; 1606 for (int i = 0; i < childCount; i++) { 1607 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1608 handlePackagePostInstall(childRes, grantPermissions, killApp, 1609 grantedPermissions, false, args.installerPackageName, 1610 args.observer); 1611 } 1612 1613 // Log tracing if needed 1614 if (args.traceMethod != null) { 1615 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1616 args.traceCookie); 1617 } 1618 } else { 1619 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1620 } 1621 1622 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1623 } break; 1624 case UPDATED_MEDIA_STATUS: { 1625 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1626 boolean reportStatus = msg.arg1 == 1; 1627 boolean doGc = msg.arg2 == 1; 1628 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1629 if (doGc) { 1630 // Force a gc to clear up stale containers. 1631 Runtime.getRuntime().gc(); 1632 } 1633 if (msg.obj != null) { 1634 @SuppressWarnings("unchecked") 1635 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1637 // Unload containers 1638 unloadAllContainers(args); 1639 } 1640 if (reportStatus) { 1641 try { 1642 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1643 PackageHelper.getMountService().finishMediaUpdate(); 1644 } catch (RemoteException e) { 1645 Log.e(TAG, "MountService not running?"); 1646 } 1647 } 1648 } break; 1649 case WRITE_SETTINGS: { 1650 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1651 synchronized (mPackages) { 1652 removeMessages(WRITE_SETTINGS); 1653 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1654 mSettings.writeLPr(); 1655 mDirtyUsers.clear(); 1656 } 1657 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1658 } break; 1659 case WRITE_PACKAGE_RESTRICTIONS: { 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1661 synchronized (mPackages) { 1662 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1663 for (int userId : mDirtyUsers) { 1664 mSettings.writePackageRestrictionsLPr(userId); 1665 } 1666 mDirtyUsers.clear(); 1667 } 1668 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1669 } break; 1670 case WRITE_PACKAGE_LIST: { 1671 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1672 synchronized (mPackages) { 1673 removeMessages(WRITE_PACKAGE_LIST); 1674 mSettings.writePackageListLPr(msg.arg1); 1675 } 1676 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1677 } break; 1678 case CHECK_PENDING_VERIFICATION: { 1679 final int verificationId = msg.arg1; 1680 final PackageVerificationState state = mPendingVerification.get(verificationId); 1681 1682 if ((state != null) && !state.timeoutExtended()) { 1683 final InstallArgs args = state.getInstallArgs(); 1684 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1685 1686 Slog.i(TAG, "Verification timed out for " + originUri); 1687 mPendingVerification.remove(verificationId); 1688 1689 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1690 1691 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1692 Slog.i(TAG, "Continuing with installation of " + originUri); 1693 state.setVerifierResponse(Binder.getCallingUid(), 1694 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1695 broadcastPackageVerified(verificationId, originUri, 1696 PackageManager.VERIFICATION_ALLOW, 1697 state.getInstallArgs().getUser()); 1698 try { 1699 ret = args.copyApk(mContainerService, true); 1700 } catch (RemoteException e) { 1701 Slog.e(TAG, "Could not contact the ContainerService"); 1702 } 1703 } else { 1704 broadcastPackageVerified(verificationId, originUri, 1705 PackageManager.VERIFICATION_REJECT, 1706 state.getInstallArgs().getUser()); 1707 } 1708 1709 Trace.asyncTraceEnd( 1710 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1711 1712 processPendingInstall(args, ret); 1713 mHandler.sendEmptyMessage(MCS_UNBIND); 1714 } 1715 break; 1716 } 1717 case PACKAGE_VERIFIED: { 1718 final int verificationId = msg.arg1; 1719 1720 final PackageVerificationState state = mPendingVerification.get(verificationId); 1721 if (state == null) { 1722 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1723 break; 1724 } 1725 1726 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1727 1728 state.setVerifierResponse(response.callerUid, response.code); 1729 1730 if (state.isVerificationComplete()) { 1731 mPendingVerification.remove(verificationId); 1732 1733 final InstallArgs args = state.getInstallArgs(); 1734 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1735 1736 int ret; 1737 if (state.isInstallAllowed()) { 1738 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1739 broadcastPackageVerified(verificationId, originUri, 1740 response.code, state.getInstallArgs().getUser()); 1741 try { 1742 ret = args.copyApk(mContainerService, true); 1743 } catch (RemoteException e) { 1744 Slog.e(TAG, "Could not contact the ContainerService"); 1745 } 1746 } else { 1747 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1748 } 1749 1750 Trace.asyncTraceEnd( 1751 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1752 1753 processPendingInstall(args, ret); 1754 mHandler.sendEmptyMessage(MCS_UNBIND); 1755 } 1756 1757 break; 1758 } 1759 case START_INTENT_FILTER_VERIFICATIONS: { 1760 IFVerificationParams params = (IFVerificationParams) msg.obj; 1761 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1762 params.replacing, params.pkg); 1763 break; 1764 } 1765 case INTENT_FILTER_VERIFIED: { 1766 final int verificationId = msg.arg1; 1767 1768 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1769 verificationId); 1770 if (state == null) { 1771 Slog.w(TAG, "Invalid IntentFilter verification token " 1772 + verificationId + " received"); 1773 break; 1774 } 1775 1776 final int userId = state.getUserId(); 1777 1778 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1779 "Processing IntentFilter verification with token:" 1780 + verificationId + " and userId:" + userId); 1781 1782 final IntentFilterVerificationResponse response = 1783 (IntentFilterVerificationResponse) msg.obj; 1784 1785 state.setVerifierResponse(response.callerUid, response.code); 1786 1787 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1788 "IntentFilter verification with token:" + verificationId 1789 + " and userId:" + userId 1790 + " is settings verifier response with response code:" 1791 + response.code); 1792 1793 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1794 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1795 + response.getFailedDomainsString()); 1796 } 1797 1798 if (state.isVerificationComplete()) { 1799 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1800 } else { 1801 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1802 "IntentFilter verification with token:" + verificationId 1803 + " was not said to be complete"); 1804 } 1805 1806 break; 1807 } 1808 } 1809 } 1810 } 1811 1812 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1813 boolean killApp, String[] grantedPermissions, 1814 boolean launchedForRestore, String installerPackage, 1815 IPackageInstallObserver2 installObserver) { 1816 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1817 // Send the removed broadcasts 1818 if (res.removedInfo != null) { 1819 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1820 } 1821 1822 // Now that we successfully installed the package, grant runtime 1823 // permissions if requested before broadcasting the install. 1824 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1825 >= Build.VERSION_CODES.M) { 1826 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1827 } 1828 1829 final boolean update = res.removedInfo != null 1830 && res.removedInfo.removedPackage != null; 1831 1832 // If this is the first time we have child packages for a disabled privileged 1833 // app that had no children, we grant requested runtime permissions to the new 1834 // children if the parent on the system image had them already granted. 1835 if (res.pkg.parentPackage != null) { 1836 synchronized (mPackages) { 1837 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1838 } 1839 } 1840 1841 synchronized (mPackages) { 1842 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1843 } 1844 1845 final String packageName = res.pkg.applicationInfo.packageName; 1846 Bundle extras = new Bundle(1); 1847 extras.putInt(Intent.EXTRA_UID, res.uid); 1848 1849 // Determine the set of users who are adding this package for 1850 // the first time vs. those who are seeing an update. 1851 int[] firstUsers = EMPTY_INT_ARRAY; 1852 int[] updateUsers = EMPTY_INT_ARRAY; 1853 if (res.origUsers == null || res.origUsers.length == 0) { 1854 firstUsers = res.newUsers; 1855 } else { 1856 for (int newUser : res.newUsers) { 1857 boolean isNew = true; 1858 for (int origUser : res.origUsers) { 1859 if (origUser == newUser) { 1860 isNew = false; 1861 break; 1862 } 1863 } 1864 if (isNew) { 1865 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1866 } else { 1867 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1868 } 1869 } 1870 } 1871 1872 // Send installed broadcasts if the install/update is not ephemeral 1873 if (!isEphemeral(res.pkg)) { 1874 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1875 1876 // Send added for users that see the package for the first time 1877 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1878 extras, 0 /*flags*/, null /*targetPackage*/, 1879 null /*finishedReceiver*/, firstUsers); 1880 1881 // Send added for users that don't see the package for the first time 1882 if (update) { 1883 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1884 } 1885 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1886 extras, 0 /*flags*/, null /*targetPackage*/, 1887 null /*finishedReceiver*/, updateUsers); 1888 1889 // Send replaced for users that don't see the package for the first time 1890 if (update) { 1891 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1892 packageName, extras, 0 /*flags*/, 1893 null /*targetPackage*/, null /*finishedReceiver*/, 1894 updateUsers); 1895 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1896 null /*package*/, null /*extras*/, 0 /*flags*/, 1897 packageName /*targetPackage*/, 1898 null /*finishedReceiver*/, updateUsers); 1899 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1900 // First-install and we did a restore, so we're responsible for the 1901 // first-launch broadcast. 1902 if (DEBUG_BACKUP) { 1903 Slog.i(TAG, "Post-restore of " + packageName 1904 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1905 } 1906 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1907 } 1908 1909 // Send broadcast package appeared if forward locked/external for all users 1910 // treat asec-hosted packages like removable media on upgrade 1911 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1912 if (DEBUG_INSTALL) { 1913 Slog.i(TAG, "upgrading pkg " + res.pkg 1914 + " is ASEC-hosted -> AVAILABLE"); 1915 } 1916 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1917 ArrayList<String> pkgList = new ArrayList<>(1); 1918 pkgList.add(packageName); 1919 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1920 } 1921 } 1922 1923 // Work that needs to happen on first install within each user 1924 if (firstUsers != null && firstUsers.length > 0) { 1925 synchronized (mPackages) { 1926 for (int userId : firstUsers) { 1927 // If this app is a browser and it's newly-installed for some 1928 // users, clear any default-browser state in those users. The 1929 // app's nature doesn't depend on the user, so we can just check 1930 // its browser nature in any user and generalize. 1931 if (packageIsBrowser(packageName, userId)) { 1932 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1933 } 1934 1935 // We may also need to apply pending (restored) runtime 1936 // permission grants within these users. 1937 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1938 } 1939 } 1940 } 1941 1942 // Log current value of "unknown sources" setting 1943 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1944 getUnknownSourcesSettings()); 1945 1946 // Force a gc to clear up things 1947 Runtime.getRuntime().gc(); 1948 1949 // Remove the replaced package's older resources safely now 1950 // We delete after a gc for applications on sdcard. 1951 if (res.removedInfo != null && res.removedInfo.args != null) { 1952 synchronized (mInstallLock) { 1953 res.removedInfo.args.doPostDeleteLI(true); 1954 } 1955 } 1956 } 1957 1958 // If someone is watching installs - notify them 1959 if (installObserver != null) { 1960 try { 1961 Bundle extras = extrasForInstallResult(res); 1962 installObserver.onPackageInstalled(res.name, res.returnCode, 1963 res.returnMsg, extras); 1964 } catch (RemoteException e) { 1965 Slog.i(TAG, "Observer no longer exists."); 1966 } 1967 } 1968 } 1969 1970 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1971 PackageParser.Package pkg) { 1972 if (pkg.parentPackage == null) { 1973 return; 1974 } 1975 if (pkg.requestedPermissions == null) { 1976 return; 1977 } 1978 final PackageSetting disabledSysParentPs = mSettings 1979 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1980 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1981 || !disabledSysParentPs.isPrivileged() 1982 || (disabledSysParentPs.childPackageNames != null 1983 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1984 return; 1985 } 1986 final int[] allUserIds = sUserManager.getUserIds(); 1987 final int permCount = pkg.requestedPermissions.size(); 1988 for (int i = 0; i < permCount; i++) { 1989 String permission = pkg.requestedPermissions.get(i); 1990 BasePermission bp = mSettings.mPermissions.get(permission); 1991 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1992 continue; 1993 } 1994 for (int userId : allUserIds) { 1995 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1996 permission, userId)) { 1997 grantRuntimePermission(pkg.packageName, permission, userId); 1998 } 1999 } 2000 } 2001 } 2002 2003 private StorageEventListener mStorageListener = new StorageEventListener() { 2004 @Override 2005 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2006 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2007 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2008 final String volumeUuid = vol.getFsUuid(); 2009 2010 // Clean up any users or apps that were removed or recreated 2011 // while this volume was missing 2012 reconcileUsers(volumeUuid); 2013 reconcileApps(volumeUuid); 2014 2015 // Clean up any install sessions that expired or were 2016 // cancelled while this volume was missing 2017 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2018 2019 loadPrivatePackages(vol); 2020 2021 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2022 unloadPrivatePackages(vol); 2023 } 2024 } 2025 2026 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2027 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2028 updateExternalMediaStatus(true, false); 2029 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2030 updateExternalMediaStatus(false, false); 2031 } 2032 } 2033 } 2034 2035 @Override 2036 public void onVolumeForgotten(String fsUuid) { 2037 if (TextUtils.isEmpty(fsUuid)) { 2038 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2039 return; 2040 } 2041 2042 // Remove any apps installed on the forgotten volume 2043 synchronized (mPackages) { 2044 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2045 for (PackageSetting ps : packages) { 2046 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2047 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2048 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2049 } 2050 2051 mSettings.onVolumeForgotten(fsUuid); 2052 mSettings.writeLPr(); 2053 } 2054 } 2055 }; 2056 2057 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2058 String[] grantedPermissions) { 2059 for (int userId : userIds) { 2060 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2061 } 2062 2063 // We could have touched GID membership, so flush out packages.list 2064 synchronized (mPackages) { 2065 mSettings.writePackageListLPr(); 2066 } 2067 } 2068 2069 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2070 String[] grantedPermissions) { 2071 SettingBase sb = (SettingBase) pkg.mExtras; 2072 if (sb == null) { 2073 return; 2074 } 2075 2076 PermissionsState permissionsState = sb.getPermissionsState(); 2077 2078 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2079 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2080 2081 for (String permission : pkg.requestedPermissions) { 2082 final BasePermission bp; 2083 synchronized (mPackages) { 2084 bp = mSettings.mPermissions.get(permission); 2085 } 2086 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2087 && (grantedPermissions == null 2088 || ArrayUtils.contains(grantedPermissions, permission))) { 2089 final int flags = permissionsState.getPermissionFlags(permission, userId); 2090 // Installer cannot change immutable permissions. 2091 if ((flags & immutableFlags) == 0) { 2092 grantRuntimePermission(pkg.packageName, permission, userId); 2093 } 2094 } 2095 } 2096 } 2097 2098 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2099 Bundle extras = null; 2100 switch (res.returnCode) { 2101 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2102 extras = new Bundle(); 2103 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2104 res.origPermission); 2105 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2106 res.origPackage); 2107 break; 2108 } 2109 case PackageManager.INSTALL_SUCCEEDED: { 2110 extras = new Bundle(); 2111 extras.putBoolean(Intent.EXTRA_REPLACING, 2112 res.removedInfo != null && res.removedInfo.removedPackage != null); 2113 break; 2114 } 2115 } 2116 return extras; 2117 } 2118 2119 void scheduleWriteSettingsLocked() { 2120 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2121 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2122 } 2123 } 2124 2125 void scheduleWritePackageListLocked(int userId) { 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2127 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2128 msg.arg1 = userId; 2129 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2130 } 2131 } 2132 2133 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2134 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2135 scheduleWritePackageRestrictionsLocked(userId); 2136 } 2137 2138 void scheduleWritePackageRestrictionsLocked(int userId) { 2139 final int[] userIds = (userId == UserHandle.USER_ALL) 2140 ? sUserManager.getUserIds() : new int[]{userId}; 2141 for (int nextUserId : userIds) { 2142 if (!sUserManager.exists(nextUserId)) return; 2143 mDirtyUsers.add(nextUserId); 2144 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2145 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2146 } 2147 } 2148 } 2149 2150 public static PackageManagerService main(Context context, Installer installer, 2151 boolean factoryTest, boolean onlyCore) { 2152 // Self-check for initial settings. 2153 PackageManagerServiceCompilerMapping.checkProperties(); 2154 2155 PackageManagerService m = new PackageManagerService(context, installer, 2156 factoryTest, onlyCore); 2157 m.enableSystemUserPackages(); 2158 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2159 // disabled after already being started. 2160 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2161 UserHandle.USER_SYSTEM); 2162 ServiceManager.addService("package", m); 2163 return m; 2164 } 2165 2166 private void enableSystemUserPackages() { 2167 if (!UserManager.isSplitSystemUser()) { 2168 return; 2169 } 2170 // For system user, enable apps based on the following conditions: 2171 // - app is whitelisted or belong to one of these groups: 2172 // -- system app which has no launcher icons 2173 // -- system app which has INTERACT_ACROSS_USERS permission 2174 // -- system IME app 2175 // - app is not in the blacklist 2176 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2177 Set<String> enableApps = new ArraySet<>(); 2178 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2179 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2180 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2181 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2182 enableApps.addAll(wlApps); 2183 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2184 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2185 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2186 enableApps.removeAll(blApps); 2187 Log.i(TAG, "Applications installed for system user: " + enableApps); 2188 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2189 UserHandle.SYSTEM); 2190 final int allAppsSize = allAps.size(); 2191 synchronized (mPackages) { 2192 for (int i = 0; i < allAppsSize; i++) { 2193 String pName = allAps.get(i); 2194 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2195 // Should not happen, but we shouldn't be failing if it does 2196 if (pkgSetting == null) { 2197 continue; 2198 } 2199 boolean install = enableApps.contains(pName); 2200 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2201 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2202 + " for system user"); 2203 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2204 } 2205 } 2206 } 2207 } 2208 2209 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2210 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2211 Context.DISPLAY_SERVICE); 2212 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2213 } 2214 2215 public PackageManagerService(Context context, Installer installer, 2216 boolean factoryTest, boolean onlyCore) { 2217 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2218 SystemClock.uptimeMillis()); 2219 2220 if (mSdkVersion <= 0) { 2221 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2222 } 2223 2224 mContext = context; 2225 mFactoryTest = factoryTest; 2226 mOnlyCore = onlyCore; 2227 mMetrics = new DisplayMetrics(); 2228 mSettings = new Settings(mPackages); 2229 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2230 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2231 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2232 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2233 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2234 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2235 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 2242 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2243 if (separateProcesses != null && separateProcesses.length() > 0) { 2244 if ("*".equals(separateProcesses)) { 2245 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2246 mSeparateProcesses = null; 2247 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2248 } else { 2249 mDefParseFlags = 0; 2250 mSeparateProcesses = separateProcesses.split(","); 2251 Slog.w(TAG, "Running with debug.separate_processes: " 2252 + separateProcesses); 2253 } 2254 } else { 2255 mDefParseFlags = 0; 2256 mSeparateProcesses = null; 2257 } 2258 2259 mInstaller = installer; 2260 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2261 "*dexopt*"); 2262 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2263 2264 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2265 FgThread.get().getLooper()); 2266 2267 getDefaultDisplayMetrics(context, mMetrics); 2268 2269 SystemConfig systemConfig = SystemConfig.getInstance(); 2270 mGlobalGids = systemConfig.getGlobalGids(); 2271 mSystemPermissions = systemConfig.getSystemPermissions(); 2272 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2273 2274 synchronized (mInstallLock) { 2275 // writer 2276 synchronized (mPackages) { 2277 mHandlerThread = new ServiceThread(TAG, 2278 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2279 mHandlerThread.start(); 2280 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2281 mProcessLoggingHandler = new ProcessLoggingHandler(); 2282 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2283 2284 File dataDir = Environment.getDataDirectory(); 2285 mAppInstallDir = new File(dataDir, "app"); 2286 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2287 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2288 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2289 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2290 2291 sUserManager = new UserManagerService(context, this, mPackages); 2292 2293 // Propagate permission configuration in to package manager. 2294 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2295 = systemConfig.getPermissions(); 2296 for (int i=0; i<permConfig.size(); i++) { 2297 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2298 BasePermission bp = mSettings.mPermissions.get(perm.name); 2299 if (bp == null) { 2300 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2301 mSettings.mPermissions.put(perm.name, bp); 2302 } 2303 if (perm.gids != null) { 2304 bp.setGids(perm.gids, perm.perUser); 2305 } 2306 } 2307 2308 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2309 for (int i=0; i<libConfig.size(); i++) { 2310 mSharedLibraries.put(libConfig.keyAt(i), 2311 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2312 } 2313 2314 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2315 2316 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2317 2318 String customResolverActivity = Resources.getSystem().getString( 2319 R.string.config_customResolverActivity); 2320 if (TextUtils.isEmpty(customResolverActivity)) { 2321 customResolverActivity = null; 2322 } else { 2323 mCustomResolverComponentName = ComponentName.unflattenFromString( 2324 customResolverActivity); 2325 } 2326 2327 long startTime = SystemClock.uptimeMillis(); 2328 2329 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2330 startTime); 2331 2332 // Set flag to monitor and not change apk file paths when 2333 // scanning install directories. 2334 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2335 2336 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2337 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2338 2339 if (bootClassPath == null) { 2340 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2341 } 2342 2343 if (systemServerClassPath == null) { 2344 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2345 } 2346 2347 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2348 final String[] dexCodeInstructionSets = 2349 getDexCodeInstructionSets( 2350 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2351 2352 /** 2353 * Ensure all external libraries have had dexopt run on them. 2354 */ 2355 if (mSharedLibraries.size() > 0) { 2356 // NOTE: For now, we're compiling these system "shared libraries" 2357 // (and framework jars) into all available architectures. It's possible 2358 // to compile them only when we come across an app that uses them (there's 2359 // already logic for that in scanPackageLI) but that adds some complexity. 2360 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2361 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2362 final String lib = libEntry.path; 2363 if (lib == null) { 2364 continue; 2365 } 2366 2367 try { 2368 // Shared libraries do not have profiles so we perform a full 2369 // AOT compilation (if needed). 2370 int dexoptNeeded = DexFile.getDexOptNeeded( 2371 lib, dexCodeInstructionSet, 2372 getCompilerFilterForReason(REASON_SHARED_APK), 2373 false /* newProfile */); 2374 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2375 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2376 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2377 getCompilerFilterForReason(REASON_SHARED_APK), 2378 StorageManager.UUID_PRIVATE_INTERNAL, 2379 SKIP_SHARED_LIBRARY_CHECK); 2380 } 2381 } catch (FileNotFoundException e) { 2382 Slog.w(TAG, "Library not found: " + lib); 2383 } catch (IOException | InstallerException e) { 2384 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2385 + e.getMessage()); 2386 } 2387 } 2388 } 2389 } 2390 2391 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2392 2393 final VersionInfo ver = mSettings.getInternalVersion(); 2394 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2395 2396 // when upgrading from pre-M, promote system app permissions from install to runtime 2397 mPromoteSystemApps = 2398 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2399 2400 // When upgrading from pre-N, we need to handle package extraction like first boot, 2401 // as there is no profiling data available. 2402 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2403 2404 // save off the names of pre-existing system packages prior to scanning; we don't 2405 // want to automatically grant runtime permissions for new system apps 2406 if (mPromoteSystemApps) { 2407 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2408 while (pkgSettingIter.hasNext()) { 2409 PackageSetting ps = pkgSettingIter.next(); 2410 if (isSystemApp(ps)) { 2411 mExistingSystemPackages.add(ps.name); 2412 } 2413 } 2414 } 2415 2416 // Collect vendor overlay packages. 2417 // (Do this before scanning any apps.) 2418 // For security and version matching reason, only consider 2419 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2420 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2421 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2422 | PackageParser.PARSE_IS_SYSTEM 2423 | PackageParser.PARSE_IS_SYSTEM_DIR 2424 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2425 2426 // Find base frameworks (resource packages without code). 2427 scanDirTracedLI(frameworkDir, mDefParseFlags 2428 | PackageParser.PARSE_IS_SYSTEM 2429 | PackageParser.PARSE_IS_SYSTEM_DIR 2430 | PackageParser.PARSE_IS_PRIVILEGED, 2431 scanFlags | SCAN_NO_DEX, 0); 2432 2433 // Collected privileged system packages. 2434 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2435 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2436 | PackageParser.PARSE_IS_SYSTEM 2437 | PackageParser.PARSE_IS_SYSTEM_DIR 2438 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2439 2440 // Collect ordinary system packages. 2441 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2442 scanDirTracedLI(systemAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2445 2446 // Collect all vendor packages. 2447 File vendorAppDir = new File("/vendor/app"); 2448 try { 2449 vendorAppDir = vendorAppDir.getCanonicalFile(); 2450 } catch (IOException e) { 2451 // failed to look up canonical path, continue with original one 2452 } 2453 scanDirTracedLI(vendorAppDir, mDefParseFlags 2454 | PackageParser.PARSE_IS_SYSTEM 2455 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2456 2457 // Collect all OEM packages. 2458 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2459 scanDirTracedLI(oemAppDir, mDefParseFlags 2460 | PackageParser.PARSE_IS_SYSTEM 2461 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2462 2463 // Prune any system packages that no longer exist. 2464 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2465 if (!mOnlyCore) { 2466 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2467 while (psit.hasNext()) { 2468 PackageSetting ps = psit.next(); 2469 2470 /* 2471 * If this is not a system app, it can't be a 2472 * disable system app. 2473 */ 2474 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2475 continue; 2476 } 2477 2478 /* 2479 * If the package is scanned, it's not erased. 2480 */ 2481 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2482 if (scannedPkg != null) { 2483 /* 2484 * If the system app is both scanned and in the 2485 * disabled packages list, then it must have been 2486 * added via OTA. Remove it from the currently 2487 * scanned package so the previously user-installed 2488 * application can be scanned. 2489 */ 2490 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2491 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2492 + ps.name + "; removing system app. Last known codePath=" 2493 + ps.codePathString + ", installStatus=" + ps.installStatus 2494 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2495 + scannedPkg.mVersionCode); 2496 removePackageLI(scannedPkg, true); 2497 mExpectingBetter.put(ps.name, ps.codePath); 2498 } 2499 2500 continue; 2501 } 2502 2503 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2504 psit.remove(); 2505 logCriticalInfo(Log.WARN, "System package " + ps.name 2506 + " no longer exists; it's data will be wiped"); 2507 // Actual deletion of code and data will be handled by later 2508 // reconciliation step 2509 } else { 2510 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2511 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2512 possiblyDeletedUpdatedSystemApps.add(ps.name); 2513 } 2514 } 2515 } 2516 } 2517 2518 //look for any incomplete package installations 2519 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2520 for (int i = 0; i < deletePkgsList.size(); i++) { 2521 // Actual deletion of code and data will be handled by later 2522 // reconciliation step 2523 final String packageName = deletePkgsList.get(i).name; 2524 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2525 synchronized (mPackages) { 2526 mSettings.removePackageLPw(packageName); 2527 } 2528 } 2529 2530 //delete tmp files 2531 deleteTempPackageFiles(); 2532 2533 // Remove any shared userIDs that have no associated packages 2534 mSettings.pruneSharedUsersLPw(); 2535 2536 if (!mOnlyCore) { 2537 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2538 SystemClock.uptimeMillis()); 2539 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2540 2541 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2542 | PackageParser.PARSE_FORWARD_LOCK, 2543 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2544 2545 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2546 | PackageParser.PARSE_IS_EPHEMERAL, 2547 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2548 2549 /** 2550 * Remove disable package settings for any updated system 2551 * apps that were removed via an OTA. If they're not a 2552 * previously-updated app, remove them completely. 2553 * Otherwise, just revoke their system-level permissions. 2554 */ 2555 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2556 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2557 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2558 2559 String msg; 2560 if (deletedPkg == null) { 2561 msg = "Updated system package " + deletedAppName 2562 + " no longer exists; it's data will be wiped"; 2563 // Actual deletion of code and data will be handled by later 2564 // reconciliation step 2565 } else { 2566 msg = "Updated system app + " + deletedAppName 2567 + " no longer present; removing system privileges for " 2568 + deletedAppName; 2569 2570 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2571 2572 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2573 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2574 } 2575 logCriticalInfo(Log.WARN, msg); 2576 } 2577 2578 /** 2579 * Make sure all system apps that we expected to appear on 2580 * the userdata partition actually showed up. If they never 2581 * appeared, crawl back and revive the system version. 2582 */ 2583 for (int i = 0; i < mExpectingBetter.size(); i++) { 2584 final String packageName = mExpectingBetter.keyAt(i); 2585 if (!mPackages.containsKey(packageName)) { 2586 final File scanFile = mExpectingBetter.valueAt(i); 2587 2588 logCriticalInfo(Log.WARN, "Expected better " + packageName 2589 + " but never showed up; reverting to system"); 2590 2591 int reparseFlags = mDefParseFlags; 2592 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2593 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2594 | PackageParser.PARSE_IS_SYSTEM_DIR 2595 | PackageParser.PARSE_IS_PRIVILEGED; 2596 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2597 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2598 | PackageParser.PARSE_IS_SYSTEM_DIR; 2599 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2600 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2601 | PackageParser.PARSE_IS_SYSTEM_DIR; 2602 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2603 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR; 2605 } else { 2606 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2607 continue; 2608 } 2609 2610 mSettings.enableSystemPackageLPw(packageName); 2611 2612 try { 2613 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2614 } catch (PackageManagerException e) { 2615 Slog.e(TAG, "Failed to parse original system package: " 2616 + e.getMessage()); 2617 } 2618 } 2619 } 2620 } 2621 mExpectingBetter.clear(); 2622 2623 // Resolve protected action filters. Only the setup wizard is allowed to 2624 // have a high priority filter for these actions. 2625 mSetupWizardPackage = getSetupWizardPackageName(); 2626 if (mProtectedFilters.size() > 0) { 2627 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2628 Slog.i(TAG, "No setup wizard;" 2629 + " All protected intents capped to priority 0"); 2630 } 2631 for (ActivityIntentInfo filter : mProtectedFilters) { 2632 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2633 if (DEBUG_FILTERS) { 2634 Slog.i(TAG, "Found setup wizard;" 2635 + " allow priority " + filter.getPriority() + ";" 2636 + " package: " + filter.activity.info.packageName 2637 + " activity: " + filter.activity.className 2638 + " priority: " + filter.getPriority()); 2639 } 2640 // skip setup wizard; allow it to keep the high priority filter 2641 continue; 2642 } 2643 Slog.w(TAG, "Protected action; cap priority to 0;" 2644 + " package: " + filter.activity.info.packageName 2645 + " activity: " + filter.activity.className 2646 + " origPrio: " + filter.getPriority()); 2647 filter.setPriority(0); 2648 } 2649 } 2650 mDeferProtectedFilters = false; 2651 mProtectedFilters.clear(); 2652 2653 // Now that we know all of the shared libraries, update all clients to have 2654 // the correct library paths. 2655 updateAllSharedLibrariesLPw(); 2656 2657 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2658 // NOTE: We ignore potential failures here during a system scan (like 2659 // the rest of the commands above) because there's precious little we 2660 // can do about it. A settings error is reported, though. 2661 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2662 false /* boot complete */); 2663 } 2664 2665 // Now that we know all the packages we are keeping, 2666 // read and update their last usage times. 2667 mPackageUsage.readLP(); 2668 2669 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2670 SystemClock.uptimeMillis()); 2671 Slog.i(TAG, "Time to scan packages: " 2672 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2673 + " seconds"); 2674 2675 // If the platform SDK has changed since the last time we booted, 2676 // we need to re-grant app permission to catch any new ones that 2677 // appear. This is really a hack, and means that apps can in some 2678 // cases get permissions that the user didn't initially explicitly 2679 // allow... it would be nice to have some better way to handle 2680 // this situation. 2681 int updateFlags = UPDATE_PERMISSIONS_ALL; 2682 if (ver.sdkVersion != mSdkVersion) { 2683 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2684 + mSdkVersion + "; regranting permissions for internal storage"); 2685 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2686 } 2687 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2688 ver.sdkVersion = mSdkVersion; 2689 2690 // If this is the first boot or an update from pre-M, and it is a normal 2691 // boot, then we need to initialize the default preferred apps across 2692 // all defined users. 2693 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2694 for (UserInfo user : sUserManager.getUsers(true)) { 2695 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2696 applyFactoryDefaultBrowserLPw(user.id); 2697 primeDomainVerificationsLPw(user.id); 2698 } 2699 } 2700 2701 // Prepare storage for system user really early during boot, 2702 // since core system apps like SettingsProvider and SystemUI 2703 // can't wait for user to start 2704 final int storageFlags; 2705 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2706 storageFlags = StorageManager.FLAG_STORAGE_DE; 2707 } else { 2708 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2709 } 2710 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2711 storageFlags); 2712 2713 // If this is first boot after an OTA, and a normal boot, then 2714 // we need to clear code cache directories. 2715 // Note that we do *not* clear the application profiles. These remain valid 2716 // across OTAs and are used to drive profile verification (post OTA) and 2717 // profile compilation (without waiting to collect a fresh set of profiles). 2718 if (mIsUpgrade && !onlyCore) { 2719 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2720 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2721 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2722 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2723 // No apps are running this early, so no need to freeze 2724 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2725 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2726 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2727 } 2728 } 2729 ver.fingerprint = Build.FINGERPRINT; 2730 } 2731 2732 checkDefaultBrowser(); 2733 2734 // clear only after permissions and other defaults have been updated 2735 mExistingSystemPackages.clear(); 2736 mPromoteSystemApps = false; 2737 2738 // All the changes are done during package scanning. 2739 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2740 2741 // can downgrade to reader 2742 mSettings.writeLPr(); 2743 2744 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2745 SystemClock.uptimeMillis()); 2746 2747 if (!mOnlyCore) { 2748 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2749 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2750 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2751 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2752 mIntentFilterVerifierComponent); 2753 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2754 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2755 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2756 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2757 } else { 2758 mRequiredVerifierPackage = null; 2759 mRequiredInstallerPackage = null; 2760 mIntentFilterVerifierComponent = null; 2761 mIntentFilterVerifier = null; 2762 mServicesSystemSharedLibraryPackageName = null; 2763 mSharedSystemSharedLibraryPackageName = null; 2764 } 2765 2766 mInstallerService = new PackageInstallerService(context, this); 2767 2768 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2769 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2770 // both the installer and resolver must be present to enable ephemeral 2771 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2772 if (DEBUG_EPHEMERAL) { 2773 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2774 + " installer:" + ephemeralInstallerComponent); 2775 } 2776 mEphemeralResolverComponent = ephemeralResolverComponent; 2777 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2778 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2779 mEphemeralResolverConnection = 2780 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2781 } else { 2782 if (DEBUG_EPHEMERAL) { 2783 final String missingComponent = 2784 (ephemeralResolverComponent == null) 2785 ? (ephemeralInstallerComponent == null) 2786 ? "resolver and installer" 2787 : "resolver" 2788 : "installer"; 2789 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2790 } 2791 mEphemeralResolverComponent = null; 2792 mEphemeralInstallerComponent = null; 2793 mEphemeralResolverConnection = null; 2794 } 2795 2796 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2797 } // synchronized (mPackages) 2798 } // synchronized (mInstallLock) 2799 2800 // Now after opening every single application zip, make sure they 2801 // are all flushed. Not really needed, but keeps things nice and 2802 // tidy. 2803 Runtime.getRuntime().gc(); 2804 2805 // The initial scanning above does many calls into installd while 2806 // holding the mPackages lock, but we're mostly interested in yelling 2807 // once we have a booted system. 2808 mInstaller.setWarnIfHeld(mPackages); 2809 2810 // Expose private service for system components to use. 2811 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2812 } 2813 2814 @Override 2815 public boolean isFirstBoot() { 2816 return !mRestoredSettings; 2817 } 2818 2819 @Override 2820 public boolean isOnlyCoreApps() { 2821 return mOnlyCore; 2822 } 2823 2824 @Override 2825 public boolean isUpgrade() { 2826 return mIsUpgrade; 2827 } 2828 2829 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2830 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2831 2832 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2833 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2834 UserHandle.USER_SYSTEM); 2835 if (matches.size() == 1) { 2836 return matches.get(0).getComponentInfo().packageName; 2837 } else { 2838 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2839 return null; 2840 } 2841 } 2842 2843 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2844 synchronized (mPackages) { 2845 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2846 if (libraryEntry == null) { 2847 throw new IllegalStateException("Missing required shared library:" + libraryName); 2848 } 2849 return libraryEntry.apk; 2850 } 2851 } 2852 2853 private @NonNull String getRequiredInstallerLPr() { 2854 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2855 intent.addCategory(Intent.CATEGORY_DEFAULT); 2856 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2857 2858 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2859 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2860 UserHandle.USER_SYSTEM); 2861 if (matches.size() == 1) { 2862 ResolveInfo resolveInfo = matches.get(0); 2863 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2864 throw new RuntimeException("The installer must be a privileged app"); 2865 } 2866 return matches.get(0).getComponentInfo().packageName; 2867 } else { 2868 throw new RuntimeException("There must be exactly one installer; found " + matches); 2869 } 2870 } 2871 2872 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2873 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2874 2875 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2876 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2877 UserHandle.USER_SYSTEM); 2878 ResolveInfo best = null; 2879 final int N = matches.size(); 2880 for (int i = 0; i < N; i++) { 2881 final ResolveInfo cur = matches.get(i); 2882 final String packageName = cur.getComponentInfo().packageName; 2883 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2884 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2885 continue; 2886 } 2887 2888 if (best == null || cur.priority > best.priority) { 2889 best = cur; 2890 } 2891 } 2892 2893 if (best != null) { 2894 return best.getComponentInfo().getComponentName(); 2895 } else { 2896 throw new RuntimeException("There must be at least one intent filter verifier"); 2897 } 2898 } 2899 2900 private @Nullable ComponentName getEphemeralResolverLPr() { 2901 final String[] packageArray = 2902 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2903 if (packageArray.length == 0) { 2904 if (DEBUG_EPHEMERAL) { 2905 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2906 } 2907 return null; 2908 } 2909 2910 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2911 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 2915 final int N = resolvers.size(); 2916 if (N == 0) { 2917 if (DEBUG_EPHEMERAL) { 2918 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2919 } 2920 return null; 2921 } 2922 2923 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2924 for (int i = 0; i < N; i++) { 2925 final ResolveInfo info = resolvers.get(i); 2926 2927 if (info.serviceInfo == null) { 2928 continue; 2929 } 2930 2931 final String packageName = info.serviceInfo.packageName; 2932 if (!possiblePackages.contains(packageName)) { 2933 if (DEBUG_EPHEMERAL) { 2934 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2935 + " pkg: " + packageName + ", info:" + info); 2936 } 2937 continue; 2938 } 2939 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.v(TAG, "Ephemeral resolver found;" 2942 + " pkg: " + packageName + ", info:" + info); 2943 } 2944 return new ComponentName(packageName, info.serviceInfo.name); 2945 } 2946 if (DEBUG_EPHEMERAL) { 2947 Slog.v(TAG, "Ephemeral resolver NOT found"); 2948 } 2949 return null; 2950 } 2951 2952 private @Nullable ComponentName getEphemeralInstallerLPr() { 2953 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2954 intent.addCategory(Intent.CATEGORY_DEFAULT); 2955 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2956 2957 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2958 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2959 UserHandle.USER_SYSTEM); 2960 if (matches.size() == 0) { 2961 return null; 2962 } else if (matches.size() == 1) { 2963 return matches.get(0).getComponentInfo().getComponentName(); 2964 } else { 2965 throw new RuntimeException( 2966 "There must be at most one ephemeral installer; found " + matches); 2967 } 2968 } 2969 2970 private void primeDomainVerificationsLPw(int userId) { 2971 if (DEBUG_DOMAIN_VERIFICATION) { 2972 Slog.d(TAG, "Priming domain verifications in user " + userId); 2973 } 2974 2975 SystemConfig systemConfig = SystemConfig.getInstance(); 2976 ArraySet<String> packages = systemConfig.getLinkedApps(); 2977 ArraySet<String> domains = new ArraySet<String>(); 2978 2979 for (String packageName : packages) { 2980 PackageParser.Package pkg = mPackages.get(packageName); 2981 if (pkg != null) { 2982 if (!pkg.isSystemApp()) { 2983 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2984 continue; 2985 } 2986 2987 domains.clear(); 2988 for (PackageParser.Activity a : pkg.activities) { 2989 for (ActivityIntentInfo filter : a.intents) { 2990 if (hasValidDomains(filter)) { 2991 domains.addAll(filter.getHostsList()); 2992 } 2993 } 2994 } 2995 2996 if (domains.size() > 0) { 2997 if (DEBUG_DOMAIN_VERIFICATION) { 2998 Slog.v(TAG, " + " + packageName); 2999 } 3000 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3001 // state w.r.t. the formal app-linkage "no verification attempted" state; 3002 // and then 'always' in the per-user state actually used for intent resolution. 3003 final IntentFilterVerificationInfo ivi; 3004 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3005 new ArrayList<String>(domains)); 3006 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3007 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3008 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3009 } else { 3010 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3011 + "' does not handle web links"); 3012 } 3013 } else { 3014 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3015 } 3016 } 3017 3018 scheduleWritePackageRestrictionsLocked(userId); 3019 scheduleWriteSettingsLocked(); 3020 } 3021 3022 private void applyFactoryDefaultBrowserLPw(int userId) { 3023 // The default browser app's package name is stored in a string resource, 3024 // with a product-specific overlay used for vendor customization. 3025 String browserPkg = mContext.getResources().getString( 3026 com.android.internal.R.string.default_browser); 3027 if (!TextUtils.isEmpty(browserPkg)) { 3028 // non-empty string => required to be a known package 3029 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3030 if (ps == null) { 3031 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3032 browserPkg = null; 3033 } else { 3034 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3035 } 3036 } 3037 3038 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3039 // default. If there's more than one, just leave everything alone. 3040 if (browserPkg == null) { 3041 calculateDefaultBrowserLPw(userId); 3042 } 3043 } 3044 3045 private void calculateDefaultBrowserLPw(int userId) { 3046 List<String> allBrowsers = resolveAllBrowserApps(userId); 3047 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3048 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3049 } 3050 3051 private List<String> resolveAllBrowserApps(int userId) { 3052 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3053 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3054 PackageManager.MATCH_ALL, userId); 3055 3056 final int count = list.size(); 3057 List<String> result = new ArrayList<String>(count); 3058 for (int i=0; i<count; i++) { 3059 ResolveInfo info = list.get(i); 3060 if (info.activityInfo == null 3061 || !info.handleAllWebDataURI 3062 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3063 || result.contains(info.activityInfo.packageName)) { 3064 continue; 3065 } 3066 result.add(info.activityInfo.packageName); 3067 } 3068 3069 return result; 3070 } 3071 3072 private boolean packageIsBrowser(String packageName, int userId) { 3073 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3074 PackageManager.MATCH_ALL, userId); 3075 final int N = list.size(); 3076 for (int i = 0; i < N; i++) { 3077 ResolveInfo info = list.get(i); 3078 if (packageName.equals(info.activityInfo.packageName)) { 3079 return true; 3080 } 3081 } 3082 return false; 3083 } 3084 3085 private void checkDefaultBrowser() { 3086 final int myUserId = UserHandle.myUserId(); 3087 final String packageName = getDefaultBrowserPackageName(myUserId); 3088 if (packageName != null) { 3089 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3090 if (info == null) { 3091 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3092 synchronized (mPackages) { 3093 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3094 } 3095 } 3096 } 3097 } 3098 3099 @Override 3100 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3101 throws RemoteException { 3102 try { 3103 return super.onTransact(code, data, reply, flags); 3104 } catch (RuntimeException e) { 3105 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3106 Slog.wtf(TAG, "Package Manager Crash", e); 3107 } 3108 throw e; 3109 } 3110 } 3111 3112 static int[] appendInts(int[] cur, int[] add) { 3113 if (add == null) return cur; 3114 if (cur == null) return add; 3115 final int N = add.length; 3116 for (int i=0; i<N; i++) { 3117 cur = appendInt(cur, add[i]); 3118 } 3119 return cur; 3120 } 3121 3122 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3123 if (!sUserManager.exists(userId)) return null; 3124 if (ps == null) { 3125 return null; 3126 } 3127 final PackageParser.Package p = ps.pkg; 3128 if (p == null) { 3129 return null; 3130 } 3131 3132 final PermissionsState permissionsState = ps.getPermissionsState(); 3133 3134 final int[] gids = permissionsState.computeGids(userId); 3135 final Set<String> permissions = permissionsState.getPermissions(userId); 3136 final PackageUserState state = ps.readUserState(userId); 3137 3138 return PackageParser.generatePackageInfo(p, gids, flags, 3139 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3140 } 3141 3142 @Override 3143 public void checkPackageStartable(String packageName, int userId) { 3144 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3145 3146 synchronized (mPackages) { 3147 final PackageSetting ps = mSettings.mPackages.get(packageName); 3148 if (ps == null) { 3149 throw new SecurityException("Package " + packageName + " was not found!"); 3150 } 3151 3152 if (!ps.getInstalled(userId)) { 3153 throw new SecurityException( 3154 "Package " + packageName + " was not installed for user " + userId + "!"); 3155 } 3156 3157 if (mSafeMode && !ps.isSystem()) { 3158 throw new SecurityException("Package " + packageName + " not a system app!"); 3159 } 3160 3161 if (mFrozenPackages.contains(packageName)) { 3162 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3163 } 3164 3165 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3166 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3167 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3168 } 3169 } 3170 } 3171 3172 @Override 3173 public boolean isPackageAvailable(String packageName, int userId) { 3174 if (!sUserManager.exists(userId)) return false; 3175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3176 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3177 synchronized (mPackages) { 3178 PackageParser.Package p = mPackages.get(packageName); 3179 if (p != null) { 3180 final PackageSetting ps = (PackageSetting) p.mExtras; 3181 if (ps != null) { 3182 final PackageUserState state = ps.readUserState(userId); 3183 if (state != null) { 3184 return PackageParser.isAvailable(state); 3185 } 3186 } 3187 } 3188 } 3189 return false; 3190 } 3191 3192 @Override 3193 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3194 if (!sUserManager.exists(userId)) return null; 3195 flags = updateFlagsForPackage(flags, userId, packageName); 3196 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3197 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3198 // reader 3199 synchronized (mPackages) { 3200 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3201 PackageParser.Package p = null; 3202 if (matchFactoryOnly) { 3203 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3204 if (ps != null) { 3205 return generatePackageInfo(ps, flags, userId); 3206 } 3207 } 3208 if (p == null) { 3209 p = mPackages.get(packageName); 3210 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3211 return null; 3212 } 3213 } 3214 if (DEBUG_PACKAGE_INFO) 3215 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3216 if (p != null) { 3217 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3218 } 3219 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3220 final PackageSetting ps = mSettings.mPackages.get(packageName); 3221 return generatePackageInfo(ps, flags, userId); 3222 } 3223 } 3224 return null; 3225 } 3226 3227 @Override 3228 public String[] currentToCanonicalPackageNames(String[] names) { 3229 String[] out = new String[names.length]; 3230 // reader 3231 synchronized (mPackages) { 3232 for (int i=names.length-1; i>=0; i--) { 3233 PackageSetting ps = mSettings.mPackages.get(names[i]); 3234 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3235 } 3236 } 3237 return out; 3238 } 3239 3240 @Override 3241 public String[] canonicalToCurrentPackageNames(String[] names) { 3242 String[] out = new String[names.length]; 3243 // reader 3244 synchronized (mPackages) { 3245 for (int i=names.length-1; i>=0; i--) { 3246 String cur = mSettings.mRenamedPackages.get(names[i]); 3247 out[i] = cur != null ? cur : names[i]; 3248 } 3249 } 3250 return out; 3251 } 3252 3253 @Override 3254 public int getPackageUid(String packageName, int flags, int userId) { 3255 if (!sUserManager.exists(userId)) return -1; 3256 flags = updateFlagsForPackage(flags, userId, packageName); 3257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3258 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 return UserHandle.getUid(userId, p.applicationInfo.uid); 3265 } 3266 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3267 final PackageSetting ps = mSettings.mPackages.get(packageName); 3268 if (ps != null && ps.isMatch(flags)) { 3269 return UserHandle.getUid(userId, ps.appId); 3270 } 3271 } 3272 } 3273 3274 return -1; 3275 } 3276 3277 @Override 3278 public int[] getPackageGids(String packageName, int flags, int userId) { 3279 if (!sUserManager.exists(userId)) return null; 3280 flags = updateFlagsForPackage(flags, userId, packageName); 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3282 false /* requireFullPermission */, false /* checkShell */, 3283 "getPackageGids"); 3284 3285 // reader 3286 synchronized (mPackages) { 3287 final PackageParser.Package p = mPackages.get(packageName); 3288 if (p != null && p.isMatch(flags)) { 3289 PackageSetting ps = (PackageSetting) p.mExtras; 3290 return ps.getPermissionsState().computeGids(userId); 3291 } 3292 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3293 final PackageSetting ps = mSettings.mPackages.get(packageName); 3294 if (ps != null && ps.isMatch(flags)) { 3295 return ps.getPermissionsState().computeGids(userId); 3296 } 3297 } 3298 } 3299 3300 return null; 3301 } 3302 3303 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3304 if (bp.perm != null) { 3305 return PackageParser.generatePermissionInfo(bp.perm, flags); 3306 } 3307 PermissionInfo pi = new PermissionInfo(); 3308 pi.name = bp.name; 3309 pi.packageName = bp.sourcePackage; 3310 pi.nonLocalizedLabel = bp.name; 3311 pi.protectionLevel = bp.protectionLevel; 3312 return pi; 3313 } 3314 3315 @Override 3316 public PermissionInfo getPermissionInfo(String name, int flags) { 3317 // reader 3318 synchronized (mPackages) { 3319 final BasePermission p = mSettings.mPermissions.get(name); 3320 if (p != null) { 3321 return generatePermissionInfo(p, flags); 3322 } 3323 return null; 3324 } 3325 } 3326 3327 @Override 3328 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3329 int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 if (group != null && !mPermissionGroups.containsKey(group)) { 3333 // This is thrown as NameNotFoundException 3334 return null; 3335 } 3336 3337 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3338 for (BasePermission p : mSettings.mPermissions.values()) { 3339 if (group == null) { 3340 if (p.perm == null || p.perm.info.group == null) { 3341 out.add(generatePermissionInfo(p, flags)); 3342 } 3343 } else { 3344 if (p.perm != null && group.equals(p.perm.info.group)) { 3345 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3346 } 3347 } 3348 } 3349 return new ParceledListSlice<>(out); 3350 } 3351 } 3352 3353 @Override 3354 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3355 // reader 3356 synchronized (mPackages) { 3357 return PackageParser.generatePermissionGroupInfo( 3358 mPermissionGroups.get(name), flags); 3359 } 3360 } 3361 3362 @Override 3363 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3364 // reader 3365 synchronized (mPackages) { 3366 final int N = mPermissionGroups.size(); 3367 ArrayList<PermissionGroupInfo> out 3368 = new ArrayList<PermissionGroupInfo>(N); 3369 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3370 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3371 } 3372 return new ParceledListSlice<>(out); 3373 } 3374 } 3375 3376 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3377 int userId) { 3378 if (!sUserManager.exists(userId)) return null; 3379 PackageSetting ps = mSettings.mPackages.get(packageName); 3380 if (ps != null) { 3381 if (ps.pkg == null) { 3382 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3383 if (pInfo != null) { 3384 return pInfo.applicationInfo; 3385 } 3386 return null; 3387 } 3388 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3389 ps.readUserState(userId), userId); 3390 } 3391 return null; 3392 } 3393 3394 @Override 3395 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3396 if (!sUserManager.exists(userId)) return null; 3397 flags = updateFlagsForApplication(flags, userId, packageName); 3398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3399 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3400 // writer 3401 synchronized (mPackages) { 3402 PackageParser.Package p = mPackages.get(packageName); 3403 if (DEBUG_PACKAGE_INFO) Log.v( 3404 TAG, "getApplicationInfo " + packageName 3405 + ": " + p); 3406 if (p != null) { 3407 PackageSetting ps = mSettings.mPackages.get(packageName); 3408 if (ps == null) return null; 3409 // Note: isEnabledLP() does not apply here - always return info 3410 return PackageParser.generateApplicationInfo( 3411 p, flags, ps.readUserState(userId), userId); 3412 } 3413 if ("android".equals(packageName)||"system".equals(packageName)) { 3414 return mAndroidApplication; 3415 } 3416 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3417 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3418 } 3419 } 3420 return null; 3421 } 3422 3423 @Override 3424 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3425 final IPackageDataObserver observer) { 3426 mContext.enforceCallingOrSelfPermission( 3427 android.Manifest.permission.CLEAR_APP_CACHE, null); 3428 // Queue up an async operation since clearing cache may take a little while. 3429 mHandler.post(new Runnable() { 3430 public void run() { 3431 mHandler.removeCallbacks(this); 3432 boolean success = true; 3433 synchronized (mInstallLock) { 3434 try { 3435 mInstaller.freeCache(volumeUuid, freeStorageSize); 3436 } catch (InstallerException e) { 3437 Slog.w(TAG, "Couldn't clear application caches: " + e); 3438 success = false; 3439 } 3440 } 3441 if (observer != null) { 3442 try { 3443 observer.onRemoveCompleted(null, success); 3444 } catch (RemoteException e) { 3445 Slog.w(TAG, "RemoveException when invoking call back"); 3446 } 3447 } 3448 } 3449 }); 3450 } 3451 3452 @Override 3453 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3454 final IntentSender pi) { 3455 mContext.enforceCallingOrSelfPermission( 3456 android.Manifest.permission.CLEAR_APP_CACHE, null); 3457 // Queue up an async operation since clearing cache may take a little while. 3458 mHandler.post(new Runnable() { 3459 public void run() { 3460 mHandler.removeCallbacks(this); 3461 boolean success = true; 3462 synchronized (mInstallLock) { 3463 try { 3464 mInstaller.freeCache(volumeUuid, freeStorageSize); 3465 } catch (InstallerException e) { 3466 Slog.w(TAG, "Couldn't clear application caches: " + e); 3467 success = false; 3468 } 3469 } 3470 if(pi != null) { 3471 try { 3472 // Callback via pending intent 3473 int code = success ? 1 : 0; 3474 pi.sendIntent(null, code, null, 3475 null, null); 3476 } catch (SendIntentException e1) { 3477 Slog.i(TAG, "Failed to send pending intent"); 3478 } 3479 } 3480 } 3481 }); 3482 } 3483 3484 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3485 synchronized (mInstallLock) { 3486 try { 3487 mInstaller.freeCache(volumeUuid, freeStorageSize); 3488 } catch (InstallerException e) { 3489 throw new IOException("Failed to free enough space", e); 3490 } 3491 } 3492 } 3493 3494 /** 3495 * Update given flags based on encryption status of current user. 3496 */ 3497 private int updateFlags(int flags, int userId) { 3498 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3499 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3500 // Caller expressed an explicit opinion about what encryption 3501 // aware/unaware components they want to see, so fall through and 3502 // give them what they want 3503 } else { 3504 // Caller expressed no opinion, so match based on user state 3505 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3506 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3507 } else { 3508 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3509 } 3510 } 3511 return flags; 3512 } 3513 3514 private UserManagerInternal getUserManagerInternal() { 3515 if (mUserManagerInternal == null) { 3516 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3517 } 3518 return mUserManagerInternal; 3519 } 3520 3521 /** 3522 * Update given flags when being used to request {@link PackageInfo}. 3523 */ 3524 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3525 boolean triaged = true; 3526 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3527 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3528 // Caller is asking for component details, so they'd better be 3529 // asking for specific encryption matching behavior, or be triaged 3530 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3531 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3532 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3533 triaged = false; 3534 } 3535 } 3536 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3537 | PackageManager.MATCH_SYSTEM_ONLY 3538 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3539 triaged = false; 3540 } 3541 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3542 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3543 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3544 } 3545 return updateFlags(flags, userId); 3546 } 3547 3548 /** 3549 * Update given flags when being used to request {@link ApplicationInfo}. 3550 */ 3551 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3552 return updateFlagsForPackage(flags, userId, cookie); 3553 } 3554 3555 /** 3556 * Update given flags when being used to request {@link ComponentInfo}. 3557 */ 3558 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3559 if (cookie instanceof Intent) { 3560 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3561 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3562 } 3563 } 3564 3565 boolean triaged = true; 3566 // Caller is asking for component details, so they'd better be 3567 // asking for specific encryption matching behavior, or be triaged 3568 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3569 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3570 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3571 triaged = false; 3572 } 3573 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3574 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3575 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3576 } 3577 3578 return updateFlags(flags, userId); 3579 } 3580 3581 /** 3582 * Update given flags when being used to request {@link ResolveInfo}. 3583 */ 3584 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3585 // Safe mode means we shouldn't match any third-party components 3586 if (mSafeMode) { 3587 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3588 } 3589 3590 return updateFlagsForComponent(flags, userId, cookie); 3591 } 3592 3593 @Override 3594 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3595 if (!sUserManager.exists(userId)) return null; 3596 flags = updateFlagsForComponent(flags, userId, component); 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3598 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3599 synchronized (mPackages) { 3600 PackageParser.Activity a = mActivities.mActivities.get(component); 3601 3602 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3603 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3604 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3605 if (ps == null) return null; 3606 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3607 userId); 3608 } 3609 if (mResolveComponentName.equals(component)) { 3610 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3611 new PackageUserState(), userId); 3612 } 3613 } 3614 return null; 3615 } 3616 3617 @Override 3618 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3619 String resolvedType) { 3620 synchronized (mPackages) { 3621 if (component.equals(mResolveComponentName)) { 3622 // The resolver supports EVERYTHING! 3623 return true; 3624 } 3625 PackageParser.Activity a = mActivities.mActivities.get(component); 3626 if (a == null) { 3627 return false; 3628 } 3629 for (int i=0; i<a.intents.size(); i++) { 3630 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3631 intent.getData(), intent.getCategories(), TAG) >= 0) { 3632 return true; 3633 } 3634 } 3635 return false; 3636 } 3637 } 3638 3639 @Override 3640 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3641 if (!sUserManager.exists(userId)) return null; 3642 flags = updateFlagsForComponent(flags, userId, component); 3643 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3644 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3645 synchronized (mPackages) { 3646 PackageParser.Activity a = mReceivers.mActivities.get(component); 3647 if (DEBUG_PACKAGE_INFO) Log.v( 3648 TAG, "getReceiverInfo " + component + ": " + a); 3649 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3650 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3651 if (ps == null) return null; 3652 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3653 userId); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3661 if (!sUserManager.exists(userId)) return null; 3662 flags = updateFlagsForComponent(flags, userId, component); 3663 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3664 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3665 synchronized (mPackages) { 3666 PackageParser.Service s = mServices.mServices.get(component); 3667 if (DEBUG_PACKAGE_INFO) Log.v( 3668 TAG, "getServiceInfo " + component + ": " + s); 3669 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3670 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3671 if (ps == null) return null; 3672 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3673 userId); 3674 } 3675 } 3676 return null; 3677 } 3678 3679 @Override 3680 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3681 if (!sUserManager.exists(userId)) return null; 3682 flags = updateFlagsForComponent(flags, userId, component); 3683 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3684 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3685 synchronized (mPackages) { 3686 PackageParser.Provider p = mProviders.mProviders.get(component); 3687 if (DEBUG_PACKAGE_INFO) Log.v( 3688 TAG, "getProviderInfo " + component + ": " + p); 3689 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3690 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3691 if (ps == null) return null; 3692 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3693 userId); 3694 } 3695 } 3696 return null; 3697 } 3698 3699 @Override 3700 public String[] getSystemSharedLibraryNames() { 3701 Set<String> libSet; 3702 synchronized (mPackages) { 3703 libSet = mSharedLibraries.keySet(); 3704 int size = libSet.size(); 3705 if (size > 0) { 3706 String[] libs = new String[size]; 3707 libSet.toArray(libs); 3708 return libs; 3709 } 3710 } 3711 return null; 3712 } 3713 3714 @Override 3715 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3716 synchronized (mPackages) { 3717 return mServicesSystemSharedLibraryPackageName; 3718 } 3719 } 3720 3721 @Override 3722 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3723 synchronized (mPackages) { 3724 return mSharedSystemSharedLibraryPackageName; 3725 } 3726 } 3727 3728 @Override 3729 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3730 synchronized (mPackages) { 3731 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3732 3733 final FeatureInfo fi = new FeatureInfo(); 3734 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3735 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3736 res.add(fi); 3737 3738 return new ParceledListSlice<>(res); 3739 } 3740 } 3741 3742 @Override 3743 public boolean hasSystemFeature(String name, int version) { 3744 synchronized (mPackages) { 3745 final FeatureInfo feat = mAvailableFeatures.get(name); 3746 if (feat == null) { 3747 return false; 3748 } else { 3749 return feat.version >= version; 3750 } 3751 } 3752 } 3753 3754 @Override 3755 public int checkPermission(String permName, String pkgName, int userId) { 3756 if (!sUserManager.exists(userId)) { 3757 return PackageManager.PERMISSION_DENIED; 3758 } 3759 3760 synchronized (mPackages) { 3761 final PackageParser.Package p = mPackages.get(pkgName); 3762 if (p != null && p.mExtras != null) { 3763 final PackageSetting ps = (PackageSetting) p.mExtras; 3764 final PermissionsState permissionsState = ps.getPermissionsState(); 3765 if (permissionsState.hasPermission(permName, userId)) { 3766 return PackageManager.PERMISSION_GRANTED; 3767 } 3768 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3769 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3770 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3771 return PackageManager.PERMISSION_GRANTED; 3772 } 3773 } 3774 } 3775 3776 return PackageManager.PERMISSION_DENIED; 3777 } 3778 3779 @Override 3780 public int checkUidPermission(String permName, int uid) { 3781 final int userId = UserHandle.getUserId(uid); 3782 3783 if (!sUserManager.exists(userId)) { 3784 return PackageManager.PERMISSION_DENIED; 3785 } 3786 3787 synchronized (mPackages) { 3788 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3789 if (obj != null) { 3790 final SettingBase ps = (SettingBase) obj; 3791 final PermissionsState permissionsState = ps.getPermissionsState(); 3792 if (permissionsState.hasPermission(permName, userId)) { 3793 return PackageManager.PERMISSION_GRANTED; 3794 } 3795 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3796 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3797 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3798 return PackageManager.PERMISSION_GRANTED; 3799 } 3800 } else { 3801 ArraySet<String> perms = mSystemPermissions.get(uid); 3802 if (perms != null) { 3803 if (perms.contains(permName)) { 3804 return PackageManager.PERMISSION_GRANTED; 3805 } 3806 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3807 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3808 return PackageManager.PERMISSION_GRANTED; 3809 } 3810 } 3811 } 3812 } 3813 3814 return PackageManager.PERMISSION_DENIED; 3815 } 3816 3817 @Override 3818 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3819 if (UserHandle.getCallingUserId() != userId) { 3820 mContext.enforceCallingPermission( 3821 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3822 "isPermissionRevokedByPolicy for user " + userId); 3823 } 3824 3825 if (checkPermission(permission, packageName, userId) 3826 == PackageManager.PERMISSION_GRANTED) { 3827 return false; 3828 } 3829 3830 final long identity = Binder.clearCallingIdentity(); 3831 try { 3832 final int flags = getPermissionFlags(permission, packageName, userId); 3833 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3834 } finally { 3835 Binder.restoreCallingIdentity(identity); 3836 } 3837 } 3838 3839 @Override 3840 public String getPermissionControllerPackageName() { 3841 synchronized (mPackages) { 3842 return mRequiredInstallerPackage; 3843 } 3844 } 3845 3846 /** 3847 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3848 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3849 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3850 * @param message the message to log on security exception 3851 */ 3852 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3853 boolean checkShell, String message) { 3854 if (userId < 0) { 3855 throw new IllegalArgumentException("Invalid userId " + userId); 3856 } 3857 if (checkShell) { 3858 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3859 } 3860 if (userId == UserHandle.getUserId(callingUid)) return; 3861 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3862 if (requireFullPermission) { 3863 mContext.enforceCallingOrSelfPermission( 3864 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3865 } else { 3866 try { 3867 mContext.enforceCallingOrSelfPermission( 3868 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3869 } catch (SecurityException se) { 3870 mContext.enforceCallingOrSelfPermission( 3871 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3872 } 3873 } 3874 } 3875 } 3876 3877 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3878 if (callingUid == Process.SHELL_UID) { 3879 if (userHandle >= 0 3880 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3881 throw new SecurityException("Shell does not have permission to access user " 3882 + userHandle); 3883 } else if (userHandle < 0) { 3884 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3885 + Debug.getCallers(3)); 3886 } 3887 } 3888 } 3889 3890 private BasePermission findPermissionTreeLP(String permName) { 3891 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3892 if (permName.startsWith(bp.name) && 3893 permName.length() > bp.name.length() && 3894 permName.charAt(bp.name.length()) == '.') { 3895 return bp; 3896 } 3897 } 3898 return null; 3899 } 3900 3901 private BasePermission checkPermissionTreeLP(String permName) { 3902 if (permName != null) { 3903 BasePermission bp = findPermissionTreeLP(permName); 3904 if (bp != null) { 3905 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3906 return bp; 3907 } 3908 throw new SecurityException("Calling uid " 3909 + Binder.getCallingUid() 3910 + " is not allowed to add to permission tree " 3911 + bp.name + " owned by uid " + bp.uid); 3912 } 3913 } 3914 throw new SecurityException("No permission tree found for " + permName); 3915 } 3916 3917 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3918 if (s1 == null) { 3919 return s2 == null; 3920 } 3921 if (s2 == null) { 3922 return false; 3923 } 3924 if (s1.getClass() != s2.getClass()) { 3925 return false; 3926 } 3927 return s1.equals(s2); 3928 } 3929 3930 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3931 if (pi1.icon != pi2.icon) return false; 3932 if (pi1.logo != pi2.logo) return false; 3933 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3934 if (!compareStrings(pi1.name, pi2.name)) return false; 3935 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3936 // We'll take care of setting this one. 3937 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3938 // These are not currently stored in settings. 3939 //if (!compareStrings(pi1.group, pi2.group)) return false; 3940 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3941 //if (pi1.labelRes != pi2.labelRes) return false; 3942 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3943 return true; 3944 } 3945 3946 int permissionInfoFootprint(PermissionInfo info) { 3947 int size = info.name.length(); 3948 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3949 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3950 return size; 3951 } 3952 3953 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3954 int size = 0; 3955 for (BasePermission perm : mSettings.mPermissions.values()) { 3956 if (perm.uid == tree.uid) { 3957 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3958 } 3959 } 3960 return size; 3961 } 3962 3963 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3964 // We calculate the max size of permissions defined by this uid and throw 3965 // if that plus the size of 'info' would exceed our stated maximum. 3966 if (tree.uid != Process.SYSTEM_UID) { 3967 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3968 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3969 throw new SecurityException("Permission tree size cap exceeded"); 3970 } 3971 } 3972 } 3973 3974 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3975 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3976 throw new SecurityException("Label must be specified in permission"); 3977 } 3978 BasePermission tree = checkPermissionTreeLP(info.name); 3979 BasePermission bp = mSettings.mPermissions.get(info.name); 3980 boolean added = bp == null; 3981 boolean changed = true; 3982 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3983 if (added) { 3984 enforcePermissionCapLocked(info, tree); 3985 bp = new BasePermission(info.name, tree.sourcePackage, 3986 BasePermission.TYPE_DYNAMIC); 3987 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3988 throw new SecurityException( 3989 "Not allowed to modify non-dynamic permission " 3990 + info.name); 3991 } else { 3992 if (bp.protectionLevel == fixedLevel 3993 && bp.perm.owner.equals(tree.perm.owner) 3994 && bp.uid == tree.uid 3995 && comparePermissionInfos(bp.perm.info, info)) { 3996 changed = false; 3997 } 3998 } 3999 bp.protectionLevel = fixedLevel; 4000 info = new PermissionInfo(info); 4001 info.protectionLevel = fixedLevel; 4002 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4003 bp.perm.info.packageName = tree.perm.info.packageName; 4004 bp.uid = tree.uid; 4005 if (added) { 4006 mSettings.mPermissions.put(info.name, bp); 4007 } 4008 if (changed) { 4009 if (!async) { 4010 mSettings.writeLPr(); 4011 } else { 4012 scheduleWriteSettingsLocked(); 4013 } 4014 } 4015 return added; 4016 } 4017 4018 @Override 4019 public boolean addPermission(PermissionInfo info) { 4020 synchronized (mPackages) { 4021 return addPermissionLocked(info, false); 4022 } 4023 } 4024 4025 @Override 4026 public boolean addPermissionAsync(PermissionInfo info) { 4027 synchronized (mPackages) { 4028 return addPermissionLocked(info, true); 4029 } 4030 } 4031 4032 @Override 4033 public void removePermission(String name) { 4034 synchronized (mPackages) { 4035 checkPermissionTreeLP(name); 4036 BasePermission bp = mSettings.mPermissions.get(name); 4037 if (bp != null) { 4038 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4039 throw new SecurityException( 4040 "Not allowed to modify non-dynamic permission " 4041 + name); 4042 } 4043 mSettings.mPermissions.remove(name); 4044 mSettings.writeLPr(); 4045 } 4046 } 4047 } 4048 4049 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4050 BasePermission bp) { 4051 int index = pkg.requestedPermissions.indexOf(bp.name); 4052 if (index == -1) { 4053 throw new SecurityException("Package " + pkg.packageName 4054 + " has not requested permission " + bp.name); 4055 } 4056 if (!bp.isRuntime() && !bp.isDevelopment()) { 4057 throw new SecurityException("Permission " + bp.name 4058 + " is not a changeable permission type"); 4059 } 4060 } 4061 4062 @Override 4063 public void grantRuntimePermission(String packageName, String name, final int userId) { 4064 if (!sUserManager.exists(userId)) { 4065 Log.e(TAG, "No such user:" + userId); 4066 return; 4067 } 4068 4069 mContext.enforceCallingOrSelfPermission( 4070 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4071 "grantRuntimePermission"); 4072 4073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4074 true /* requireFullPermission */, true /* checkShell */, 4075 "grantRuntimePermission"); 4076 4077 final int uid; 4078 final SettingBase sb; 4079 4080 synchronized (mPackages) { 4081 final PackageParser.Package pkg = mPackages.get(packageName); 4082 if (pkg == null) { 4083 throw new IllegalArgumentException("Unknown package: " + packageName); 4084 } 4085 4086 final BasePermission bp = mSettings.mPermissions.get(name); 4087 if (bp == null) { 4088 throw new IllegalArgumentException("Unknown permission: " + name); 4089 } 4090 4091 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4092 4093 // If a permission review is required for legacy apps we represent 4094 // their permissions as always granted runtime ones since we need 4095 // to keep the review required permission flag per user while an 4096 // install permission's state is shared across all users. 4097 if (Build.PERMISSIONS_REVIEW_REQUIRED 4098 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4099 && bp.isRuntime()) { 4100 return; 4101 } 4102 4103 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4104 sb = (SettingBase) pkg.mExtras; 4105 if (sb == null) { 4106 throw new IllegalArgumentException("Unknown package: " + packageName); 4107 } 4108 4109 final PermissionsState permissionsState = sb.getPermissionsState(); 4110 4111 final int flags = permissionsState.getPermissionFlags(name, userId); 4112 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4113 throw new SecurityException("Cannot grant system fixed permission " 4114 + name + " for package " + packageName); 4115 } 4116 4117 if (bp.isDevelopment()) { 4118 // Development permissions must be handled specially, since they are not 4119 // normal runtime permissions. For now they apply to all users. 4120 if (permissionsState.grantInstallPermission(bp) != 4121 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4122 scheduleWriteSettingsLocked(); 4123 } 4124 return; 4125 } 4126 4127 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4128 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4129 return; 4130 } 4131 4132 final int result = permissionsState.grantRuntimePermission(bp, userId); 4133 switch (result) { 4134 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4135 return; 4136 } 4137 4138 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4139 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4140 mHandler.post(new Runnable() { 4141 @Override 4142 public void run() { 4143 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4144 } 4145 }); 4146 } 4147 break; 4148 } 4149 4150 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4151 4152 // Not critical if that is lost - app has to request again. 4153 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4154 } 4155 4156 // Only need to do this if user is initialized. Otherwise it's a new user 4157 // and there are no processes running as the user yet and there's no need 4158 // to make an expensive call to remount processes for the changed permissions. 4159 if (READ_EXTERNAL_STORAGE.equals(name) 4160 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4161 final long token = Binder.clearCallingIdentity(); 4162 try { 4163 if (sUserManager.isInitialized(userId)) { 4164 MountServiceInternal mountServiceInternal = LocalServices.getService( 4165 MountServiceInternal.class); 4166 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4167 } 4168 } finally { 4169 Binder.restoreCallingIdentity(token); 4170 } 4171 } 4172 } 4173 4174 @Override 4175 public void revokeRuntimePermission(String packageName, String name, int userId) { 4176 if (!sUserManager.exists(userId)) { 4177 Log.e(TAG, "No such user:" + userId); 4178 return; 4179 } 4180 4181 mContext.enforceCallingOrSelfPermission( 4182 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4183 "revokeRuntimePermission"); 4184 4185 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4186 true /* requireFullPermission */, true /* checkShell */, 4187 "revokeRuntimePermission"); 4188 4189 final int appId; 4190 4191 synchronized (mPackages) { 4192 final PackageParser.Package pkg = mPackages.get(packageName); 4193 if (pkg == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final BasePermission bp = mSettings.mPermissions.get(name); 4198 if (bp == null) { 4199 throw new IllegalArgumentException("Unknown permission: " + name); 4200 } 4201 4202 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4203 4204 // If a permission review is required for legacy apps we represent 4205 // their permissions as always granted runtime ones since we need 4206 // to keep the review required permission flag per user while an 4207 // install permission's state is shared across all users. 4208 if (Build.PERMISSIONS_REVIEW_REQUIRED 4209 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4210 && bp.isRuntime()) { 4211 return; 4212 } 4213 4214 SettingBase sb = (SettingBase) pkg.mExtras; 4215 if (sb == null) { 4216 throw new IllegalArgumentException("Unknown package: " + packageName); 4217 } 4218 4219 final PermissionsState permissionsState = sb.getPermissionsState(); 4220 4221 final int flags = permissionsState.getPermissionFlags(name, userId); 4222 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4223 throw new SecurityException("Cannot revoke system fixed permission " 4224 + name + " for package " + packageName); 4225 } 4226 4227 if (bp.isDevelopment()) { 4228 // Development permissions must be handled specially, since they are not 4229 // normal runtime permissions. For now they apply to all users. 4230 if (permissionsState.revokeInstallPermission(bp) != 4231 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4232 scheduleWriteSettingsLocked(); 4233 } 4234 return; 4235 } 4236 4237 if (permissionsState.revokeRuntimePermission(bp, userId) == 4238 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4239 return; 4240 } 4241 4242 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4243 4244 // Critical, after this call app should never have the permission. 4245 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4246 4247 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4248 } 4249 4250 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4251 } 4252 4253 @Override 4254 public void resetRuntimePermissions() { 4255 mContext.enforceCallingOrSelfPermission( 4256 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4257 "revokeRuntimePermission"); 4258 4259 int callingUid = Binder.getCallingUid(); 4260 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4261 mContext.enforceCallingOrSelfPermission( 4262 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4263 "resetRuntimePermissions"); 4264 } 4265 4266 synchronized (mPackages) { 4267 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4268 for (int userId : UserManagerService.getInstance().getUserIds()) { 4269 final int packageCount = mPackages.size(); 4270 for (int i = 0; i < packageCount; i++) { 4271 PackageParser.Package pkg = mPackages.valueAt(i); 4272 if (!(pkg.mExtras instanceof PackageSetting)) { 4273 continue; 4274 } 4275 PackageSetting ps = (PackageSetting) pkg.mExtras; 4276 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4277 } 4278 } 4279 } 4280 } 4281 4282 @Override 4283 public int getPermissionFlags(String name, String packageName, int userId) { 4284 if (!sUserManager.exists(userId)) { 4285 return 0; 4286 } 4287 4288 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4289 4290 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4291 true /* requireFullPermission */, false /* checkShell */, 4292 "getPermissionFlags"); 4293 4294 synchronized (mPackages) { 4295 final PackageParser.Package pkg = mPackages.get(packageName); 4296 if (pkg == null) { 4297 return 0; 4298 } 4299 4300 final BasePermission bp = mSettings.mPermissions.get(name); 4301 if (bp == null) { 4302 return 0; 4303 } 4304 4305 SettingBase sb = (SettingBase) pkg.mExtras; 4306 if (sb == null) { 4307 return 0; 4308 } 4309 4310 PermissionsState permissionsState = sb.getPermissionsState(); 4311 return permissionsState.getPermissionFlags(name, userId); 4312 } 4313 } 4314 4315 @Override 4316 public void updatePermissionFlags(String name, String packageName, int flagMask, 4317 int flagValues, int userId) { 4318 if (!sUserManager.exists(userId)) { 4319 return; 4320 } 4321 4322 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4323 4324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4325 true /* requireFullPermission */, true /* checkShell */, 4326 "updatePermissionFlags"); 4327 4328 // Only the system can change these flags and nothing else. 4329 if (getCallingUid() != Process.SYSTEM_UID) { 4330 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4331 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4332 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4333 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4334 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4335 } 4336 4337 synchronized (mPackages) { 4338 final PackageParser.Package pkg = mPackages.get(packageName); 4339 if (pkg == null) { 4340 throw new IllegalArgumentException("Unknown package: " + packageName); 4341 } 4342 4343 final BasePermission bp = mSettings.mPermissions.get(name); 4344 if (bp == null) { 4345 throw new IllegalArgumentException("Unknown permission: " + name); 4346 } 4347 4348 SettingBase sb = (SettingBase) pkg.mExtras; 4349 if (sb == null) { 4350 throw new IllegalArgumentException("Unknown package: " + packageName); 4351 } 4352 4353 PermissionsState permissionsState = sb.getPermissionsState(); 4354 4355 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4356 4357 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4358 // Install and runtime permissions are stored in different places, 4359 // so figure out what permission changed and persist the change. 4360 if (permissionsState.getInstallPermissionState(name) != null) { 4361 scheduleWriteSettingsLocked(); 4362 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4363 || hadState) { 4364 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4365 } 4366 } 4367 } 4368 } 4369 4370 /** 4371 * Update the permission flags for all packages and runtime permissions of a user in order 4372 * to allow device or profile owner to remove POLICY_FIXED. 4373 */ 4374 @Override 4375 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4376 if (!sUserManager.exists(userId)) { 4377 return; 4378 } 4379 4380 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4381 4382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4383 true /* requireFullPermission */, true /* checkShell */, 4384 "updatePermissionFlagsForAllApps"); 4385 4386 // Only the system can change system fixed flags. 4387 if (getCallingUid() != Process.SYSTEM_UID) { 4388 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4389 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4390 } 4391 4392 synchronized (mPackages) { 4393 boolean changed = false; 4394 final int packageCount = mPackages.size(); 4395 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4396 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4397 SettingBase sb = (SettingBase) pkg.mExtras; 4398 if (sb == null) { 4399 continue; 4400 } 4401 PermissionsState permissionsState = sb.getPermissionsState(); 4402 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4403 userId, flagMask, flagValues); 4404 } 4405 if (changed) { 4406 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4407 } 4408 } 4409 } 4410 4411 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4412 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4413 != PackageManager.PERMISSION_GRANTED 4414 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4415 != PackageManager.PERMISSION_GRANTED) { 4416 throw new SecurityException(message + " requires " 4417 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4418 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4419 } 4420 } 4421 4422 @Override 4423 public boolean shouldShowRequestPermissionRationale(String permissionName, 4424 String packageName, int userId) { 4425 if (UserHandle.getCallingUserId() != userId) { 4426 mContext.enforceCallingPermission( 4427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4428 "canShowRequestPermissionRationale for user " + userId); 4429 } 4430 4431 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4432 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4433 return false; 4434 } 4435 4436 if (checkPermission(permissionName, packageName, userId) 4437 == PackageManager.PERMISSION_GRANTED) { 4438 return false; 4439 } 4440 4441 final int flags; 4442 4443 final long identity = Binder.clearCallingIdentity(); 4444 try { 4445 flags = getPermissionFlags(permissionName, 4446 packageName, userId); 4447 } finally { 4448 Binder.restoreCallingIdentity(identity); 4449 } 4450 4451 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4452 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4453 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4454 4455 if ((flags & fixedFlags) != 0) { 4456 return false; 4457 } 4458 4459 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4460 } 4461 4462 @Override 4463 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4464 mContext.enforceCallingOrSelfPermission( 4465 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4466 "addOnPermissionsChangeListener"); 4467 4468 synchronized (mPackages) { 4469 mOnPermissionChangeListeners.addListenerLocked(listener); 4470 } 4471 } 4472 4473 @Override 4474 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4475 synchronized (mPackages) { 4476 mOnPermissionChangeListeners.removeListenerLocked(listener); 4477 } 4478 } 4479 4480 @Override 4481 public boolean isProtectedBroadcast(String actionName) { 4482 synchronized (mPackages) { 4483 if (mProtectedBroadcasts.contains(actionName)) { 4484 return true; 4485 } else if (actionName != null) { 4486 // TODO: remove these terrible hacks 4487 if (actionName.startsWith("android.net.netmon.lingerExpired") 4488 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4489 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4490 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4491 return true; 4492 } 4493 } 4494 } 4495 return false; 4496 } 4497 4498 @Override 4499 public int checkSignatures(String pkg1, String pkg2) { 4500 synchronized (mPackages) { 4501 final PackageParser.Package p1 = mPackages.get(pkg1); 4502 final PackageParser.Package p2 = mPackages.get(pkg2); 4503 if (p1 == null || p1.mExtras == null 4504 || p2 == null || p2.mExtras == null) { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 return compareSignatures(p1.mSignatures, p2.mSignatures); 4508 } 4509 } 4510 4511 @Override 4512 public int checkUidSignatures(int uid1, int uid2) { 4513 // Map to base uids. 4514 uid1 = UserHandle.getAppId(uid1); 4515 uid2 = UserHandle.getAppId(uid2); 4516 // reader 4517 synchronized (mPackages) { 4518 Signature[] s1; 4519 Signature[] s2; 4520 Object obj = mSettings.getUserIdLPr(uid1); 4521 if (obj != null) { 4522 if (obj instanceof SharedUserSetting) { 4523 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4524 } else if (obj instanceof PackageSetting) { 4525 s1 = ((PackageSetting)obj).signatures.mSignatures; 4526 } else { 4527 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4528 } 4529 } else { 4530 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4531 } 4532 obj = mSettings.getUserIdLPr(uid2); 4533 if (obj != null) { 4534 if (obj instanceof SharedUserSetting) { 4535 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4536 } else if (obj instanceof PackageSetting) { 4537 s2 = ((PackageSetting)obj).signatures.mSignatures; 4538 } else { 4539 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4540 } 4541 } else { 4542 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4543 } 4544 return compareSignatures(s1, s2); 4545 } 4546 } 4547 4548 /** 4549 * This method should typically only be used when granting or revoking 4550 * permissions, since the app may immediately restart after this call. 4551 * <p> 4552 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4553 * guard your work against the app being relaunched. 4554 */ 4555 private void killUid(int appId, int userId, String reason) { 4556 final long identity = Binder.clearCallingIdentity(); 4557 try { 4558 IActivityManager am = ActivityManagerNative.getDefault(); 4559 if (am != null) { 4560 try { 4561 am.killUid(appId, userId, reason); 4562 } catch (RemoteException e) { 4563 /* ignore - same process */ 4564 } 4565 } 4566 } finally { 4567 Binder.restoreCallingIdentity(identity); 4568 } 4569 } 4570 4571 /** 4572 * Compares two sets of signatures. Returns: 4573 * <br /> 4574 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4575 * <br /> 4576 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4577 * <br /> 4578 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4579 * <br /> 4580 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4581 * <br /> 4582 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4583 */ 4584 static int compareSignatures(Signature[] s1, Signature[] s2) { 4585 if (s1 == null) { 4586 return s2 == null 4587 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4588 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4589 } 4590 4591 if (s2 == null) { 4592 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4593 } 4594 4595 if (s1.length != s2.length) { 4596 return PackageManager.SIGNATURE_NO_MATCH; 4597 } 4598 4599 // Since both signature sets are of size 1, we can compare without HashSets. 4600 if (s1.length == 1) { 4601 return s1[0].equals(s2[0]) ? 4602 PackageManager.SIGNATURE_MATCH : 4603 PackageManager.SIGNATURE_NO_MATCH; 4604 } 4605 4606 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4607 for (Signature sig : s1) { 4608 set1.add(sig); 4609 } 4610 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4611 for (Signature sig : s2) { 4612 set2.add(sig); 4613 } 4614 // Make sure s2 contains all signatures in s1. 4615 if (set1.equals(set2)) { 4616 return PackageManager.SIGNATURE_MATCH; 4617 } 4618 return PackageManager.SIGNATURE_NO_MATCH; 4619 } 4620 4621 /** 4622 * If the database version for this type of package (internal storage or 4623 * external storage) is less than the version where package signatures 4624 * were updated, return true. 4625 */ 4626 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4627 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4628 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4629 } 4630 4631 /** 4632 * Used for backward compatibility to make sure any packages with 4633 * certificate chains get upgraded to the new style. {@code existingSigs} 4634 * will be in the old format (since they were stored on disk from before the 4635 * system upgrade) and {@code scannedSigs} will be in the newer format. 4636 */ 4637 private int compareSignaturesCompat(PackageSignatures existingSigs, 4638 PackageParser.Package scannedPkg) { 4639 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4640 return PackageManager.SIGNATURE_NO_MATCH; 4641 } 4642 4643 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4644 for (Signature sig : existingSigs.mSignatures) { 4645 existingSet.add(sig); 4646 } 4647 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4648 for (Signature sig : scannedPkg.mSignatures) { 4649 try { 4650 Signature[] chainSignatures = sig.getChainSignatures(); 4651 for (Signature chainSig : chainSignatures) { 4652 scannedCompatSet.add(chainSig); 4653 } 4654 } catch (CertificateEncodingException e) { 4655 scannedCompatSet.add(sig); 4656 } 4657 } 4658 /* 4659 * Make sure the expanded scanned set contains all signatures in the 4660 * existing one. 4661 */ 4662 if (scannedCompatSet.equals(existingSet)) { 4663 // Migrate the old signatures to the new scheme. 4664 existingSigs.assignSignatures(scannedPkg.mSignatures); 4665 // The new KeySets will be re-added later in the scanning process. 4666 synchronized (mPackages) { 4667 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4668 } 4669 return PackageManager.SIGNATURE_MATCH; 4670 } 4671 return PackageManager.SIGNATURE_NO_MATCH; 4672 } 4673 4674 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4675 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4676 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4677 } 4678 4679 private int compareSignaturesRecover(PackageSignatures existingSigs, 4680 PackageParser.Package scannedPkg) { 4681 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4682 return PackageManager.SIGNATURE_NO_MATCH; 4683 } 4684 4685 String msg = null; 4686 try { 4687 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4688 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4689 + scannedPkg.packageName); 4690 return PackageManager.SIGNATURE_MATCH; 4691 } 4692 } catch (CertificateException e) { 4693 msg = e.getMessage(); 4694 } 4695 4696 logCriticalInfo(Log.INFO, 4697 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4698 return PackageManager.SIGNATURE_NO_MATCH; 4699 } 4700 4701 @Override 4702 public List<String> getAllPackages() { 4703 synchronized (mPackages) { 4704 return new ArrayList<String>(mPackages.keySet()); 4705 } 4706 } 4707 4708 @Override 4709 public String[] getPackagesForUid(int uid) { 4710 uid = UserHandle.getAppId(uid); 4711 // reader 4712 synchronized (mPackages) { 4713 Object obj = mSettings.getUserIdLPr(uid); 4714 if (obj instanceof SharedUserSetting) { 4715 final SharedUserSetting sus = (SharedUserSetting) obj; 4716 final int N = sus.packages.size(); 4717 final String[] res = new String[N]; 4718 final Iterator<PackageSetting> it = sus.packages.iterator(); 4719 int i = 0; 4720 while (it.hasNext()) { 4721 res[i++] = it.next().name; 4722 } 4723 return res; 4724 } else if (obj instanceof PackageSetting) { 4725 final PackageSetting ps = (PackageSetting) obj; 4726 return new String[] { ps.name }; 4727 } 4728 } 4729 return null; 4730 } 4731 4732 @Override 4733 public String getNameForUid(int uid) { 4734 // reader 4735 synchronized (mPackages) { 4736 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4737 if (obj instanceof SharedUserSetting) { 4738 final SharedUserSetting sus = (SharedUserSetting) obj; 4739 return sus.name + ":" + sus.userId; 4740 } else if (obj instanceof PackageSetting) { 4741 final PackageSetting ps = (PackageSetting) obj; 4742 return ps.name; 4743 } 4744 } 4745 return null; 4746 } 4747 4748 @Override 4749 public int getUidForSharedUser(String sharedUserName) { 4750 if(sharedUserName == null) { 4751 return -1; 4752 } 4753 // reader 4754 synchronized (mPackages) { 4755 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4756 if (suid == null) { 4757 return -1; 4758 } 4759 return suid.userId; 4760 } 4761 } 4762 4763 @Override 4764 public int getFlagsForUid(int uid) { 4765 synchronized (mPackages) { 4766 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4767 if (obj instanceof SharedUserSetting) { 4768 final SharedUserSetting sus = (SharedUserSetting) obj; 4769 return sus.pkgFlags; 4770 } else if (obj instanceof PackageSetting) { 4771 final PackageSetting ps = (PackageSetting) obj; 4772 return ps.pkgFlags; 4773 } 4774 } 4775 return 0; 4776 } 4777 4778 @Override 4779 public int getPrivateFlagsForUid(int uid) { 4780 synchronized (mPackages) { 4781 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4782 if (obj instanceof SharedUserSetting) { 4783 final SharedUserSetting sus = (SharedUserSetting) obj; 4784 return sus.pkgPrivateFlags; 4785 } else if (obj instanceof PackageSetting) { 4786 final PackageSetting ps = (PackageSetting) obj; 4787 return ps.pkgPrivateFlags; 4788 } 4789 } 4790 return 0; 4791 } 4792 4793 @Override 4794 public boolean isUidPrivileged(int uid) { 4795 uid = UserHandle.getAppId(uid); 4796 // reader 4797 synchronized (mPackages) { 4798 Object obj = mSettings.getUserIdLPr(uid); 4799 if (obj instanceof SharedUserSetting) { 4800 final SharedUserSetting sus = (SharedUserSetting) obj; 4801 final Iterator<PackageSetting> it = sus.packages.iterator(); 4802 while (it.hasNext()) { 4803 if (it.next().isPrivileged()) { 4804 return true; 4805 } 4806 } 4807 } else if (obj instanceof PackageSetting) { 4808 final PackageSetting ps = (PackageSetting) obj; 4809 return ps.isPrivileged(); 4810 } 4811 } 4812 return false; 4813 } 4814 4815 @Override 4816 public String[] getAppOpPermissionPackages(String permissionName) { 4817 synchronized (mPackages) { 4818 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4819 if (pkgs == null) { 4820 return null; 4821 } 4822 return pkgs.toArray(new String[pkgs.size()]); 4823 } 4824 } 4825 4826 @Override 4827 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4828 int flags, int userId) { 4829 try { 4830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4831 4832 if (!sUserManager.exists(userId)) return null; 4833 flags = updateFlagsForResolve(flags, userId, intent); 4834 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4835 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4836 4837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4838 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4839 flags, userId); 4840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4841 4842 final ResolveInfo bestChoice = 4843 chooseBestActivity(intent, resolvedType, flags, query, userId); 4844 4845 if (isEphemeralAllowed(intent, query, userId)) { 4846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4847 final EphemeralResolveInfo ai = 4848 getEphemeralResolveInfo(intent, resolvedType, userId); 4849 if (ai != null) { 4850 if (DEBUG_EPHEMERAL) { 4851 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4852 } 4853 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4854 bestChoice.ephemeralResolveInfo = ai; 4855 } 4856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4857 } 4858 return bestChoice; 4859 } finally { 4860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4861 } 4862 } 4863 4864 @Override 4865 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4866 IntentFilter filter, int match, ComponentName activity) { 4867 final int userId = UserHandle.getCallingUserId(); 4868 if (DEBUG_PREFERRED) { 4869 Log.v(TAG, "setLastChosenActivity intent=" + intent 4870 + " resolvedType=" + resolvedType 4871 + " flags=" + flags 4872 + " filter=" + filter 4873 + " match=" + match 4874 + " activity=" + activity); 4875 filter.dump(new PrintStreamPrinter(System.out), " "); 4876 } 4877 intent.setComponent(null); 4878 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4879 userId); 4880 // Find any earlier preferred or last chosen entries and nuke them 4881 findPreferredActivity(intent, resolvedType, 4882 flags, query, 0, false, true, false, userId); 4883 // Add the new activity as the last chosen for this filter 4884 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4885 "Setting last chosen"); 4886 } 4887 4888 @Override 4889 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4890 final int userId = UserHandle.getCallingUserId(); 4891 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4892 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4893 userId); 4894 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4895 false, false, false, userId); 4896 } 4897 4898 4899 private boolean isEphemeralAllowed( 4900 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4901 // Short circuit and return early if possible. 4902 if (DISABLE_EPHEMERAL_APPS) { 4903 return false; 4904 } 4905 final int callingUser = UserHandle.getCallingUserId(); 4906 if (callingUser != UserHandle.USER_SYSTEM) { 4907 return false; 4908 } 4909 if (mEphemeralResolverConnection == null) { 4910 return false; 4911 } 4912 if (intent.getComponent() != null) { 4913 return false; 4914 } 4915 if (intent.getPackage() != null) { 4916 return false; 4917 } 4918 final boolean isWebUri = hasWebURI(intent); 4919 if (!isWebUri) { 4920 return false; 4921 } 4922 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4923 synchronized (mPackages) { 4924 final int count = resolvedActivites.size(); 4925 for (int n = 0; n < count; n++) { 4926 ResolveInfo info = resolvedActivites.get(n); 4927 String packageName = info.activityInfo.packageName; 4928 PackageSetting ps = mSettings.mPackages.get(packageName); 4929 if (ps != null) { 4930 // Try to get the status from User settings first 4931 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4932 int status = (int) (packedStatus >> 32); 4933 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4934 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4935 if (DEBUG_EPHEMERAL) { 4936 Slog.v(TAG, "DENY ephemeral apps;" 4937 + " pkg: " + packageName + ", status: " + status); 4938 } 4939 return false; 4940 } 4941 } 4942 } 4943 } 4944 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4945 return true; 4946 } 4947 4948 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4949 int userId) { 4950 MessageDigest digest = null; 4951 try { 4952 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4953 } catch (NoSuchAlgorithmException e) { 4954 // If we can't create a digest, ignore ephemeral apps. 4955 return null; 4956 } 4957 4958 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4959 final byte[] digestBytes = digest.digest(hostBytes); 4960 int shaPrefix = 4961 digestBytes[0] << 24 4962 | digestBytes[1] << 16 4963 | digestBytes[2] << 8 4964 | digestBytes[3] << 0; 4965 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4966 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4967 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4968 // No hash prefix match; there are no ephemeral apps for this domain. 4969 return null; 4970 } 4971 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4972 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4973 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4974 continue; 4975 } 4976 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4977 // No filters; this should never happen. 4978 if (filters.isEmpty()) { 4979 continue; 4980 } 4981 // We have a domain match; resolve the filters to see if anything matches. 4982 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4983 for (int j = filters.size() - 1; j >= 0; --j) { 4984 final EphemeralResolveIntentInfo intentInfo = 4985 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4986 ephemeralResolver.addFilter(intentInfo); 4987 } 4988 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4989 intent, resolvedType, false /*defaultOnly*/, userId); 4990 if (!matchedResolveInfoList.isEmpty()) { 4991 return matchedResolveInfoList.get(0); 4992 } 4993 } 4994 // Hash or filter mis-match; no ephemeral apps for this domain. 4995 return null; 4996 } 4997 4998 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4999 int flags, List<ResolveInfo> query, int userId) { 5000 if (query != null) { 5001 final int N = query.size(); 5002 if (N == 1) { 5003 return query.get(0); 5004 } else if (N > 1) { 5005 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5006 // If there is more than one activity with the same priority, 5007 // then let the user decide between them. 5008 ResolveInfo r0 = query.get(0); 5009 ResolveInfo r1 = query.get(1); 5010 if (DEBUG_INTENT_MATCHING || debug) { 5011 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5012 + r1.activityInfo.name + "=" + r1.priority); 5013 } 5014 // If the first activity has a higher priority, or a different 5015 // default, then it is always desirable to pick it. 5016 if (r0.priority != r1.priority 5017 || r0.preferredOrder != r1.preferredOrder 5018 || r0.isDefault != r1.isDefault) { 5019 return query.get(0); 5020 } 5021 // If we have saved a preference for a preferred activity for 5022 // this Intent, use that. 5023 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5024 flags, query, r0.priority, true, false, debug, userId); 5025 if (ri != null) { 5026 return ri; 5027 } 5028 ri = new ResolveInfo(mResolveInfo); 5029 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5030 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5031 // If all of the options come from the same package, show the application's 5032 // label and icon instead of the generic resolver's. 5033 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5034 // and then throw away the ResolveInfo itself, meaning that the caller loses 5035 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5036 // a fallback for this case; we only set the target package's resources on 5037 // the ResolveInfo, not the ActivityInfo. 5038 final String intentPackage = intent.getPackage(); 5039 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5040 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5041 ri.resolvePackageName = intentPackage; 5042 if (userNeedsBadging(userId)) { 5043 ri.noResourceId = true; 5044 } else { 5045 ri.icon = appi.icon; 5046 } 5047 ri.iconResourceId = appi.icon; 5048 ri.labelRes = appi.labelRes; 5049 } 5050 ri.activityInfo.applicationInfo = new ApplicationInfo( 5051 ri.activityInfo.applicationInfo); 5052 if (userId != 0) { 5053 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5054 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5055 } 5056 // Make sure that the resolver is displayable in car mode 5057 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5058 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5059 return ri; 5060 } 5061 } 5062 return null; 5063 } 5064 5065 /** 5066 * Return true if the given list is not empty and all of its contents have 5067 * an activityInfo with the given package name. 5068 */ 5069 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5070 if (ArrayUtils.isEmpty(list)) { 5071 return false; 5072 } 5073 for (int i = 0, N = list.size(); i < N; i++) { 5074 final ResolveInfo ri = list.get(i); 5075 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5076 if (ai == null || !packageName.equals(ai.packageName)) { 5077 return false; 5078 } 5079 } 5080 return true; 5081 } 5082 5083 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5084 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5085 final int N = query.size(); 5086 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5087 .get(userId); 5088 // Get the list of persistent preferred activities that handle the intent 5089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5090 List<PersistentPreferredActivity> pprefs = ppir != null 5091 ? ppir.queryIntent(intent, resolvedType, 5092 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5093 : null; 5094 if (pprefs != null && pprefs.size() > 0) { 5095 final int M = pprefs.size(); 5096 for (int i=0; i<M; i++) { 5097 final PersistentPreferredActivity ppa = pprefs.get(i); 5098 if (DEBUG_PREFERRED || debug) { 5099 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5100 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5101 + "\n component=" + ppa.mComponent); 5102 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5103 } 5104 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5105 flags | MATCH_DISABLED_COMPONENTS, userId); 5106 if (DEBUG_PREFERRED || debug) { 5107 Slog.v(TAG, "Found persistent preferred activity:"); 5108 if (ai != null) { 5109 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5110 } else { 5111 Slog.v(TAG, " null"); 5112 } 5113 } 5114 if (ai == null) { 5115 // This previously registered persistent preferred activity 5116 // component is no longer known. Ignore it and do NOT remove it. 5117 continue; 5118 } 5119 for (int j=0; j<N; j++) { 5120 final ResolveInfo ri = query.get(j); 5121 if (!ri.activityInfo.applicationInfo.packageName 5122 .equals(ai.applicationInfo.packageName)) { 5123 continue; 5124 } 5125 if (!ri.activityInfo.name.equals(ai.name)) { 5126 continue; 5127 } 5128 // Found a persistent preference that can handle the intent. 5129 if (DEBUG_PREFERRED || debug) { 5130 Slog.v(TAG, "Returning persistent preferred activity: " + 5131 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5132 } 5133 return ri; 5134 } 5135 } 5136 } 5137 return null; 5138 } 5139 5140 // TODO: handle preferred activities missing while user has amnesia 5141 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5142 List<ResolveInfo> query, int priority, boolean always, 5143 boolean removeMatches, boolean debug, int userId) { 5144 if (!sUserManager.exists(userId)) return null; 5145 flags = updateFlagsForResolve(flags, userId, intent); 5146 // writer 5147 synchronized (mPackages) { 5148 if (intent.getSelector() != null) { 5149 intent = intent.getSelector(); 5150 } 5151 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5152 5153 // Try to find a matching persistent preferred activity. 5154 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5155 debug, userId); 5156 5157 // If a persistent preferred activity matched, use it. 5158 if (pri != null) { 5159 return pri; 5160 } 5161 5162 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5163 // Get the list of preferred activities that handle the intent 5164 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5165 List<PreferredActivity> prefs = pir != null 5166 ? pir.queryIntent(intent, resolvedType, 5167 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5168 : null; 5169 if (prefs != null && prefs.size() > 0) { 5170 boolean changed = false; 5171 try { 5172 // First figure out how good the original match set is. 5173 // We will only allow preferred activities that came 5174 // from the same match quality. 5175 int match = 0; 5176 5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5178 5179 final int N = query.size(); 5180 for (int j=0; j<N; j++) { 5181 final ResolveInfo ri = query.get(j); 5182 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5183 + ": 0x" + Integer.toHexString(match)); 5184 if (ri.match > match) { 5185 match = ri.match; 5186 } 5187 } 5188 5189 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5190 + Integer.toHexString(match)); 5191 5192 match &= IntentFilter.MATCH_CATEGORY_MASK; 5193 final int M = prefs.size(); 5194 for (int i=0; i<M; i++) { 5195 final PreferredActivity pa = prefs.get(i); 5196 if (DEBUG_PREFERRED || debug) { 5197 Slog.v(TAG, "Checking PreferredActivity ds=" 5198 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5199 + "\n component=" + pa.mPref.mComponent); 5200 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5201 } 5202 if (pa.mPref.mMatch != match) { 5203 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5204 + Integer.toHexString(pa.mPref.mMatch)); 5205 continue; 5206 } 5207 // If it's not an "always" type preferred activity and that's what we're 5208 // looking for, skip it. 5209 if (always && !pa.mPref.mAlways) { 5210 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5211 continue; 5212 } 5213 final ActivityInfo ai = getActivityInfo( 5214 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5215 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5216 userId); 5217 if (DEBUG_PREFERRED || debug) { 5218 Slog.v(TAG, "Found preferred activity:"); 5219 if (ai != null) { 5220 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5221 } else { 5222 Slog.v(TAG, " null"); 5223 } 5224 } 5225 if (ai == null) { 5226 // This previously registered preferred activity 5227 // component is no longer known. Most likely an update 5228 // to the app was installed and in the new version this 5229 // component no longer exists. Clean it up by removing 5230 // it from the preferred activities list, and skip it. 5231 Slog.w(TAG, "Removing dangling preferred activity: " 5232 + pa.mPref.mComponent); 5233 pir.removeFilter(pa); 5234 changed = true; 5235 continue; 5236 } 5237 for (int j=0; j<N; j++) { 5238 final ResolveInfo ri = query.get(j); 5239 if (!ri.activityInfo.applicationInfo.packageName 5240 .equals(ai.applicationInfo.packageName)) { 5241 continue; 5242 } 5243 if (!ri.activityInfo.name.equals(ai.name)) { 5244 continue; 5245 } 5246 5247 if (removeMatches) { 5248 pir.removeFilter(pa); 5249 changed = true; 5250 if (DEBUG_PREFERRED) { 5251 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5252 } 5253 break; 5254 } 5255 5256 // Okay we found a previously set preferred or last chosen app. 5257 // If the result set is different from when this 5258 // was created, we need to clear it and re-ask the 5259 // user their preference, if we're looking for an "always" type entry. 5260 if (always && !pa.mPref.sameSet(query)) { 5261 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5262 + intent + " type " + resolvedType); 5263 if (DEBUG_PREFERRED) { 5264 Slog.v(TAG, "Removing preferred activity since set changed " 5265 + pa.mPref.mComponent); 5266 } 5267 pir.removeFilter(pa); 5268 // Re-add the filter as a "last chosen" entry (!always) 5269 PreferredActivity lastChosen = new PreferredActivity( 5270 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5271 pir.addFilter(lastChosen); 5272 changed = true; 5273 return null; 5274 } 5275 5276 // Yay! Either the set matched or we're looking for the last chosen 5277 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5278 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5279 return ri; 5280 } 5281 } 5282 } finally { 5283 if (changed) { 5284 if (DEBUG_PREFERRED) { 5285 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5286 } 5287 scheduleWritePackageRestrictionsLocked(userId); 5288 } 5289 } 5290 } 5291 } 5292 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5293 return null; 5294 } 5295 5296 /* 5297 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5298 */ 5299 @Override 5300 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5301 int targetUserId) { 5302 mContext.enforceCallingOrSelfPermission( 5303 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5304 List<CrossProfileIntentFilter> matches = 5305 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5306 if (matches != null) { 5307 int size = matches.size(); 5308 for (int i = 0; i < size; i++) { 5309 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5310 } 5311 } 5312 if (hasWebURI(intent)) { 5313 // cross-profile app linking works only towards the parent. 5314 final UserInfo parent = getProfileParent(sourceUserId); 5315 synchronized(mPackages) { 5316 int flags = updateFlagsForResolve(0, parent.id, intent); 5317 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5318 intent, resolvedType, flags, sourceUserId, parent.id); 5319 return xpDomainInfo != null; 5320 } 5321 } 5322 return false; 5323 } 5324 5325 private UserInfo getProfileParent(int userId) { 5326 final long identity = Binder.clearCallingIdentity(); 5327 try { 5328 return sUserManager.getProfileParent(userId); 5329 } finally { 5330 Binder.restoreCallingIdentity(identity); 5331 } 5332 } 5333 5334 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5335 String resolvedType, int userId) { 5336 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5337 if (resolver != null) { 5338 return resolver.queryIntent(intent, resolvedType, false, userId); 5339 } 5340 return null; 5341 } 5342 5343 @Override 5344 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5345 String resolvedType, int flags, int userId) { 5346 try { 5347 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5348 5349 return new ParceledListSlice<>( 5350 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5351 } finally { 5352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5353 } 5354 } 5355 5356 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5357 String resolvedType, int flags, int userId) { 5358 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5359 flags = updateFlagsForResolve(flags, userId, intent); 5360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5361 false /* requireFullPermission */, false /* checkShell */, 5362 "query intent activities"); 5363 ComponentName comp = intent.getComponent(); 5364 if (comp == null) { 5365 if (intent.getSelector() != null) { 5366 intent = intent.getSelector(); 5367 comp = intent.getComponent(); 5368 } 5369 } 5370 5371 if (comp != null) { 5372 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5373 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5374 if (ai != null) { 5375 final ResolveInfo ri = new ResolveInfo(); 5376 ri.activityInfo = ai; 5377 list.add(ri); 5378 } 5379 return list; 5380 } 5381 5382 // reader 5383 synchronized (mPackages) { 5384 final String pkgName = intent.getPackage(); 5385 if (pkgName == null) { 5386 List<CrossProfileIntentFilter> matchingFilters = 5387 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5388 // Check for results that need to skip the current profile. 5389 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5390 resolvedType, flags, userId); 5391 if (xpResolveInfo != null) { 5392 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5393 result.add(xpResolveInfo); 5394 return filterIfNotSystemUser(result, userId); 5395 } 5396 5397 // Check for results in the current profile. 5398 List<ResolveInfo> result = mActivities.queryIntent( 5399 intent, resolvedType, flags, userId); 5400 result = filterIfNotSystemUser(result, userId); 5401 5402 // Check for cross profile results. 5403 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5404 xpResolveInfo = queryCrossProfileIntents( 5405 matchingFilters, intent, resolvedType, flags, userId, 5406 hasNonNegativePriorityResult); 5407 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5408 boolean isVisibleToUser = filterIfNotSystemUser( 5409 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5410 if (isVisibleToUser) { 5411 result.add(xpResolveInfo); 5412 Collections.sort(result, mResolvePrioritySorter); 5413 } 5414 } 5415 if (hasWebURI(intent)) { 5416 CrossProfileDomainInfo xpDomainInfo = null; 5417 final UserInfo parent = getProfileParent(userId); 5418 if (parent != null) { 5419 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5420 flags, userId, parent.id); 5421 } 5422 if (xpDomainInfo != null) { 5423 if (xpResolveInfo != null) { 5424 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5425 // in the result. 5426 result.remove(xpResolveInfo); 5427 } 5428 if (result.size() == 0) { 5429 result.add(xpDomainInfo.resolveInfo); 5430 return result; 5431 } 5432 } else if (result.size() <= 1) { 5433 return result; 5434 } 5435 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5436 xpDomainInfo, userId); 5437 Collections.sort(result, mResolvePrioritySorter); 5438 } 5439 return result; 5440 } 5441 final PackageParser.Package pkg = mPackages.get(pkgName); 5442 if (pkg != null) { 5443 return filterIfNotSystemUser( 5444 mActivities.queryIntentForPackage( 5445 intent, resolvedType, flags, pkg.activities, userId), 5446 userId); 5447 } 5448 return new ArrayList<ResolveInfo>(); 5449 } 5450 } 5451 5452 private static class CrossProfileDomainInfo { 5453 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5454 ResolveInfo resolveInfo; 5455 /* Best domain verification status of the activities found in the other profile */ 5456 int bestDomainVerificationStatus; 5457 } 5458 5459 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5460 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5461 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5462 sourceUserId)) { 5463 return null; 5464 } 5465 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5466 resolvedType, flags, parentUserId); 5467 5468 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5469 return null; 5470 } 5471 CrossProfileDomainInfo result = null; 5472 int size = resultTargetUser.size(); 5473 for (int i = 0; i < size; i++) { 5474 ResolveInfo riTargetUser = resultTargetUser.get(i); 5475 // Intent filter verification is only for filters that specify a host. So don't return 5476 // those that handle all web uris. 5477 if (riTargetUser.handleAllWebDataURI) { 5478 continue; 5479 } 5480 String packageName = riTargetUser.activityInfo.packageName; 5481 PackageSetting ps = mSettings.mPackages.get(packageName); 5482 if (ps == null) { 5483 continue; 5484 } 5485 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5486 int status = (int)(verificationState >> 32); 5487 if (result == null) { 5488 result = new CrossProfileDomainInfo(); 5489 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5490 sourceUserId, parentUserId); 5491 result.bestDomainVerificationStatus = status; 5492 } else { 5493 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5494 result.bestDomainVerificationStatus); 5495 } 5496 } 5497 // Don't consider matches with status NEVER across profiles. 5498 if (result != null && result.bestDomainVerificationStatus 5499 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5500 return null; 5501 } 5502 return result; 5503 } 5504 5505 /** 5506 * Verification statuses are ordered from the worse to the best, except for 5507 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5508 */ 5509 private int bestDomainVerificationStatus(int status1, int status2) { 5510 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5511 return status2; 5512 } 5513 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5514 return status1; 5515 } 5516 return (int) MathUtils.max(status1, status2); 5517 } 5518 5519 private boolean isUserEnabled(int userId) { 5520 long callingId = Binder.clearCallingIdentity(); 5521 try { 5522 UserInfo userInfo = sUserManager.getUserInfo(userId); 5523 return userInfo != null && userInfo.isEnabled(); 5524 } finally { 5525 Binder.restoreCallingIdentity(callingId); 5526 } 5527 } 5528 5529 /** 5530 * Filter out activities with systemUserOnly flag set, when current user is not System. 5531 * 5532 * @return filtered list 5533 */ 5534 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5535 if (userId == UserHandle.USER_SYSTEM) { 5536 return resolveInfos; 5537 } 5538 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5539 ResolveInfo info = resolveInfos.get(i); 5540 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5541 resolveInfos.remove(i); 5542 } 5543 } 5544 return resolveInfos; 5545 } 5546 5547 /** 5548 * @param resolveInfos list of resolve infos in descending priority order 5549 * @return if the list contains a resolve info with non-negative priority 5550 */ 5551 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5552 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5553 } 5554 5555 private static boolean hasWebURI(Intent intent) { 5556 if (intent.getData() == null) { 5557 return false; 5558 } 5559 final String scheme = intent.getScheme(); 5560 if (TextUtils.isEmpty(scheme)) { 5561 return false; 5562 } 5563 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5564 } 5565 5566 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5567 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5568 int userId) { 5569 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5570 5571 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5572 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5573 candidates.size()); 5574 } 5575 5576 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5577 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5578 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5579 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5580 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5581 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5582 5583 synchronized (mPackages) { 5584 final int count = candidates.size(); 5585 // First, try to use linked apps. Partition the candidates into four lists: 5586 // one for the final results, one for the "do not use ever", one for "undefined status" 5587 // and finally one for "browser app type". 5588 for (int n=0; n<count; n++) { 5589 ResolveInfo info = candidates.get(n); 5590 String packageName = info.activityInfo.packageName; 5591 PackageSetting ps = mSettings.mPackages.get(packageName); 5592 if (ps != null) { 5593 // Add to the special match all list (Browser use case) 5594 if (info.handleAllWebDataURI) { 5595 matchAllList.add(info); 5596 continue; 5597 } 5598 // Try to get the status from User settings first 5599 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5600 int status = (int)(packedStatus >> 32); 5601 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5602 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5603 if (DEBUG_DOMAIN_VERIFICATION) { 5604 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5605 + " : linkgen=" + linkGeneration); 5606 } 5607 // Use link-enabled generation as preferredOrder, i.e. 5608 // prefer newly-enabled over earlier-enabled. 5609 info.preferredOrder = linkGeneration; 5610 alwaysList.add(info); 5611 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5612 if (DEBUG_DOMAIN_VERIFICATION) { 5613 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5614 } 5615 neverList.add(info); 5616 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5617 if (DEBUG_DOMAIN_VERIFICATION) { 5618 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5619 } 5620 alwaysAskList.add(info); 5621 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5622 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5623 if (DEBUG_DOMAIN_VERIFICATION) { 5624 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5625 } 5626 undefinedList.add(info); 5627 } 5628 } 5629 } 5630 5631 // We'll want to include browser possibilities in a few cases 5632 boolean includeBrowser = false; 5633 5634 // First try to add the "always" resolution(s) for the current user, if any 5635 if (alwaysList.size() > 0) { 5636 result.addAll(alwaysList); 5637 } else { 5638 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5639 result.addAll(undefinedList); 5640 // Maybe add one for the other profile. 5641 if (xpDomainInfo != null && ( 5642 xpDomainInfo.bestDomainVerificationStatus 5643 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5644 result.add(xpDomainInfo.resolveInfo); 5645 } 5646 includeBrowser = true; 5647 } 5648 5649 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5650 // If there were 'always' entries their preferred order has been set, so we also 5651 // back that off to make the alternatives equivalent 5652 if (alwaysAskList.size() > 0) { 5653 for (ResolveInfo i : result) { 5654 i.preferredOrder = 0; 5655 } 5656 result.addAll(alwaysAskList); 5657 includeBrowser = true; 5658 } 5659 5660 if (includeBrowser) { 5661 // Also add browsers (all of them or only the default one) 5662 if (DEBUG_DOMAIN_VERIFICATION) { 5663 Slog.v(TAG, " ...including browsers in candidate set"); 5664 } 5665 if ((matchFlags & MATCH_ALL) != 0) { 5666 result.addAll(matchAllList); 5667 } else { 5668 // Browser/generic handling case. If there's a default browser, go straight 5669 // to that (but only if there is no other higher-priority match). 5670 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5671 int maxMatchPrio = 0; 5672 ResolveInfo defaultBrowserMatch = null; 5673 final int numCandidates = matchAllList.size(); 5674 for (int n = 0; n < numCandidates; n++) { 5675 ResolveInfo info = matchAllList.get(n); 5676 // track the highest overall match priority... 5677 if (info.priority > maxMatchPrio) { 5678 maxMatchPrio = info.priority; 5679 } 5680 // ...and the highest-priority default browser match 5681 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5682 if (defaultBrowserMatch == null 5683 || (defaultBrowserMatch.priority < info.priority)) { 5684 if (debug) { 5685 Slog.v(TAG, "Considering default browser match " + info); 5686 } 5687 defaultBrowserMatch = info; 5688 } 5689 } 5690 } 5691 if (defaultBrowserMatch != null 5692 && defaultBrowserMatch.priority >= maxMatchPrio 5693 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5694 { 5695 if (debug) { 5696 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5697 } 5698 result.add(defaultBrowserMatch); 5699 } else { 5700 result.addAll(matchAllList); 5701 } 5702 } 5703 5704 // If there is nothing selected, add all candidates and remove the ones that the user 5705 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5706 if (result.size() == 0) { 5707 result.addAll(candidates); 5708 result.removeAll(neverList); 5709 } 5710 } 5711 } 5712 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5713 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5714 result.size()); 5715 for (ResolveInfo info : result) { 5716 Slog.v(TAG, " + " + info.activityInfo); 5717 } 5718 } 5719 return result; 5720 } 5721 5722 // Returns a packed value as a long: 5723 // 5724 // high 'int'-sized word: link status: undefined/ask/never/always. 5725 // low 'int'-sized word: relative priority among 'always' results. 5726 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5727 long result = ps.getDomainVerificationStatusForUser(userId); 5728 // if none available, get the master status 5729 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5730 if (ps.getIntentFilterVerificationInfo() != null) { 5731 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5732 } 5733 } 5734 return result; 5735 } 5736 5737 private ResolveInfo querySkipCurrentProfileIntents( 5738 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5739 int flags, int sourceUserId) { 5740 if (matchingFilters != null) { 5741 int size = matchingFilters.size(); 5742 for (int i = 0; i < size; i ++) { 5743 CrossProfileIntentFilter filter = matchingFilters.get(i); 5744 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5745 // Checking if there are activities in the target user that can handle the 5746 // intent. 5747 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5748 resolvedType, flags, sourceUserId); 5749 if (resolveInfo != null) { 5750 return resolveInfo; 5751 } 5752 } 5753 } 5754 } 5755 return null; 5756 } 5757 5758 // Return matching ResolveInfo in target user if any. 5759 private ResolveInfo queryCrossProfileIntents( 5760 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5761 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5762 if (matchingFilters != null) { 5763 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5764 // match the same intent. For performance reasons, it is better not to 5765 // run queryIntent twice for the same userId 5766 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5767 int size = matchingFilters.size(); 5768 for (int i = 0; i < size; i++) { 5769 CrossProfileIntentFilter filter = matchingFilters.get(i); 5770 int targetUserId = filter.getTargetUserId(); 5771 boolean skipCurrentProfile = 5772 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5773 boolean skipCurrentProfileIfNoMatchFound = 5774 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5775 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5776 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5777 // Checking if there are activities in the target user that can handle the 5778 // intent. 5779 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5780 resolvedType, flags, sourceUserId); 5781 if (resolveInfo != null) return resolveInfo; 5782 alreadyTriedUserIds.put(targetUserId, true); 5783 } 5784 } 5785 } 5786 return null; 5787 } 5788 5789 /** 5790 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5791 * will forward the intent to the filter's target user. 5792 * Otherwise, returns null. 5793 */ 5794 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5795 String resolvedType, int flags, int sourceUserId) { 5796 int targetUserId = filter.getTargetUserId(); 5797 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5798 resolvedType, flags, targetUserId); 5799 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5800 // If all the matches in the target profile are suspended, return null. 5801 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5802 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5803 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5804 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5805 targetUserId); 5806 } 5807 } 5808 } 5809 return null; 5810 } 5811 5812 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5813 int sourceUserId, int targetUserId) { 5814 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5815 long ident = Binder.clearCallingIdentity(); 5816 boolean targetIsProfile; 5817 try { 5818 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5819 } finally { 5820 Binder.restoreCallingIdentity(ident); 5821 } 5822 String className; 5823 if (targetIsProfile) { 5824 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5825 } else { 5826 className = FORWARD_INTENT_TO_PARENT; 5827 } 5828 ComponentName forwardingActivityComponentName = new ComponentName( 5829 mAndroidApplication.packageName, className); 5830 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5831 sourceUserId); 5832 if (!targetIsProfile) { 5833 forwardingActivityInfo.showUserIcon = targetUserId; 5834 forwardingResolveInfo.noResourceId = true; 5835 } 5836 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5837 forwardingResolveInfo.priority = 0; 5838 forwardingResolveInfo.preferredOrder = 0; 5839 forwardingResolveInfo.match = 0; 5840 forwardingResolveInfo.isDefault = true; 5841 forwardingResolveInfo.filter = filter; 5842 forwardingResolveInfo.targetUserId = targetUserId; 5843 return forwardingResolveInfo; 5844 } 5845 5846 @Override 5847 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5848 Intent[] specifics, String[] specificTypes, Intent intent, 5849 String resolvedType, int flags, int userId) { 5850 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5851 specificTypes, intent, resolvedType, flags, userId)); 5852 } 5853 5854 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5855 Intent[] specifics, String[] specificTypes, Intent intent, 5856 String resolvedType, int flags, int userId) { 5857 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5858 flags = updateFlagsForResolve(flags, userId, intent); 5859 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5860 false /* requireFullPermission */, false /* checkShell */, 5861 "query intent activity options"); 5862 final String resultsAction = intent.getAction(); 5863 5864 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5865 | PackageManager.GET_RESOLVED_FILTER, userId); 5866 5867 if (DEBUG_INTENT_MATCHING) { 5868 Log.v(TAG, "Query " + intent + ": " + results); 5869 } 5870 5871 int specificsPos = 0; 5872 int N; 5873 5874 // todo: note that the algorithm used here is O(N^2). This 5875 // isn't a problem in our current environment, but if we start running 5876 // into situations where we have more than 5 or 10 matches then this 5877 // should probably be changed to something smarter... 5878 5879 // First we go through and resolve each of the specific items 5880 // that were supplied, taking care of removing any corresponding 5881 // duplicate items in the generic resolve list. 5882 if (specifics != null) { 5883 for (int i=0; i<specifics.length; i++) { 5884 final Intent sintent = specifics[i]; 5885 if (sintent == null) { 5886 continue; 5887 } 5888 5889 if (DEBUG_INTENT_MATCHING) { 5890 Log.v(TAG, "Specific #" + i + ": " + sintent); 5891 } 5892 5893 String action = sintent.getAction(); 5894 if (resultsAction != null && resultsAction.equals(action)) { 5895 // If this action was explicitly requested, then don't 5896 // remove things that have it. 5897 action = null; 5898 } 5899 5900 ResolveInfo ri = null; 5901 ActivityInfo ai = null; 5902 5903 ComponentName comp = sintent.getComponent(); 5904 if (comp == null) { 5905 ri = resolveIntent( 5906 sintent, 5907 specificTypes != null ? specificTypes[i] : null, 5908 flags, userId); 5909 if (ri == null) { 5910 continue; 5911 } 5912 if (ri == mResolveInfo) { 5913 // ACK! Must do something better with this. 5914 } 5915 ai = ri.activityInfo; 5916 comp = new ComponentName(ai.applicationInfo.packageName, 5917 ai.name); 5918 } else { 5919 ai = getActivityInfo(comp, flags, userId); 5920 if (ai == null) { 5921 continue; 5922 } 5923 } 5924 5925 // Look for any generic query activities that are duplicates 5926 // of this specific one, and remove them from the results. 5927 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5928 N = results.size(); 5929 int j; 5930 for (j=specificsPos; j<N; j++) { 5931 ResolveInfo sri = results.get(j); 5932 if ((sri.activityInfo.name.equals(comp.getClassName()) 5933 && sri.activityInfo.applicationInfo.packageName.equals( 5934 comp.getPackageName())) 5935 || (action != null && sri.filter.matchAction(action))) { 5936 results.remove(j); 5937 if (DEBUG_INTENT_MATCHING) Log.v( 5938 TAG, "Removing duplicate item from " + j 5939 + " due to specific " + specificsPos); 5940 if (ri == null) { 5941 ri = sri; 5942 } 5943 j--; 5944 N--; 5945 } 5946 } 5947 5948 // Add this specific item to its proper place. 5949 if (ri == null) { 5950 ri = new ResolveInfo(); 5951 ri.activityInfo = ai; 5952 } 5953 results.add(specificsPos, ri); 5954 ri.specificIndex = i; 5955 specificsPos++; 5956 } 5957 } 5958 5959 // Now we go through the remaining generic results and remove any 5960 // duplicate actions that are found here. 5961 N = results.size(); 5962 for (int i=specificsPos; i<N-1; i++) { 5963 final ResolveInfo rii = results.get(i); 5964 if (rii.filter == null) { 5965 continue; 5966 } 5967 5968 // Iterate over all of the actions of this result's intent 5969 // filter... typically this should be just one. 5970 final Iterator<String> it = rii.filter.actionsIterator(); 5971 if (it == null) { 5972 continue; 5973 } 5974 while (it.hasNext()) { 5975 final String action = it.next(); 5976 if (resultsAction != null && resultsAction.equals(action)) { 5977 // If this action was explicitly requested, then don't 5978 // remove things that have it. 5979 continue; 5980 } 5981 for (int j=i+1; j<N; j++) { 5982 final ResolveInfo rij = results.get(j); 5983 if (rij.filter != null && rij.filter.hasAction(action)) { 5984 results.remove(j); 5985 if (DEBUG_INTENT_MATCHING) Log.v( 5986 TAG, "Removing duplicate item from " + j 5987 + " due to action " + action + " at " + i); 5988 j--; 5989 N--; 5990 } 5991 } 5992 } 5993 5994 // If the caller didn't request filter information, drop it now 5995 // so we don't have to marshall/unmarshall it. 5996 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5997 rii.filter = null; 5998 } 5999 } 6000 6001 // Filter out the caller activity if so requested. 6002 if (caller != null) { 6003 N = results.size(); 6004 for (int i=0; i<N; i++) { 6005 ActivityInfo ainfo = results.get(i).activityInfo; 6006 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6007 && caller.getClassName().equals(ainfo.name)) { 6008 results.remove(i); 6009 break; 6010 } 6011 } 6012 } 6013 6014 // If the caller didn't request filter information, 6015 // drop them now so we don't have to 6016 // marshall/unmarshall it. 6017 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6018 N = results.size(); 6019 for (int i=0; i<N; i++) { 6020 results.get(i).filter = null; 6021 } 6022 } 6023 6024 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6025 return results; 6026 } 6027 6028 @Override 6029 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 return new ParceledListSlice<>( 6032 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6033 } 6034 6035 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6036 String resolvedType, int flags, int userId) { 6037 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6038 flags = updateFlagsForResolve(flags, userId, intent); 6039 ComponentName comp = intent.getComponent(); 6040 if (comp == null) { 6041 if (intent.getSelector() != null) { 6042 intent = intent.getSelector(); 6043 comp = intent.getComponent(); 6044 } 6045 } 6046 if (comp != null) { 6047 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6048 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6049 if (ai != null) { 6050 ResolveInfo ri = new ResolveInfo(); 6051 ri.activityInfo = ai; 6052 list.add(ri); 6053 } 6054 return list; 6055 } 6056 6057 // reader 6058 synchronized (mPackages) { 6059 String pkgName = intent.getPackage(); 6060 if (pkgName == null) { 6061 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6062 } 6063 final PackageParser.Package pkg = mPackages.get(pkgName); 6064 if (pkg != null) { 6065 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6066 userId); 6067 } 6068 return Collections.emptyList(); 6069 } 6070 } 6071 6072 @Override 6073 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6074 if (!sUserManager.exists(userId)) return null; 6075 flags = updateFlagsForResolve(flags, userId, intent); 6076 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6077 if (query != null) { 6078 if (query.size() >= 1) { 6079 // If there is more than one service with the same priority, 6080 // just arbitrarily pick the first one. 6081 return query.get(0); 6082 } 6083 } 6084 return null; 6085 } 6086 6087 @Override 6088 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6089 String resolvedType, int flags, int userId) { 6090 return new ParceledListSlice<>( 6091 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6092 } 6093 6094 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6095 String resolvedType, int flags, int userId) { 6096 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6097 flags = updateFlagsForResolve(flags, userId, intent); 6098 ComponentName comp = intent.getComponent(); 6099 if (comp == null) { 6100 if (intent.getSelector() != null) { 6101 intent = intent.getSelector(); 6102 comp = intent.getComponent(); 6103 } 6104 } 6105 if (comp != null) { 6106 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6107 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6108 if (si != null) { 6109 final ResolveInfo ri = new ResolveInfo(); 6110 ri.serviceInfo = si; 6111 list.add(ri); 6112 } 6113 return list; 6114 } 6115 6116 // reader 6117 synchronized (mPackages) { 6118 String pkgName = intent.getPackage(); 6119 if (pkgName == null) { 6120 return mServices.queryIntent(intent, resolvedType, flags, userId); 6121 } 6122 final PackageParser.Package pkg = mPackages.get(pkgName); 6123 if (pkg != null) { 6124 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6125 userId); 6126 } 6127 return Collections.emptyList(); 6128 } 6129 } 6130 6131 @Override 6132 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6133 String resolvedType, int flags, int userId) { 6134 return new ParceledListSlice<>( 6135 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6136 } 6137 6138 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6139 Intent intent, String resolvedType, int flags, int userId) { 6140 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6141 flags = updateFlagsForResolve(flags, userId, intent); 6142 ComponentName comp = intent.getComponent(); 6143 if (comp == null) { 6144 if (intent.getSelector() != null) { 6145 intent = intent.getSelector(); 6146 comp = intent.getComponent(); 6147 } 6148 } 6149 if (comp != null) { 6150 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6151 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6152 if (pi != null) { 6153 final ResolveInfo ri = new ResolveInfo(); 6154 ri.providerInfo = pi; 6155 list.add(ri); 6156 } 6157 return list; 6158 } 6159 6160 // reader 6161 synchronized (mPackages) { 6162 String pkgName = intent.getPackage(); 6163 if (pkgName == null) { 6164 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6165 } 6166 final PackageParser.Package pkg = mPackages.get(pkgName); 6167 if (pkg != null) { 6168 return mProviders.queryIntentForPackage( 6169 intent, resolvedType, flags, pkg.providers, userId); 6170 } 6171 return Collections.emptyList(); 6172 } 6173 } 6174 6175 @Override 6176 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6177 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6178 flags = updateFlagsForPackage(flags, userId, null); 6179 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6181 true /* requireFullPermission */, false /* checkShell */, 6182 "get installed packages"); 6183 6184 // writer 6185 synchronized (mPackages) { 6186 ArrayList<PackageInfo> list; 6187 if (listUninstalled) { 6188 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6189 for (PackageSetting ps : mSettings.mPackages.values()) { 6190 final PackageInfo pi; 6191 if (ps.pkg != null) { 6192 pi = generatePackageInfo(ps, flags, userId); 6193 } else { 6194 pi = generatePackageInfo(ps, flags, userId); 6195 } 6196 if (pi != null) { 6197 list.add(pi); 6198 } 6199 } 6200 } else { 6201 list = new ArrayList<PackageInfo>(mPackages.size()); 6202 for (PackageParser.Package p : mPackages.values()) { 6203 final PackageInfo pi = 6204 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6205 if (pi != null) { 6206 list.add(pi); 6207 } 6208 } 6209 } 6210 6211 return new ParceledListSlice<PackageInfo>(list); 6212 } 6213 } 6214 6215 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6216 String[] permissions, boolean[] tmp, int flags, int userId) { 6217 int numMatch = 0; 6218 final PermissionsState permissionsState = ps.getPermissionsState(); 6219 for (int i=0; i<permissions.length; i++) { 6220 final String permission = permissions[i]; 6221 if (permissionsState.hasPermission(permission, userId)) { 6222 tmp[i] = true; 6223 numMatch++; 6224 } else { 6225 tmp[i] = false; 6226 } 6227 } 6228 if (numMatch == 0) { 6229 return; 6230 } 6231 final PackageInfo pi; 6232 if (ps.pkg != null) { 6233 pi = generatePackageInfo(ps, flags, userId); 6234 } else { 6235 pi = generatePackageInfo(ps, flags, userId); 6236 } 6237 // The above might return null in cases of uninstalled apps or install-state 6238 // skew across users/profiles. 6239 if (pi != null) { 6240 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6241 if (numMatch == permissions.length) { 6242 pi.requestedPermissions = permissions; 6243 } else { 6244 pi.requestedPermissions = new String[numMatch]; 6245 numMatch = 0; 6246 for (int i=0; i<permissions.length; i++) { 6247 if (tmp[i]) { 6248 pi.requestedPermissions[numMatch] = permissions[i]; 6249 numMatch++; 6250 } 6251 } 6252 } 6253 } 6254 list.add(pi); 6255 } 6256 } 6257 6258 @Override 6259 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6260 String[] permissions, int flags, int userId) { 6261 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6262 flags = updateFlagsForPackage(flags, userId, permissions); 6263 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6264 6265 // writer 6266 synchronized (mPackages) { 6267 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6268 boolean[] tmpBools = new boolean[permissions.length]; 6269 if (listUninstalled) { 6270 for (PackageSetting ps : mSettings.mPackages.values()) { 6271 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6272 } 6273 } else { 6274 for (PackageParser.Package pkg : mPackages.values()) { 6275 PackageSetting ps = (PackageSetting)pkg.mExtras; 6276 if (ps != null) { 6277 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6278 userId); 6279 } 6280 } 6281 } 6282 6283 return new ParceledListSlice<PackageInfo>(list); 6284 } 6285 } 6286 6287 @Override 6288 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6289 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6290 flags = updateFlagsForApplication(flags, userId, null); 6291 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6292 6293 // writer 6294 synchronized (mPackages) { 6295 ArrayList<ApplicationInfo> list; 6296 if (listUninstalled) { 6297 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6298 for (PackageSetting ps : mSettings.mPackages.values()) { 6299 ApplicationInfo ai; 6300 if (ps.pkg != null) { 6301 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6302 ps.readUserState(userId), userId); 6303 } else { 6304 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6305 } 6306 if (ai != null) { 6307 list.add(ai); 6308 } 6309 } 6310 } else { 6311 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6312 for (PackageParser.Package p : mPackages.values()) { 6313 if (p.mExtras != null) { 6314 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6315 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6316 if (ai != null) { 6317 list.add(ai); 6318 } 6319 } 6320 } 6321 } 6322 6323 return new ParceledListSlice<ApplicationInfo>(list); 6324 } 6325 } 6326 6327 @Override 6328 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6329 if (DISABLE_EPHEMERAL_APPS) { 6330 return null; 6331 } 6332 6333 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6334 "getEphemeralApplications"); 6335 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6336 true /* requireFullPermission */, false /* checkShell */, 6337 "getEphemeralApplications"); 6338 synchronized (mPackages) { 6339 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6340 .getEphemeralApplicationsLPw(userId); 6341 if (ephemeralApps != null) { 6342 return new ParceledListSlice<>(ephemeralApps); 6343 } 6344 } 6345 return null; 6346 } 6347 6348 @Override 6349 public boolean isEphemeralApplication(String packageName, int userId) { 6350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6351 true /* requireFullPermission */, false /* checkShell */, 6352 "isEphemeral"); 6353 if (DISABLE_EPHEMERAL_APPS) { 6354 return false; 6355 } 6356 6357 if (!isCallerSameApp(packageName)) { 6358 return false; 6359 } 6360 synchronized (mPackages) { 6361 PackageParser.Package pkg = mPackages.get(packageName); 6362 if (pkg != null) { 6363 return pkg.applicationInfo.isEphemeralApp(); 6364 } 6365 } 6366 return false; 6367 } 6368 6369 @Override 6370 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6371 if (DISABLE_EPHEMERAL_APPS) { 6372 return null; 6373 } 6374 6375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6376 true /* requireFullPermission */, false /* checkShell */, 6377 "getCookie"); 6378 if (!isCallerSameApp(packageName)) { 6379 return null; 6380 } 6381 synchronized (mPackages) { 6382 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6383 packageName, userId); 6384 } 6385 } 6386 6387 @Override 6388 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6389 if (DISABLE_EPHEMERAL_APPS) { 6390 return true; 6391 } 6392 6393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6394 true /* requireFullPermission */, true /* checkShell */, 6395 "setCookie"); 6396 if (!isCallerSameApp(packageName)) { 6397 return false; 6398 } 6399 synchronized (mPackages) { 6400 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6401 packageName, cookie, userId); 6402 } 6403 } 6404 6405 @Override 6406 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6407 if (DISABLE_EPHEMERAL_APPS) { 6408 return null; 6409 } 6410 6411 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6412 "getEphemeralApplicationIcon"); 6413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6414 true /* requireFullPermission */, false /* checkShell */, 6415 "getEphemeralApplicationIcon"); 6416 synchronized (mPackages) { 6417 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6418 packageName, userId); 6419 } 6420 } 6421 6422 private boolean isCallerSameApp(String packageName) { 6423 PackageParser.Package pkg = mPackages.get(packageName); 6424 return pkg != null 6425 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6426 } 6427 6428 @Override 6429 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6430 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6431 } 6432 6433 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6434 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6435 6436 // reader 6437 synchronized (mPackages) { 6438 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6439 final int userId = UserHandle.getCallingUserId(); 6440 while (i.hasNext()) { 6441 final PackageParser.Package p = i.next(); 6442 if (p.applicationInfo == null) continue; 6443 6444 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6445 && !p.applicationInfo.isDirectBootAware(); 6446 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6447 && p.applicationInfo.isDirectBootAware(); 6448 6449 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6450 && (!mSafeMode || isSystemApp(p)) 6451 && (matchesUnaware || matchesAware)) { 6452 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6453 if (ps != null) { 6454 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6455 ps.readUserState(userId), userId); 6456 if (ai != null) { 6457 finalList.add(ai); 6458 } 6459 } 6460 } 6461 } 6462 } 6463 6464 return finalList; 6465 } 6466 6467 @Override 6468 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6469 if (!sUserManager.exists(userId)) return null; 6470 flags = updateFlagsForComponent(flags, userId, name); 6471 // reader 6472 synchronized (mPackages) { 6473 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6474 PackageSetting ps = provider != null 6475 ? mSettings.mPackages.get(provider.owner.packageName) 6476 : null; 6477 return ps != null 6478 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6479 ? PackageParser.generateProviderInfo(provider, flags, 6480 ps.readUserState(userId), userId) 6481 : null; 6482 } 6483 } 6484 6485 /** 6486 * @deprecated 6487 */ 6488 @Deprecated 6489 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6490 // reader 6491 synchronized (mPackages) { 6492 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6493 .entrySet().iterator(); 6494 final int userId = UserHandle.getCallingUserId(); 6495 while (i.hasNext()) { 6496 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6497 PackageParser.Provider p = entry.getValue(); 6498 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6499 6500 if (ps != null && p.syncable 6501 && (!mSafeMode || (p.info.applicationInfo.flags 6502 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6503 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6504 ps.readUserState(userId), userId); 6505 if (info != null) { 6506 outNames.add(entry.getKey()); 6507 outInfo.add(info); 6508 } 6509 } 6510 } 6511 } 6512 } 6513 6514 @Override 6515 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6516 int uid, int flags) { 6517 final int userId = processName != null ? UserHandle.getUserId(uid) 6518 : UserHandle.getCallingUserId(); 6519 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6520 flags = updateFlagsForComponent(flags, userId, processName); 6521 6522 ArrayList<ProviderInfo> finalList = null; 6523 // reader 6524 synchronized (mPackages) { 6525 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6526 while (i.hasNext()) { 6527 final PackageParser.Provider p = i.next(); 6528 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6529 if (ps != null && p.info.authority != null 6530 && (processName == null 6531 || (p.info.processName.equals(processName) 6532 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6533 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6534 if (finalList == null) { 6535 finalList = new ArrayList<ProviderInfo>(3); 6536 } 6537 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6538 ps.readUserState(userId), userId); 6539 if (info != null) { 6540 finalList.add(info); 6541 } 6542 } 6543 } 6544 } 6545 6546 if (finalList != null) { 6547 Collections.sort(finalList, mProviderInitOrderSorter); 6548 return new ParceledListSlice<ProviderInfo>(finalList); 6549 } 6550 6551 return ParceledListSlice.emptyList(); 6552 } 6553 6554 @Override 6555 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6556 // reader 6557 synchronized (mPackages) { 6558 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6559 return PackageParser.generateInstrumentationInfo(i, flags); 6560 } 6561 } 6562 6563 @Override 6564 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6565 String targetPackage, int flags) { 6566 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6567 } 6568 6569 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6570 int flags) { 6571 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6572 6573 // reader 6574 synchronized (mPackages) { 6575 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6576 while (i.hasNext()) { 6577 final PackageParser.Instrumentation p = i.next(); 6578 if (targetPackage == null 6579 || targetPackage.equals(p.info.targetPackage)) { 6580 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6581 flags); 6582 if (ii != null) { 6583 finalList.add(ii); 6584 } 6585 } 6586 } 6587 } 6588 6589 return finalList; 6590 } 6591 6592 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6593 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6594 if (overlays == null) { 6595 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6596 return; 6597 } 6598 for (PackageParser.Package opkg : overlays.values()) { 6599 // Not much to do if idmap fails: we already logged the error 6600 // and we certainly don't want to abort installation of pkg simply 6601 // because an overlay didn't fit properly. For these reasons, 6602 // ignore the return value of createIdmapForPackagePairLI. 6603 createIdmapForPackagePairLI(pkg, opkg); 6604 } 6605 } 6606 6607 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6608 PackageParser.Package opkg) { 6609 if (!opkg.mTrustedOverlay) { 6610 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6611 opkg.baseCodePath + ": overlay not trusted"); 6612 return false; 6613 } 6614 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6615 if (overlaySet == null) { 6616 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6617 opkg.baseCodePath + " but target package has no known overlays"); 6618 return false; 6619 } 6620 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6621 // TODO: generate idmap for split APKs 6622 try { 6623 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6624 } catch (InstallerException e) { 6625 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6626 + opkg.baseCodePath); 6627 return false; 6628 } 6629 PackageParser.Package[] overlayArray = 6630 overlaySet.values().toArray(new PackageParser.Package[0]); 6631 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6632 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6633 return p1.mOverlayPriority - p2.mOverlayPriority; 6634 } 6635 }; 6636 Arrays.sort(overlayArray, cmp); 6637 6638 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6639 int i = 0; 6640 for (PackageParser.Package p : overlayArray) { 6641 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6642 } 6643 return true; 6644 } 6645 6646 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6648 try { 6649 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6650 } finally { 6651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6652 } 6653 } 6654 6655 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6656 final File[] files = dir.listFiles(); 6657 if (ArrayUtils.isEmpty(files)) { 6658 Log.d(TAG, "No files in app dir " + dir); 6659 return; 6660 } 6661 6662 if (DEBUG_PACKAGE_SCANNING) { 6663 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6664 + " flags=0x" + Integer.toHexString(parseFlags)); 6665 } 6666 6667 for (File file : files) { 6668 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6669 && !PackageInstallerService.isStageName(file.getName()); 6670 if (!isPackage) { 6671 // Ignore entries which are not packages 6672 continue; 6673 } 6674 try { 6675 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6676 scanFlags, currentTime, null); 6677 } catch (PackageManagerException e) { 6678 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6679 6680 // Delete invalid userdata apps 6681 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6682 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6683 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6684 removeCodePathLI(file); 6685 } 6686 } 6687 } 6688 } 6689 6690 private static File getSettingsProblemFile() { 6691 File dataDir = Environment.getDataDirectory(); 6692 File systemDir = new File(dataDir, "system"); 6693 File fname = new File(systemDir, "uiderrors.txt"); 6694 return fname; 6695 } 6696 6697 static void reportSettingsProblem(int priority, String msg) { 6698 logCriticalInfo(priority, msg); 6699 } 6700 6701 static void logCriticalInfo(int priority, String msg) { 6702 Slog.println(priority, TAG, msg); 6703 EventLogTags.writePmCriticalInfo(msg); 6704 try { 6705 File fname = getSettingsProblemFile(); 6706 FileOutputStream out = new FileOutputStream(fname, true); 6707 PrintWriter pw = new FastPrintWriter(out); 6708 SimpleDateFormat formatter = new SimpleDateFormat(); 6709 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6710 pw.println(dateString + ": " + msg); 6711 pw.close(); 6712 FileUtils.setPermissions( 6713 fname.toString(), 6714 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6715 -1, -1); 6716 } catch (java.io.IOException e) { 6717 } 6718 } 6719 6720 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6721 final int policyFlags) throws PackageManagerException { 6722 if (ps != null 6723 && ps.codePath.equals(srcFile) 6724 && ps.timeStamp == srcFile.lastModified() 6725 && !isCompatSignatureUpdateNeeded(pkg) 6726 && !isRecoverSignatureUpdateNeeded(pkg)) { 6727 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6728 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6729 ArraySet<PublicKey> signingKs; 6730 synchronized (mPackages) { 6731 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6732 } 6733 if (ps.signatures.mSignatures != null 6734 && ps.signatures.mSignatures.length != 0 6735 && signingKs != null) { 6736 // Optimization: reuse the existing cached certificates 6737 // if the package appears to be unchanged. 6738 pkg.mSignatures = ps.signatures.mSignatures; 6739 pkg.mSigningKeys = signingKs; 6740 return; 6741 } 6742 6743 Slog.w(TAG, "PackageSetting for " + ps.name 6744 + " is missing signatures. Collecting certs again to recover them."); 6745 } else { 6746 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6747 } 6748 6749 try { 6750 PackageParser.collectCertificates(pkg, policyFlags); 6751 } catch (PackageParserException e) { 6752 throw PackageManagerException.from(e); 6753 } 6754 } 6755 6756 /** 6757 * Traces a package scan. 6758 * @see #scanPackageLI(File, int, int, long, UserHandle) 6759 */ 6760 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6761 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6762 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6763 try { 6764 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6765 } finally { 6766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6767 } 6768 } 6769 6770 /** 6771 * Scans a package and returns the newly parsed package. 6772 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6773 */ 6774 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6775 long currentTime, UserHandle user) throws PackageManagerException { 6776 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6777 PackageParser pp = new PackageParser(); 6778 pp.setSeparateProcesses(mSeparateProcesses); 6779 pp.setOnlyCoreApps(mOnlyCore); 6780 pp.setDisplayMetrics(mMetrics); 6781 6782 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6783 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6784 } 6785 6786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6787 final PackageParser.Package pkg; 6788 try { 6789 pkg = pp.parsePackage(scanFile, parseFlags); 6790 } catch (PackageParserException e) { 6791 throw PackageManagerException.from(e); 6792 } finally { 6793 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6794 } 6795 6796 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6797 } 6798 6799 /** 6800 * Scans a package and returns the newly parsed package. 6801 * @throws PackageManagerException on a parse error. 6802 */ 6803 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6804 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6805 throws PackageManagerException { 6806 // If the package has children and this is the first dive in the function 6807 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6808 // packages (parent and children) would be successfully scanned before the 6809 // actual scan since scanning mutates internal state and we want to atomically 6810 // install the package and its children. 6811 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6812 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6813 scanFlags |= SCAN_CHECK_ONLY; 6814 } 6815 } else { 6816 scanFlags &= ~SCAN_CHECK_ONLY; 6817 } 6818 6819 // Scan the parent 6820 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6821 scanFlags, currentTime, user); 6822 6823 // Scan the children 6824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6825 for (int i = 0; i < childCount; i++) { 6826 PackageParser.Package childPackage = pkg.childPackages.get(i); 6827 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6828 currentTime, user); 6829 } 6830 6831 6832 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6833 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6834 } 6835 6836 return scannedPkg; 6837 } 6838 6839 /** 6840 * Scans a package and returns the newly parsed package. 6841 * @throws PackageManagerException on a parse error. 6842 */ 6843 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6844 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6845 throws PackageManagerException { 6846 PackageSetting ps = null; 6847 PackageSetting updatedPkg; 6848 // reader 6849 synchronized (mPackages) { 6850 // Look to see if we already know about this package. 6851 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6852 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6853 // This package has been renamed to its original name. Let's 6854 // use that. 6855 ps = mSettings.peekPackageLPr(oldName); 6856 } 6857 // If there was no original package, see one for the real package name. 6858 if (ps == null) { 6859 ps = mSettings.peekPackageLPr(pkg.packageName); 6860 } 6861 // Check to see if this package could be hiding/updating a system 6862 // package. Must look for it either under the original or real 6863 // package name depending on our state. 6864 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6865 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6866 6867 // If this is a package we don't know about on the system partition, we 6868 // may need to remove disabled child packages on the system partition 6869 // or may need to not add child packages if the parent apk is updated 6870 // on the data partition and no longer defines this child package. 6871 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6872 // If this is a parent package for an updated system app and this system 6873 // app got an OTA update which no longer defines some of the child packages 6874 // we have to prune them from the disabled system packages. 6875 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6876 if (disabledPs != null) { 6877 final int scannedChildCount = (pkg.childPackages != null) 6878 ? pkg.childPackages.size() : 0; 6879 final int disabledChildCount = disabledPs.childPackageNames != null 6880 ? disabledPs.childPackageNames.size() : 0; 6881 for (int i = 0; i < disabledChildCount; i++) { 6882 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6883 boolean disabledPackageAvailable = false; 6884 for (int j = 0; j < scannedChildCount; j++) { 6885 PackageParser.Package childPkg = pkg.childPackages.get(j); 6886 if (childPkg.packageName.equals(disabledChildPackageName)) { 6887 disabledPackageAvailable = true; 6888 break; 6889 } 6890 } 6891 if (!disabledPackageAvailable) { 6892 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6893 } 6894 } 6895 } 6896 } 6897 } 6898 6899 boolean updatedPkgBetter = false; 6900 // First check if this is a system package that may involve an update 6901 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6902 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6903 // it needs to drop FLAG_PRIVILEGED. 6904 if (locationIsPrivileged(scanFile)) { 6905 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6906 } else { 6907 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6908 } 6909 6910 if (ps != null && !ps.codePath.equals(scanFile)) { 6911 // The path has changed from what was last scanned... check the 6912 // version of the new path against what we have stored to determine 6913 // what to do. 6914 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6915 if (pkg.mVersionCode <= ps.versionCode) { 6916 // The system package has been updated and the code path does not match 6917 // Ignore entry. Skip it. 6918 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6919 + " ignored: updated version " + ps.versionCode 6920 + " better than this " + pkg.mVersionCode); 6921 if (!updatedPkg.codePath.equals(scanFile)) { 6922 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6923 + ps.name + " changing from " + updatedPkg.codePathString 6924 + " to " + scanFile); 6925 updatedPkg.codePath = scanFile; 6926 updatedPkg.codePathString = scanFile.toString(); 6927 updatedPkg.resourcePath = scanFile; 6928 updatedPkg.resourcePathString = scanFile.toString(); 6929 } 6930 updatedPkg.pkg = pkg; 6931 updatedPkg.versionCode = pkg.mVersionCode; 6932 6933 // Update the disabled system child packages to point to the package too. 6934 final int childCount = updatedPkg.childPackageNames != null 6935 ? updatedPkg.childPackageNames.size() : 0; 6936 for (int i = 0; i < childCount; i++) { 6937 String childPackageName = updatedPkg.childPackageNames.get(i); 6938 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6939 childPackageName); 6940 if (updatedChildPkg != null) { 6941 updatedChildPkg.pkg = pkg; 6942 updatedChildPkg.versionCode = pkg.mVersionCode; 6943 } 6944 } 6945 6946 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6947 + scanFile + " ignored: updated version " + ps.versionCode 6948 + " better than this " + pkg.mVersionCode); 6949 } else { 6950 // The current app on the system partition is better than 6951 // what we have updated to on the data partition; switch 6952 // back to the system partition version. 6953 // At this point, its safely assumed that package installation for 6954 // apps in system partition will go through. If not there won't be a working 6955 // version of the app 6956 // writer 6957 synchronized (mPackages) { 6958 // Just remove the loaded entries from package lists. 6959 mPackages.remove(ps.name); 6960 } 6961 6962 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6963 + " reverting from " + ps.codePathString 6964 + ": new version " + pkg.mVersionCode 6965 + " better than installed " + ps.versionCode); 6966 6967 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6968 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6969 synchronized (mInstallLock) { 6970 args.cleanUpResourcesLI(); 6971 } 6972 synchronized (mPackages) { 6973 mSettings.enableSystemPackageLPw(ps.name); 6974 } 6975 updatedPkgBetter = true; 6976 } 6977 } 6978 } 6979 6980 if (updatedPkg != null) { 6981 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6982 // initially 6983 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6984 6985 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6986 // flag set initially 6987 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6988 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6989 } 6990 } 6991 6992 // Verify certificates against what was last scanned 6993 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6994 6995 /* 6996 * A new system app appeared, but we already had a non-system one of the 6997 * same name installed earlier. 6998 */ 6999 boolean shouldHideSystemApp = false; 7000 if (updatedPkg == null && ps != null 7001 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7002 /* 7003 * Check to make sure the signatures match first. If they don't, 7004 * wipe the installed application and its data. 7005 */ 7006 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7007 != PackageManager.SIGNATURE_MATCH) { 7008 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7009 + " signatures don't match existing userdata copy; removing"); 7010 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7011 "scanPackageInternalLI")) { 7012 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7013 } 7014 ps = null; 7015 } else { 7016 /* 7017 * If the newly-added system app is an older version than the 7018 * already installed version, hide it. It will be scanned later 7019 * and re-added like an update. 7020 */ 7021 if (pkg.mVersionCode <= ps.versionCode) { 7022 shouldHideSystemApp = true; 7023 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7024 + " but new version " + pkg.mVersionCode + " better than installed " 7025 + ps.versionCode + "; hiding system"); 7026 } else { 7027 /* 7028 * The newly found system app is a newer version that the 7029 * one previously installed. Simply remove the 7030 * already-installed application and replace it with our own 7031 * while keeping the application data. 7032 */ 7033 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7034 + " reverting from " + ps.codePathString + ": new version " 7035 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7036 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7037 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7038 synchronized (mInstallLock) { 7039 args.cleanUpResourcesLI(); 7040 } 7041 } 7042 } 7043 } 7044 7045 // The apk is forward locked (not public) if its code and resources 7046 // are kept in different files. (except for app in either system or 7047 // vendor path). 7048 // TODO grab this value from PackageSettings 7049 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7050 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7051 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7052 } 7053 } 7054 7055 // TODO: extend to support forward-locked splits 7056 String resourcePath = null; 7057 String baseResourcePath = null; 7058 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7059 if (ps != null && ps.resourcePathString != null) { 7060 resourcePath = ps.resourcePathString; 7061 baseResourcePath = ps.resourcePathString; 7062 } else { 7063 // Should not happen at all. Just log an error. 7064 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7065 } 7066 } else { 7067 resourcePath = pkg.codePath; 7068 baseResourcePath = pkg.baseCodePath; 7069 } 7070 7071 // Set application objects path explicitly. 7072 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7073 pkg.setApplicationInfoCodePath(pkg.codePath); 7074 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7075 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7076 pkg.setApplicationInfoResourcePath(resourcePath); 7077 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7078 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7079 7080 // Note that we invoke the following method only if we are about to unpack an application 7081 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7082 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7083 7084 /* 7085 * If the system app should be overridden by a previously installed 7086 * data, hide the system app now and let the /data/app scan pick it up 7087 * again. 7088 */ 7089 if (shouldHideSystemApp) { 7090 synchronized (mPackages) { 7091 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7092 } 7093 } 7094 7095 return scannedPkg; 7096 } 7097 7098 private static String fixProcessName(String defProcessName, 7099 String processName, int uid) { 7100 if (processName == null) { 7101 return defProcessName; 7102 } 7103 return processName; 7104 } 7105 7106 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7107 throws PackageManagerException { 7108 if (pkgSetting.signatures.mSignatures != null) { 7109 // Already existing package. Make sure signatures match 7110 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7111 == PackageManager.SIGNATURE_MATCH; 7112 if (!match) { 7113 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7114 == PackageManager.SIGNATURE_MATCH; 7115 } 7116 if (!match) { 7117 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7118 == PackageManager.SIGNATURE_MATCH; 7119 } 7120 if (!match) { 7121 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7122 + pkg.packageName + " signatures do not match the " 7123 + "previously installed version; ignoring!"); 7124 } 7125 } 7126 7127 // Check for shared user signatures 7128 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7129 // Already existing package. Make sure signatures match 7130 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7131 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7132 if (!match) { 7133 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7134 == PackageManager.SIGNATURE_MATCH; 7135 } 7136 if (!match) { 7137 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7138 == PackageManager.SIGNATURE_MATCH; 7139 } 7140 if (!match) { 7141 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7142 "Package " + pkg.packageName 7143 + " has no signatures that match those in shared user " 7144 + pkgSetting.sharedUser.name + "; ignoring!"); 7145 } 7146 } 7147 } 7148 7149 /** 7150 * Enforces that only the system UID or root's UID can call a method exposed 7151 * via Binder. 7152 * 7153 * @param message used as message if SecurityException is thrown 7154 * @throws SecurityException if the caller is not system or root 7155 */ 7156 private static final void enforceSystemOrRoot(String message) { 7157 final int uid = Binder.getCallingUid(); 7158 if (uid != Process.SYSTEM_UID && uid != 0) { 7159 throw new SecurityException(message); 7160 } 7161 } 7162 7163 @Override 7164 public void performFstrimIfNeeded() { 7165 enforceSystemOrRoot("Only the system can request fstrim"); 7166 7167 // Before everything else, see whether we need to fstrim. 7168 try { 7169 IMountService ms = PackageHelper.getMountService(); 7170 if (ms != null) { 7171 final boolean isUpgrade = isUpgrade(); 7172 boolean doTrim = isUpgrade; 7173 if (doTrim) { 7174 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7175 } else { 7176 final long interval = android.provider.Settings.Global.getLong( 7177 mContext.getContentResolver(), 7178 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7179 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7180 if (interval > 0) { 7181 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7182 if (timeSinceLast > interval) { 7183 doTrim = true; 7184 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7185 + "; running immediately"); 7186 } 7187 } 7188 } 7189 if (doTrim) { 7190 if (!isFirstBoot()) { 7191 try { 7192 ActivityManagerNative.getDefault().showBootMessage( 7193 mContext.getResources().getString( 7194 R.string.android_upgrading_fstrim), true); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 ms.runMaintenance(); 7199 } 7200 } else { 7201 Slog.e(TAG, "Mount service unavailable!"); 7202 } 7203 } catch (RemoteException e) { 7204 // Can't happen; MountService is local 7205 } 7206 } 7207 7208 @Override 7209 public void updatePackagesIfNeeded() { 7210 enforceSystemOrRoot("Only the system can request package update"); 7211 7212 // We need to re-extract after an OTA. 7213 boolean causeUpgrade = isUpgrade(); 7214 7215 // First boot or factory reset. 7216 // Note: we also handle devices that are upgrading to N right now as if it is their 7217 // first boot, as they do not have profile data. 7218 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7219 7220 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7221 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7222 7223 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7224 return; 7225 } 7226 7227 List<PackageParser.Package> pkgs; 7228 synchronized (mPackages) { 7229 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7230 } 7231 7232 int numberOfPackagesVisited = 0; 7233 int numberOfPackagesOptimized = 0; 7234 int numberOfPackagesSkipped = 0; 7235 int numberOfPackagesFailed = 0; 7236 final int numberOfPackagesToDexopt = pkgs.size(); 7237 final long startTime = System.nanoTime(); 7238 7239 for (PackageParser.Package pkg : pkgs) { 7240 numberOfPackagesVisited++; 7241 7242 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7243 if (DEBUG_DEXOPT) { 7244 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7245 } 7246 numberOfPackagesSkipped++; 7247 continue; 7248 } 7249 7250 if (DEBUG_DEXOPT) { 7251 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7252 numberOfPackagesToDexopt + ": " + pkg.packageName); 7253 } 7254 7255 if (mIsPreNUpgrade) { 7256 try { 7257 ActivityManagerNative.getDefault().showBootMessage( 7258 mContext.getResources().getString(R.string.android_upgrading_apk, 7259 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7260 } catch (RemoteException e) { 7261 } 7262 } 7263 7264 // checkProfiles is false to avoid merging profiles during boot which 7265 // might interfere with background compilation (b/28612421). 7266 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7267 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7268 // trade-off worth doing to save boot time work. 7269 int dexOptStatus = performDexOptTraced(pkg.packageName, 7270 false /* checkProfiles */, 7271 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7272 false /* force */); 7273 switch (dexOptStatus) { 7274 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7275 numberOfPackagesOptimized++; 7276 break; 7277 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7278 numberOfPackagesSkipped++; 7279 break; 7280 case PackageDexOptimizer.DEX_OPT_FAILED: 7281 numberOfPackagesFailed++; 7282 break; 7283 default: 7284 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7285 break; 7286 } 7287 } 7288 7289 final int elapsedTimeSeconds = 7290 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7291 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7292 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7293 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7294 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7295 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7296 } 7297 7298 @Override 7299 public void notifyPackageUse(String packageName, int reason) { 7300 synchronized (mPackages) { 7301 PackageParser.Package p = mPackages.get(packageName); 7302 if (p == null) { 7303 return; 7304 } 7305 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7306 } 7307 } 7308 7309 // TODO: this is not used nor needed. Delete it. 7310 @Override 7311 public boolean performDexOptIfNeeded(String packageName) { 7312 int dexOptStatus = performDexOptTraced(packageName, 7313 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7314 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7315 } 7316 7317 @Override 7318 public boolean performDexOpt(String packageName, 7319 boolean checkProfiles, int compileReason, boolean force) { 7320 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7321 getCompilerFilterForReason(compileReason), force); 7322 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7323 } 7324 7325 @Override 7326 public boolean performDexOptMode(String packageName, 7327 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7328 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7329 targetCompilerFilter, force); 7330 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7331 } 7332 7333 private int performDexOptTraced(String packageName, 7334 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7336 try { 7337 return performDexOptInternal(packageName, checkProfiles, 7338 targetCompilerFilter, force); 7339 } finally { 7340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7341 } 7342 } 7343 7344 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7345 // if the package can now be considered up to date for the given filter. 7346 private int performDexOptInternal(String packageName, 7347 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7348 PackageParser.Package p; 7349 synchronized (mPackages) { 7350 p = mPackages.get(packageName); 7351 if (p == null) { 7352 // Package could not be found. Report failure. 7353 return PackageDexOptimizer.DEX_OPT_FAILED; 7354 } 7355 mPackageUsage.write(false); 7356 } 7357 long callingId = Binder.clearCallingIdentity(); 7358 try { 7359 synchronized (mInstallLock) { 7360 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7361 targetCompilerFilter, force); 7362 } 7363 } finally { 7364 Binder.restoreCallingIdentity(callingId); 7365 } 7366 } 7367 7368 public ArraySet<String> getOptimizablePackages() { 7369 ArraySet<String> pkgs = new ArraySet<String>(); 7370 synchronized (mPackages) { 7371 for (PackageParser.Package p : mPackages.values()) { 7372 if (PackageDexOptimizer.canOptimizePackage(p)) { 7373 pkgs.add(p.packageName); 7374 } 7375 } 7376 } 7377 return pkgs; 7378 } 7379 7380 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7381 boolean checkProfiles, String targetCompilerFilter, 7382 boolean force) { 7383 // Select the dex optimizer based on the force parameter. 7384 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7385 // allocate an object here. 7386 PackageDexOptimizer pdo = force 7387 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7388 : mPackageDexOptimizer; 7389 7390 // Optimize all dependencies first. Note: we ignore the return value and march on 7391 // on errors. 7392 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7393 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7394 if (!deps.isEmpty()) { 7395 for (PackageParser.Package depPackage : deps) { 7396 // TODO: Analyze and investigate if we (should) profile libraries. 7397 // Currently this will do a full compilation of the library by default. 7398 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7399 false /* checkProfiles */, 7400 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7401 } 7402 } 7403 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7404 targetCompilerFilter); 7405 } 7406 7407 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7408 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7409 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7410 Set<String> collectedNames = new HashSet<>(); 7411 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7412 7413 retValue.remove(p); 7414 7415 return retValue; 7416 } else { 7417 return Collections.emptyList(); 7418 } 7419 } 7420 7421 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7422 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7423 if (!collectedNames.contains(p.packageName)) { 7424 collectedNames.add(p.packageName); 7425 collected.add(p); 7426 7427 if (p.usesLibraries != null) { 7428 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7429 } 7430 if (p.usesOptionalLibraries != null) { 7431 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7432 collectedNames); 7433 } 7434 } 7435 } 7436 7437 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7438 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7439 for (String libName : libs) { 7440 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7441 if (libPkg != null) { 7442 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7443 } 7444 } 7445 } 7446 7447 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7448 synchronized (mPackages) { 7449 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7450 if (lib != null && lib.apk != null) { 7451 return mPackages.get(lib.apk); 7452 } 7453 } 7454 return null; 7455 } 7456 7457 public void shutdown() { 7458 mPackageUsage.write(true); 7459 } 7460 7461 @Override 7462 public void forceDexOpt(String packageName) { 7463 enforceSystemOrRoot("forceDexOpt"); 7464 7465 PackageParser.Package pkg; 7466 synchronized (mPackages) { 7467 pkg = mPackages.get(packageName); 7468 if (pkg == null) { 7469 throw new IllegalArgumentException("Unknown package: " + packageName); 7470 } 7471 } 7472 7473 synchronized (mInstallLock) { 7474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7475 7476 // Whoever is calling forceDexOpt wants a fully compiled package. 7477 // Don't use profiles since that may cause compilation to be skipped. 7478 final int res = performDexOptInternalWithDependenciesLI(pkg, 7479 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7480 true /* force */); 7481 7482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7483 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7484 throw new IllegalStateException("Failed to dexopt: " + res); 7485 } 7486 } 7487 } 7488 7489 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7490 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7491 Slog.w(TAG, "Unable to update from " + oldPkg.name 7492 + " to " + newPkg.packageName 7493 + ": old package not in system partition"); 7494 return false; 7495 } else if (mPackages.get(oldPkg.name) != null) { 7496 Slog.w(TAG, "Unable to update from " + oldPkg.name 7497 + " to " + newPkg.packageName 7498 + ": old package still exists"); 7499 return false; 7500 } 7501 return true; 7502 } 7503 7504 void removeCodePathLI(File codePath) { 7505 if (codePath.isDirectory()) { 7506 try { 7507 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7508 } catch (InstallerException e) { 7509 Slog.w(TAG, "Failed to remove code path", e); 7510 } 7511 } else { 7512 codePath.delete(); 7513 } 7514 } 7515 7516 private int[] resolveUserIds(int userId) { 7517 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7518 } 7519 7520 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7521 if (pkg == null) { 7522 Slog.wtf(TAG, "Package was null!", new Throwable()); 7523 return; 7524 } 7525 clearAppDataLeafLIF(pkg, userId, flags); 7526 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7527 for (int i = 0; i < childCount; i++) { 7528 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7529 } 7530 } 7531 7532 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7533 final PackageSetting ps; 7534 synchronized (mPackages) { 7535 ps = mSettings.mPackages.get(pkg.packageName); 7536 } 7537 for (int realUserId : resolveUserIds(userId)) { 7538 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7539 try { 7540 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7541 ceDataInode); 7542 } catch (InstallerException e) { 7543 Slog.w(TAG, String.valueOf(e)); 7544 } 7545 } 7546 } 7547 7548 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7549 if (pkg == null) { 7550 Slog.wtf(TAG, "Package was null!", new Throwable()); 7551 return; 7552 } 7553 destroyAppDataLeafLIF(pkg, userId, flags); 7554 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7555 for (int i = 0; i < childCount; i++) { 7556 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7557 } 7558 } 7559 7560 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7561 final PackageSetting ps; 7562 synchronized (mPackages) { 7563 ps = mSettings.mPackages.get(pkg.packageName); 7564 } 7565 for (int realUserId : resolveUserIds(userId)) { 7566 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7567 try { 7568 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7569 ceDataInode); 7570 } catch (InstallerException e) { 7571 Slog.w(TAG, String.valueOf(e)); 7572 } 7573 } 7574 } 7575 7576 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7577 if (pkg == null) { 7578 Slog.wtf(TAG, "Package was null!", new Throwable()); 7579 return; 7580 } 7581 destroyAppProfilesLeafLIF(pkg); 7582 destroyAppReferenceProfileLeafLIF(pkg, userId); 7583 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7584 for (int i = 0; i < childCount; i++) { 7585 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7586 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId); 7587 } 7588 } 7589 7590 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) { 7591 if (pkg.isForwardLocked()) { 7592 return; 7593 } 7594 7595 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7596 try { 7597 path = PackageManagerServiceUtils.realpath(new File(path)); 7598 } catch (IOException e) { 7599 // TODO: Should we return early here ? 7600 Slog.w(TAG, "Failed to get canonical path", e); 7601 continue; 7602 } 7603 7604 final String useMarker = path.replace('/', '@'); 7605 for (int realUserId : resolveUserIds(userId)) { 7606 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7607 File foreignUseMark = new File(profileDir, useMarker); 7608 if (foreignUseMark.exists()) { 7609 if (!foreignUseMark.delete()) { 7610 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7611 + pkg.packageName); 7612 } 7613 } 7614 7615 File[] markers = profileDir.listFiles(); 7616 if (markers != null) { 7617 final String searchString = "@" + pkg.packageName + "@"; 7618 // We also delete all markers that contain the package name we're 7619 // uninstalling. These are associated with secondary dex-files belonging 7620 // to the package. Reconstructing the path of these dex files is messy 7621 // in general. 7622 for (File marker : markers) { 7623 if (marker.getName().indexOf(searchString) > 0) { 7624 if (!marker.delete()) { 7625 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7626 + pkg.packageName); 7627 } 7628 } 7629 } 7630 } 7631 } 7632 } 7633 } 7634 7635 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7636 try { 7637 mInstaller.destroyAppProfiles(pkg.packageName); 7638 } catch (InstallerException e) { 7639 Slog.w(TAG, String.valueOf(e)); 7640 } 7641 } 7642 7643 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7644 if (pkg == null) { 7645 Slog.wtf(TAG, "Package was null!", new Throwable()); 7646 return; 7647 } 7648 clearAppProfilesLeafLIF(pkg); 7649 destroyAppReferenceProfileLeafLIF(pkg, userId); 7650 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7651 for (int i = 0; i < childCount; i++) { 7652 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7653 } 7654 } 7655 7656 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7657 try { 7658 mInstaller.clearAppProfiles(pkg.packageName); 7659 } catch (InstallerException e) { 7660 Slog.w(TAG, String.valueOf(e)); 7661 } 7662 } 7663 7664 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7665 long lastUpdateTime) { 7666 // Set parent install/update time 7667 PackageSetting ps = (PackageSetting) pkg.mExtras; 7668 if (ps != null) { 7669 ps.firstInstallTime = firstInstallTime; 7670 ps.lastUpdateTime = lastUpdateTime; 7671 } 7672 // Set children install/update time 7673 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7674 for (int i = 0; i < childCount; i++) { 7675 PackageParser.Package childPkg = pkg.childPackages.get(i); 7676 ps = (PackageSetting) childPkg.mExtras; 7677 if (ps != null) { 7678 ps.firstInstallTime = firstInstallTime; 7679 ps.lastUpdateTime = lastUpdateTime; 7680 } 7681 } 7682 } 7683 7684 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7685 PackageParser.Package changingLib) { 7686 if (file.path != null) { 7687 usesLibraryFiles.add(file.path); 7688 return; 7689 } 7690 PackageParser.Package p = mPackages.get(file.apk); 7691 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7692 // If we are doing this while in the middle of updating a library apk, 7693 // then we need to make sure to use that new apk for determining the 7694 // dependencies here. (We haven't yet finished committing the new apk 7695 // to the package manager state.) 7696 if (p == null || p.packageName.equals(changingLib.packageName)) { 7697 p = changingLib; 7698 } 7699 } 7700 if (p != null) { 7701 usesLibraryFiles.addAll(p.getAllCodePaths()); 7702 } 7703 } 7704 7705 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7706 PackageParser.Package changingLib) throws PackageManagerException { 7707 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7708 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7709 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7710 for (int i=0; i<N; i++) { 7711 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7712 if (file == null) { 7713 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7714 "Package " + pkg.packageName + " requires unavailable shared library " 7715 + pkg.usesLibraries.get(i) + "; failing!"); 7716 } 7717 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7718 } 7719 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7720 for (int i=0; i<N; i++) { 7721 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7722 if (file == null) { 7723 Slog.w(TAG, "Package " + pkg.packageName 7724 + " desires unavailable shared library " 7725 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7726 } else { 7727 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7728 } 7729 } 7730 N = usesLibraryFiles.size(); 7731 if (N > 0) { 7732 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7733 } else { 7734 pkg.usesLibraryFiles = null; 7735 } 7736 } 7737 } 7738 7739 private static boolean hasString(List<String> list, List<String> which) { 7740 if (list == null) { 7741 return false; 7742 } 7743 for (int i=list.size()-1; i>=0; i--) { 7744 for (int j=which.size()-1; j>=0; j--) { 7745 if (which.get(j).equals(list.get(i))) { 7746 return true; 7747 } 7748 } 7749 } 7750 return false; 7751 } 7752 7753 private void updateAllSharedLibrariesLPw() { 7754 for (PackageParser.Package pkg : mPackages.values()) { 7755 try { 7756 updateSharedLibrariesLPw(pkg, null); 7757 } catch (PackageManagerException e) { 7758 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7759 } 7760 } 7761 } 7762 7763 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7764 PackageParser.Package changingPkg) { 7765 ArrayList<PackageParser.Package> res = null; 7766 for (PackageParser.Package pkg : mPackages.values()) { 7767 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7768 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7769 if (res == null) { 7770 res = new ArrayList<PackageParser.Package>(); 7771 } 7772 res.add(pkg); 7773 try { 7774 updateSharedLibrariesLPw(pkg, changingPkg); 7775 } catch (PackageManagerException e) { 7776 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7777 } 7778 } 7779 } 7780 return res; 7781 } 7782 7783 /** 7784 * Derive the value of the {@code cpuAbiOverride} based on the provided 7785 * value and an optional stored value from the package settings. 7786 */ 7787 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7788 String cpuAbiOverride = null; 7789 7790 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7791 cpuAbiOverride = null; 7792 } else if (abiOverride != null) { 7793 cpuAbiOverride = abiOverride; 7794 } else if (settings != null) { 7795 cpuAbiOverride = settings.cpuAbiOverrideString; 7796 } 7797 7798 return cpuAbiOverride; 7799 } 7800 7801 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7802 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7803 throws PackageManagerException { 7804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7805 // If the package has children and this is the first dive in the function 7806 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7807 // whether all packages (parent and children) would be successfully scanned 7808 // before the actual scan since scanning mutates internal state and we want 7809 // to atomically install the package and its children. 7810 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7811 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7812 scanFlags |= SCAN_CHECK_ONLY; 7813 } 7814 } else { 7815 scanFlags &= ~SCAN_CHECK_ONLY; 7816 } 7817 7818 final PackageParser.Package scannedPkg; 7819 try { 7820 // Scan the parent 7821 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7822 // Scan the children 7823 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7824 for (int i = 0; i < childCount; i++) { 7825 PackageParser.Package childPkg = pkg.childPackages.get(i); 7826 scanPackageLI(childPkg, policyFlags, 7827 scanFlags, currentTime, user); 7828 } 7829 } finally { 7830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7831 } 7832 7833 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7834 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7835 } 7836 7837 return scannedPkg; 7838 } 7839 7840 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7841 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7842 boolean success = false; 7843 try { 7844 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7845 currentTime, user); 7846 success = true; 7847 return res; 7848 } finally { 7849 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7850 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7851 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7852 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7853 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7854 } 7855 } 7856 } 7857 7858 /** 7859 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7860 */ 7861 private static boolean apkHasCode(String fileName) { 7862 StrictJarFile jarFile = null; 7863 try { 7864 jarFile = new StrictJarFile(fileName, 7865 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7866 return jarFile.findEntry("classes.dex") != null; 7867 } catch (IOException ignore) { 7868 } finally { 7869 try { 7870 jarFile.close(); 7871 } catch (IOException ignore) {} 7872 } 7873 return false; 7874 } 7875 7876 /** 7877 * Enforces code policy for the package. This ensures that if an APK has 7878 * declared hasCode="true" in its manifest that the APK actually contains 7879 * code. 7880 * 7881 * @throws PackageManagerException If bytecode could not be found when it should exist 7882 */ 7883 private static void enforceCodePolicy(PackageParser.Package pkg) 7884 throws PackageManagerException { 7885 final boolean shouldHaveCode = 7886 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7887 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7888 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7889 "Package " + pkg.baseCodePath + " code is missing"); 7890 } 7891 7892 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7893 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7894 final boolean splitShouldHaveCode = 7895 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7896 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7897 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7898 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7899 } 7900 } 7901 } 7902 } 7903 7904 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7905 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7906 throws PackageManagerException { 7907 final File scanFile = new File(pkg.codePath); 7908 if (pkg.applicationInfo.getCodePath() == null || 7909 pkg.applicationInfo.getResourcePath() == null) { 7910 // Bail out. The resource and code paths haven't been set. 7911 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7912 "Code and resource paths haven't been set correctly"); 7913 } 7914 7915 // Apply policy 7916 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7917 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7918 if (pkg.applicationInfo.isDirectBootAware()) { 7919 // we're direct boot aware; set for all components 7920 for (PackageParser.Service s : pkg.services) { 7921 s.info.encryptionAware = s.info.directBootAware = true; 7922 } 7923 for (PackageParser.Provider p : pkg.providers) { 7924 p.info.encryptionAware = p.info.directBootAware = true; 7925 } 7926 for (PackageParser.Activity a : pkg.activities) { 7927 a.info.encryptionAware = a.info.directBootAware = true; 7928 } 7929 for (PackageParser.Activity r : pkg.receivers) { 7930 r.info.encryptionAware = r.info.directBootAware = true; 7931 } 7932 } 7933 } else { 7934 // Only allow system apps to be flagged as core apps. 7935 pkg.coreApp = false; 7936 // clear flags not applicable to regular apps 7937 pkg.applicationInfo.privateFlags &= 7938 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7939 pkg.applicationInfo.privateFlags &= 7940 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7941 } 7942 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7943 7944 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7945 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7946 } 7947 7948 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7949 enforceCodePolicy(pkg); 7950 } 7951 7952 if (mCustomResolverComponentName != null && 7953 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7954 setUpCustomResolverActivity(pkg); 7955 } 7956 7957 if (pkg.packageName.equals("android")) { 7958 synchronized (mPackages) { 7959 if (mAndroidApplication != null) { 7960 Slog.w(TAG, "*************************************************"); 7961 Slog.w(TAG, "Core android package being redefined. Skipping."); 7962 Slog.w(TAG, " file=" + scanFile); 7963 Slog.w(TAG, "*************************************************"); 7964 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7965 "Core android package being redefined. Skipping."); 7966 } 7967 7968 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7969 // Set up information for our fall-back user intent resolution activity. 7970 mPlatformPackage = pkg; 7971 pkg.mVersionCode = mSdkVersion; 7972 mAndroidApplication = pkg.applicationInfo; 7973 7974 if (!mResolverReplaced) { 7975 mResolveActivity.applicationInfo = mAndroidApplication; 7976 mResolveActivity.name = ResolverActivity.class.getName(); 7977 mResolveActivity.packageName = mAndroidApplication.packageName; 7978 mResolveActivity.processName = "system:ui"; 7979 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7980 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7981 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7982 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7983 mResolveActivity.exported = true; 7984 mResolveActivity.enabled = true; 7985 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7986 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7987 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7988 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7989 | ActivityInfo.CONFIG_ORIENTATION 7990 | ActivityInfo.CONFIG_KEYBOARD 7991 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7992 mResolveInfo.activityInfo = mResolveActivity; 7993 mResolveInfo.priority = 0; 7994 mResolveInfo.preferredOrder = 0; 7995 mResolveInfo.match = 0; 7996 mResolveComponentName = new ComponentName( 7997 mAndroidApplication.packageName, mResolveActivity.name); 7998 } 7999 } 8000 } 8001 } 8002 8003 if (DEBUG_PACKAGE_SCANNING) { 8004 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8005 Log.d(TAG, "Scanning package " + pkg.packageName); 8006 } 8007 8008 synchronized (mPackages) { 8009 if (mPackages.containsKey(pkg.packageName) 8010 || mSharedLibraries.containsKey(pkg.packageName)) { 8011 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8012 "Application package " + pkg.packageName 8013 + " already installed. Skipping duplicate."); 8014 } 8015 8016 // If we're only installing presumed-existing packages, require that the 8017 // scanned APK is both already known and at the path previously established 8018 // for it. Previously unknown packages we pick up normally, but if we have an 8019 // a priori expectation about this package's install presence, enforce it. 8020 // With a singular exception for new system packages. When an OTA contains 8021 // a new system package, we allow the codepath to change from a system location 8022 // to the user-installed location. If we don't allow this change, any newer, 8023 // user-installed version of the application will be ignored. 8024 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8025 if (mExpectingBetter.containsKey(pkg.packageName)) { 8026 logCriticalInfo(Log.WARN, 8027 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8028 } else { 8029 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8030 if (known != null) { 8031 if (DEBUG_PACKAGE_SCANNING) { 8032 Log.d(TAG, "Examining " + pkg.codePath 8033 + " and requiring known paths " + known.codePathString 8034 + " & " + known.resourcePathString); 8035 } 8036 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8037 || !pkg.applicationInfo.getResourcePath().equals( 8038 known.resourcePathString)) { 8039 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8040 "Application package " + pkg.packageName 8041 + " found at " + pkg.applicationInfo.getCodePath() 8042 + " but expected at " + known.codePathString 8043 + "; ignoring."); 8044 } 8045 } 8046 } 8047 } 8048 } 8049 8050 // Initialize package source and resource directories 8051 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8052 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8053 8054 SharedUserSetting suid = null; 8055 PackageSetting pkgSetting = null; 8056 8057 if (!isSystemApp(pkg)) { 8058 // Only system apps can use these features. 8059 pkg.mOriginalPackages = null; 8060 pkg.mRealPackage = null; 8061 pkg.mAdoptPermissions = null; 8062 } 8063 8064 // Getting the package setting may have a side-effect, so if we 8065 // are only checking if scan would succeed, stash a copy of the 8066 // old setting to restore at the end. 8067 PackageSetting nonMutatedPs = null; 8068 8069 // writer 8070 synchronized (mPackages) { 8071 if (pkg.mSharedUserId != null) { 8072 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8073 if (suid == null) { 8074 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8075 "Creating application package " + pkg.packageName 8076 + " for shared user failed"); 8077 } 8078 if (DEBUG_PACKAGE_SCANNING) { 8079 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8080 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8081 + "): packages=" + suid.packages); 8082 } 8083 } 8084 8085 // Check if we are renaming from an original package name. 8086 PackageSetting origPackage = null; 8087 String realName = null; 8088 if (pkg.mOriginalPackages != null) { 8089 // This package may need to be renamed to a previously 8090 // installed name. Let's check on that... 8091 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8092 if (pkg.mOriginalPackages.contains(renamed)) { 8093 // This package had originally been installed as the 8094 // original name, and we have already taken care of 8095 // transitioning to the new one. Just update the new 8096 // one to continue using the old name. 8097 realName = pkg.mRealPackage; 8098 if (!pkg.packageName.equals(renamed)) { 8099 // Callers into this function may have already taken 8100 // care of renaming the package; only do it here if 8101 // it is not already done. 8102 pkg.setPackageName(renamed); 8103 } 8104 8105 } else { 8106 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8107 if ((origPackage = mSettings.peekPackageLPr( 8108 pkg.mOriginalPackages.get(i))) != null) { 8109 // We do have the package already installed under its 8110 // original name... should we use it? 8111 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8112 // New package is not compatible with original. 8113 origPackage = null; 8114 continue; 8115 } else if (origPackage.sharedUser != null) { 8116 // Make sure uid is compatible between packages. 8117 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8118 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8119 + " to " + pkg.packageName + ": old uid " 8120 + origPackage.sharedUser.name 8121 + " differs from " + pkg.mSharedUserId); 8122 origPackage = null; 8123 continue; 8124 } 8125 // TODO: Add case when shared user id is added [b/28144775] 8126 } else { 8127 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8128 + pkg.packageName + " to old name " + origPackage.name); 8129 } 8130 break; 8131 } 8132 } 8133 } 8134 } 8135 8136 if (mTransferedPackages.contains(pkg.packageName)) { 8137 Slog.w(TAG, "Package " + pkg.packageName 8138 + " was transferred to another, but its .apk remains"); 8139 } 8140 8141 // See comments in nonMutatedPs declaration 8142 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8143 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8144 if (foundPs != null) { 8145 nonMutatedPs = new PackageSetting(foundPs); 8146 } 8147 } 8148 8149 // Just create the setting, don't add it yet. For already existing packages 8150 // the PkgSetting exists already and doesn't have to be created. 8151 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8152 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8153 pkg.applicationInfo.primaryCpuAbi, 8154 pkg.applicationInfo.secondaryCpuAbi, 8155 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8156 user, false); 8157 if (pkgSetting == null) { 8158 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8159 "Creating application package " + pkg.packageName + " failed"); 8160 } 8161 8162 if (pkgSetting.origPackage != null) { 8163 // If we are first transitioning from an original package, 8164 // fix up the new package's name now. We need to do this after 8165 // looking up the package under its new name, so getPackageLP 8166 // can take care of fiddling things correctly. 8167 pkg.setPackageName(origPackage.name); 8168 8169 // File a report about this. 8170 String msg = "New package " + pkgSetting.realName 8171 + " renamed to replace old package " + pkgSetting.name; 8172 reportSettingsProblem(Log.WARN, msg); 8173 8174 // Make a note of it. 8175 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8176 mTransferedPackages.add(origPackage.name); 8177 } 8178 8179 // No longer need to retain this. 8180 pkgSetting.origPackage = null; 8181 } 8182 8183 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8184 // Make a note of it. 8185 mTransferedPackages.add(pkg.packageName); 8186 } 8187 8188 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8189 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8190 } 8191 8192 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8193 // Check all shared libraries and map to their actual file path. 8194 // We only do this here for apps not on a system dir, because those 8195 // are the only ones that can fail an install due to this. We 8196 // will take care of the system apps by updating all of their 8197 // library paths after the scan is done. 8198 updateSharedLibrariesLPw(pkg, null); 8199 } 8200 8201 if (mFoundPolicyFile) { 8202 SELinuxMMAC.assignSeinfoValue(pkg); 8203 } 8204 8205 pkg.applicationInfo.uid = pkgSetting.appId; 8206 pkg.mExtras = pkgSetting; 8207 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8208 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8209 // We just determined the app is signed correctly, so bring 8210 // over the latest parsed certs. 8211 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8212 } else { 8213 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8214 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8215 "Package " + pkg.packageName + " upgrade keys do not match the " 8216 + "previously installed version"); 8217 } else { 8218 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8219 String msg = "System package " + pkg.packageName 8220 + " signature changed; retaining data."; 8221 reportSettingsProblem(Log.WARN, msg); 8222 } 8223 } 8224 } else { 8225 try { 8226 verifySignaturesLP(pkgSetting, pkg); 8227 // We just determined the app is signed correctly, so bring 8228 // over the latest parsed certs. 8229 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8230 } catch (PackageManagerException e) { 8231 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8232 throw e; 8233 } 8234 // The signature has changed, but this package is in the system 8235 // image... let's recover! 8236 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8237 // However... if this package is part of a shared user, but it 8238 // doesn't match the signature of the shared user, let's fail. 8239 // What this means is that you can't change the signatures 8240 // associated with an overall shared user, which doesn't seem all 8241 // that unreasonable. 8242 if (pkgSetting.sharedUser != null) { 8243 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8244 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8245 throw new PackageManagerException( 8246 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8247 "Signature mismatch for shared user: " 8248 + pkgSetting.sharedUser); 8249 } 8250 } 8251 // File a report about this. 8252 String msg = "System package " + pkg.packageName 8253 + " signature changed; retaining data."; 8254 reportSettingsProblem(Log.WARN, msg); 8255 } 8256 } 8257 // Verify that this new package doesn't have any content providers 8258 // that conflict with existing packages. Only do this if the 8259 // package isn't already installed, since we don't want to break 8260 // things that are installed. 8261 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8262 final int N = pkg.providers.size(); 8263 int i; 8264 for (i=0; i<N; i++) { 8265 PackageParser.Provider p = pkg.providers.get(i); 8266 if (p.info.authority != null) { 8267 String names[] = p.info.authority.split(";"); 8268 for (int j = 0; j < names.length; j++) { 8269 if (mProvidersByAuthority.containsKey(names[j])) { 8270 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8271 final String otherPackageName = 8272 ((other != null && other.getComponentName() != null) ? 8273 other.getComponentName().getPackageName() : "?"); 8274 throw new PackageManagerException( 8275 INSTALL_FAILED_CONFLICTING_PROVIDER, 8276 "Can't install because provider name " + names[j] 8277 + " (in package " + pkg.applicationInfo.packageName 8278 + ") is already used by " + otherPackageName); 8279 } 8280 } 8281 } 8282 } 8283 } 8284 8285 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8286 // This package wants to adopt ownership of permissions from 8287 // another package. 8288 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8289 final String origName = pkg.mAdoptPermissions.get(i); 8290 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8291 if (orig != null) { 8292 if (verifyPackageUpdateLPr(orig, pkg)) { 8293 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8294 + pkg.packageName); 8295 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8296 } 8297 } 8298 } 8299 } 8300 } 8301 8302 final String pkgName = pkg.packageName; 8303 8304 final long scanFileTime = scanFile.lastModified(); 8305 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8306 pkg.applicationInfo.processName = fixProcessName( 8307 pkg.applicationInfo.packageName, 8308 pkg.applicationInfo.processName, 8309 pkg.applicationInfo.uid); 8310 8311 if (pkg != mPlatformPackage) { 8312 // Get all of our default paths setup 8313 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8314 } 8315 8316 final String path = scanFile.getPath(); 8317 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8318 8319 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8320 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8321 8322 // Some system apps still use directory structure for native libraries 8323 // in which case we might end up not detecting abi solely based on apk 8324 // structure. Try to detect abi based on directory structure. 8325 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8326 pkg.applicationInfo.primaryCpuAbi == null) { 8327 setBundledAppAbisAndRoots(pkg, pkgSetting); 8328 setNativeLibraryPaths(pkg); 8329 } 8330 8331 } else { 8332 if ((scanFlags & SCAN_MOVE) != 0) { 8333 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8334 // but we already have this packages package info in the PackageSetting. We just 8335 // use that and derive the native library path based on the new codepath. 8336 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8337 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8338 } 8339 8340 // Set native library paths again. For moves, the path will be updated based on the 8341 // ABIs we've determined above. For non-moves, the path will be updated based on the 8342 // ABIs we determined during compilation, but the path will depend on the final 8343 // package path (after the rename away from the stage path). 8344 setNativeLibraryPaths(pkg); 8345 } 8346 8347 // This is a special case for the "system" package, where the ABI is 8348 // dictated by the zygote configuration (and init.rc). We should keep track 8349 // of this ABI so that we can deal with "normal" applications that run under 8350 // the same UID correctly. 8351 if (mPlatformPackage == pkg) { 8352 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8353 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8354 } 8355 8356 // If there's a mismatch between the abi-override in the package setting 8357 // and the abiOverride specified for the install. Warn about this because we 8358 // would've already compiled the app without taking the package setting into 8359 // account. 8360 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8361 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8362 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8363 " for package " + pkg.packageName); 8364 } 8365 } 8366 8367 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8368 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8369 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8370 8371 // Copy the derived override back to the parsed package, so that we can 8372 // update the package settings accordingly. 8373 pkg.cpuAbiOverride = cpuAbiOverride; 8374 8375 if (DEBUG_ABI_SELECTION) { 8376 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8377 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8378 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8379 } 8380 8381 // Push the derived path down into PackageSettings so we know what to 8382 // clean up at uninstall time. 8383 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8384 8385 if (DEBUG_ABI_SELECTION) { 8386 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8387 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8388 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8389 } 8390 8391 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8392 // We don't do this here during boot because we can do it all 8393 // at once after scanning all existing packages. 8394 // 8395 // We also do this *before* we perform dexopt on this package, so that 8396 // we can avoid redundant dexopts, and also to make sure we've got the 8397 // code and package path correct. 8398 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8399 pkg, true /* boot complete */); 8400 } 8401 8402 if (mFactoryTest && pkg.requestedPermissions.contains( 8403 android.Manifest.permission.FACTORY_TEST)) { 8404 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8405 } 8406 8407 ArrayList<PackageParser.Package> clientLibPkgs = null; 8408 8409 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8410 if (nonMutatedPs != null) { 8411 synchronized (mPackages) { 8412 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8413 } 8414 } 8415 return pkg; 8416 } 8417 8418 // Only privileged apps and updated privileged apps can add child packages. 8419 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8420 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8421 throw new PackageManagerException("Only privileged apps and updated " 8422 + "privileged apps can add child packages. Ignoring package " 8423 + pkg.packageName); 8424 } 8425 final int childCount = pkg.childPackages.size(); 8426 for (int i = 0; i < childCount; i++) { 8427 PackageParser.Package childPkg = pkg.childPackages.get(i); 8428 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8429 childPkg.packageName)) { 8430 throw new PackageManagerException("Cannot override a child package of " 8431 + "another disabled system app. Ignoring package " + pkg.packageName); 8432 } 8433 } 8434 } 8435 8436 // writer 8437 synchronized (mPackages) { 8438 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8439 // Only system apps can add new shared libraries. 8440 if (pkg.libraryNames != null) { 8441 for (int i=0; i<pkg.libraryNames.size(); i++) { 8442 String name = pkg.libraryNames.get(i); 8443 boolean allowed = false; 8444 if (pkg.isUpdatedSystemApp()) { 8445 // New library entries can only be added through the 8446 // system image. This is important to get rid of a lot 8447 // of nasty edge cases: for example if we allowed a non- 8448 // system update of the app to add a library, then uninstalling 8449 // the update would make the library go away, and assumptions 8450 // we made such as through app install filtering would now 8451 // have allowed apps on the device which aren't compatible 8452 // with it. Better to just have the restriction here, be 8453 // conservative, and create many fewer cases that can negatively 8454 // impact the user experience. 8455 final PackageSetting sysPs = mSettings 8456 .getDisabledSystemPkgLPr(pkg.packageName); 8457 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8458 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8459 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8460 allowed = true; 8461 break; 8462 } 8463 } 8464 } 8465 } else { 8466 allowed = true; 8467 } 8468 if (allowed) { 8469 if (!mSharedLibraries.containsKey(name)) { 8470 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8471 } else if (!name.equals(pkg.packageName)) { 8472 Slog.w(TAG, "Package " + pkg.packageName + " library " 8473 + name + " already exists; skipping"); 8474 } 8475 } else { 8476 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8477 + name + " that is not declared on system image; skipping"); 8478 } 8479 } 8480 if ((scanFlags & SCAN_BOOTING) == 0) { 8481 // If we are not booting, we need to update any applications 8482 // that are clients of our shared library. If we are booting, 8483 // this will all be done once the scan is complete. 8484 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8485 } 8486 } 8487 } 8488 } 8489 8490 if ((scanFlags & SCAN_BOOTING) != 0) { 8491 // No apps can run during boot scan, so they don't need to be frozen 8492 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8493 // Caller asked to not kill app, so it's probably not frozen 8494 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8495 // Caller asked us to ignore frozen check for some reason; they 8496 // probably didn't know the package name 8497 } else { 8498 // We're doing major surgery on this package, so it better be frozen 8499 // right now to keep it from launching 8500 checkPackageFrozen(pkgName); 8501 } 8502 8503 // Also need to kill any apps that are dependent on the library. 8504 if (clientLibPkgs != null) { 8505 for (int i=0; i<clientLibPkgs.size(); i++) { 8506 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8507 killApplication(clientPkg.applicationInfo.packageName, 8508 clientPkg.applicationInfo.uid, "update lib"); 8509 } 8510 } 8511 8512 // Make sure we're not adding any bogus keyset info 8513 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8514 ksms.assertScannedPackageValid(pkg); 8515 8516 // writer 8517 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8518 8519 boolean createIdmapFailed = false; 8520 synchronized (mPackages) { 8521 // We don't expect installation to fail beyond this point 8522 8523 // Add the new setting to mSettings 8524 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8525 // Add the new setting to mPackages 8526 mPackages.put(pkg.applicationInfo.packageName, pkg); 8527 // Make sure we don't accidentally delete its data. 8528 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8529 while (iter.hasNext()) { 8530 PackageCleanItem item = iter.next(); 8531 if (pkgName.equals(item.packageName)) { 8532 iter.remove(); 8533 } 8534 } 8535 8536 // Take care of first install / last update times. 8537 if (currentTime != 0) { 8538 if (pkgSetting.firstInstallTime == 0) { 8539 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8540 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8541 pkgSetting.lastUpdateTime = currentTime; 8542 } 8543 } else if (pkgSetting.firstInstallTime == 0) { 8544 // We need *something*. Take time time stamp of the file. 8545 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8546 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8547 if (scanFileTime != pkgSetting.timeStamp) { 8548 // A package on the system image has changed; consider this 8549 // to be an update. 8550 pkgSetting.lastUpdateTime = scanFileTime; 8551 } 8552 } 8553 8554 // Add the package's KeySets to the global KeySetManagerService 8555 ksms.addScannedPackageLPw(pkg); 8556 8557 int N = pkg.providers.size(); 8558 StringBuilder r = null; 8559 int i; 8560 for (i=0; i<N; i++) { 8561 PackageParser.Provider p = pkg.providers.get(i); 8562 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8563 p.info.processName, pkg.applicationInfo.uid); 8564 mProviders.addProvider(p); 8565 p.syncable = p.info.isSyncable; 8566 if (p.info.authority != null) { 8567 String names[] = p.info.authority.split(";"); 8568 p.info.authority = null; 8569 for (int j = 0; j < names.length; j++) { 8570 if (j == 1 && p.syncable) { 8571 // We only want the first authority for a provider to possibly be 8572 // syncable, so if we already added this provider using a different 8573 // authority clear the syncable flag. We copy the provider before 8574 // changing it because the mProviders object contains a reference 8575 // to a provider that we don't want to change. 8576 // Only do this for the second authority since the resulting provider 8577 // object can be the same for all future authorities for this provider. 8578 p = new PackageParser.Provider(p); 8579 p.syncable = false; 8580 } 8581 if (!mProvidersByAuthority.containsKey(names[j])) { 8582 mProvidersByAuthority.put(names[j], p); 8583 if (p.info.authority == null) { 8584 p.info.authority = names[j]; 8585 } else { 8586 p.info.authority = p.info.authority + ";" + names[j]; 8587 } 8588 if (DEBUG_PACKAGE_SCANNING) { 8589 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8590 Log.d(TAG, "Registered content provider: " + names[j] 8591 + ", className = " + p.info.name + ", isSyncable = " 8592 + p.info.isSyncable); 8593 } 8594 } else { 8595 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8596 Slog.w(TAG, "Skipping provider name " + names[j] + 8597 " (in package " + pkg.applicationInfo.packageName + 8598 "): name already used by " 8599 + ((other != null && other.getComponentName() != null) 8600 ? other.getComponentName().getPackageName() : "?")); 8601 } 8602 } 8603 } 8604 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8605 if (r == null) { 8606 r = new StringBuilder(256); 8607 } else { 8608 r.append(' '); 8609 } 8610 r.append(p.info.name); 8611 } 8612 } 8613 if (r != null) { 8614 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8615 } 8616 8617 N = pkg.services.size(); 8618 r = null; 8619 for (i=0; i<N; i++) { 8620 PackageParser.Service s = pkg.services.get(i); 8621 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8622 s.info.processName, pkg.applicationInfo.uid); 8623 mServices.addService(s); 8624 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8625 if (r == null) { 8626 r = new StringBuilder(256); 8627 } else { 8628 r.append(' '); 8629 } 8630 r.append(s.info.name); 8631 } 8632 } 8633 if (r != null) { 8634 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8635 } 8636 8637 N = pkg.receivers.size(); 8638 r = null; 8639 for (i=0; i<N; i++) { 8640 PackageParser.Activity a = pkg.receivers.get(i); 8641 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8642 a.info.processName, pkg.applicationInfo.uid); 8643 mReceivers.addActivity(a, "receiver"); 8644 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8645 if (r == null) { 8646 r = new StringBuilder(256); 8647 } else { 8648 r.append(' '); 8649 } 8650 r.append(a.info.name); 8651 } 8652 } 8653 if (r != null) { 8654 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8655 } 8656 8657 N = pkg.activities.size(); 8658 r = null; 8659 for (i=0; i<N; i++) { 8660 PackageParser.Activity a = pkg.activities.get(i); 8661 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8662 a.info.processName, pkg.applicationInfo.uid); 8663 mActivities.addActivity(a, "activity"); 8664 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8665 if (r == null) { 8666 r = new StringBuilder(256); 8667 } else { 8668 r.append(' '); 8669 } 8670 r.append(a.info.name); 8671 } 8672 } 8673 if (r != null) { 8674 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8675 } 8676 8677 N = pkg.permissionGroups.size(); 8678 r = null; 8679 for (i=0; i<N; i++) { 8680 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8681 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8682 if (cur == null) { 8683 mPermissionGroups.put(pg.info.name, pg); 8684 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8685 if (r == null) { 8686 r = new StringBuilder(256); 8687 } else { 8688 r.append(' '); 8689 } 8690 r.append(pg.info.name); 8691 } 8692 } else { 8693 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8694 + pg.info.packageName + " ignored: original from " 8695 + cur.info.packageName); 8696 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8697 if (r == null) { 8698 r = new StringBuilder(256); 8699 } else { 8700 r.append(' '); 8701 } 8702 r.append("DUP:"); 8703 r.append(pg.info.name); 8704 } 8705 } 8706 } 8707 if (r != null) { 8708 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8709 } 8710 8711 N = pkg.permissions.size(); 8712 r = null; 8713 for (i=0; i<N; i++) { 8714 PackageParser.Permission p = pkg.permissions.get(i); 8715 8716 // Assume by default that we did not install this permission into the system. 8717 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8718 8719 // Now that permission groups have a special meaning, we ignore permission 8720 // groups for legacy apps to prevent unexpected behavior. In particular, 8721 // permissions for one app being granted to someone just becase they happen 8722 // to be in a group defined by another app (before this had no implications). 8723 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8724 p.group = mPermissionGroups.get(p.info.group); 8725 // Warn for a permission in an unknown group. 8726 if (p.info.group != null && p.group == null) { 8727 Slog.w(TAG, "Permission " + p.info.name + " from package " 8728 + p.info.packageName + " in an unknown group " + p.info.group); 8729 } 8730 } 8731 8732 ArrayMap<String, BasePermission> permissionMap = 8733 p.tree ? mSettings.mPermissionTrees 8734 : mSettings.mPermissions; 8735 BasePermission bp = permissionMap.get(p.info.name); 8736 8737 // Allow system apps to redefine non-system permissions 8738 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8739 final boolean currentOwnerIsSystem = (bp.perm != null 8740 && isSystemApp(bp.perm.owner)); 8741 if (isSystemApp(p.owner)) { 8742 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8743 // It's a built-in permission and no owner, take ownership now 8744 bp.packageSetting = pkgSetting; 8745 bp.perm = p; 8746 bp.uid = pkg.applicationInfo.uid; 8747 bp.sourcePackage = p.info.packageName; 8748 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8749 } else if (!currentOwnerIsSystem) { 8750 String msg = "New decl " + p.owner + " of permission " 8751 + p.info.name + " is system; overriding " + bp.sourcePackage; 8752 reportSettingsProblem(Log.WARN, msg); 8753 bp = null; 8754 } 8755 } 8756 } 8757 8758 if (bp == null) { 8759 bp = new BasePermission(p.info.name, p.info.packageName, 8760 BasePermission.TYPE_NORMAL); 8761 permissionMap.put(p.info.name, bp); 8762 } 8763 8764 if (bp.perm == null) { 8765 if (bp.sourcePackage == null 8766 || bp.sourcePackage.equals(p.info.packageName)) { 8767 BasePermission tree = findPermissionTreeLP(p.info.name); 8768 if (tree == null 8769 || tree.sourcePackage.equals(p.info.packageName)) { 8770 bp.packageSetting = pkgSetting; 8771 bp.perm = p; 8772 bp.uid = pkg.applicationInfo.uid; 8773 bp.sourcePackage = p.info.packageName; 8774 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8775 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8776 if (r == null) { 8777 r = new StringBuilder(256); 8778 } else { 8779 r.append(' '); 8780 } 8781 r.append(p.info.name); 8782 } 8783 } else { 8784 Slog.w(TAG, "Permission " + p.info.name + " from package " 8785 + p.info.packageName + " ignored: base tree " 8786 + tree.name + " is from package " 8787 + tree.sourcePackage); 8788 } 8789 } else { 8790 Slog.w(TAG, "Permission " + p.info.name + " from package " 8791 + p.info.packageName + " ignored: original from " 8792 + bp.sourcePackage); 8793 } 8794 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8795 if (r == null) { 8796 r = new StringBuilder(256); 8797 } else { 8798 r.append(' '); 8799 } 8800 r.append("DUP:"); 8801 r.append(p.info.name); 8802 } 8803 if (bp.perm == p) { 8804 bp.protectionLevel = p.info.protectionLevel; 8805 } 8806 } 8807 8808 if (r != null) { 8809 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8810 } 8811 8812 N = pkg.instrumentation.size(); 8813 r = null; 8814 for (i=0; i<N; i++) { 8815 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8816 a.info.packageName = pkg.applicationInfo.packageName; 8817 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8818 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8819 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8820 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8821 a.info.dataDir = pkg.applicationInfo.dataDir; 8822 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8823 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8824 8825 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8826 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8827 mInstrumentation.put(a.getComponentName(), a); 8828 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8829 if (r == null) { 8830 r = new StringBuilder(256); 8831 } else { 8832 r.append(' '); 8833 } 8834 r.append(a.info.name); 8835 } 8836 } 8837 if (r != null) { 8838 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8839 } 8840 8841 if (pkg.protectedBroadcasts != null) { 8842 N = pkg.protectedBroadcasts.size(); 8843 for (i=0; i<N; i++) { 8844 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8845 } 8846 } 8847 8848 pkgSetting.setTimeStamp(scanFileTime); 8849 8850 // Create idmap files for pairs of (packages, overlay packages). 8851 // Note: "android", ie framework-res.apk, is handled by native layers. 8852 if (pkg.mOverlayTarget != null) { 8853 // This is an overlay package. 8854 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8855 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8856 mOverlays.put(pkg.mOverlayTarget, 8857 new ArrayMap<String, PackageParser.Package>()); 8858 } 8859 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8860 map.put(pkg.packageName, pkg); 8861 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8862 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8863 createIdmapFailed = true; 8864 } 8865 } 8866 } else if (mOverlays.containsKey(pkg.packageName) && 8867 !pkg.packageName.equals("android")) { 8868 // This is a regular package, with one or more known overlay packages. 8869 createIdmapsForPackageLI(pkg); 8870 } 8871 } 8872 8873 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8874 8875 if (createIdmapFailed) { 8876 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8877 "scanPackageLI failed to createIdmap"); 8878 } 8879 return pkg; 8880 } 8881 8882 /** 8883 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8884 * is derived purely on the basis of the contents of {@code scanFile} and 8885 * {@code cpuAbiOverride}. 8886 * 8887 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8888 */ 8889 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8890 String cpuAbiOverride, boolean extractLibs) 8891 throws PackageManagerException { 8892 // TODO: We can probably be smarter about this stuff. For installed apps, 8893 // we can calculate this information at install time once and for all. For 8894 // system apps, we can probably assume that this information doesn't change 8895 // after the first boot scan. As things stand, we do lots of unnecessary work. 8896 8897 // Give ourselves some initial paths; we'll come back for another 8898 // pass once we've determined ABI below. 8899 setNativeLibraryPaths(pkg); 8900 8901 // We would never need to extract libs for forward-locked and external packages, 8902 // since the container service will do it for us. We shouldn't attempt to 8903 // extract libs from system app when it was not updated. 8904 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8905 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8906 extractLibs = false; 8907 } 8908 8909 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8910 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8911 8912 NativeLibraryHelper.Handle handle = null; 8913 try { 8914 handle = NativeLibraryHelper.Handle.create(pkg); 8915 // TODO(multiArch): This can be null for apps that didn't go through the 8916 // usual installation process. We can calculate it again, like we 8917 // do during install time. 8918 // 8919 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8920 // unnecessary. 8921 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8922 8923 // Null out the abis so that they can be recalculated. 8924 pkg.applicationInfo.primaryCpuAbi = null; 8925 pkg.applicationInfo.secondaryCpuAbi = null; 8926 if (isMultiArch(pkg.applicationInfo)) { 8927 // Warn if we've set an abiOverride for multi-lib packages.. 8928 // By definition, we need to copy both 32 and 64 bit libraries for 8929 // such packages. 8930 if (pkg.cpuAbiOverride != null 8931 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8932 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8933 } 8934 8935 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8936 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8937 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8938 if (extractLibs) { 8939 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8940 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8941 useIsaSpecificSubdirs); 8942 } else { 8943 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8944 } 8945 } 8946 8947 maybeThrowExceptionForMultiArchCopy( 8948 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8949 8950 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8951 if (extractLibs) { 8952 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8953 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8954 useIsaSpecificSubdirs); 8955 } else { 8956 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8957 } 8958 } 8959 8960 maybeThrowExceptionForMultiArchCopy( 8961 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8962 8963 if (abi64 >= 0) { 8964 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8965 } 8966 8967 if (abi32 >= 0) { 8968 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8969 if (abi64 >= 0) { 8970 if (pkg.use32bitAbi) { 8971 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8972 pkg.applicationInfo.primaryCpuAbi = abi; 8973 } else { 8974 pkg.applicationInfo.secondaryCpuAbi = abi; 8975 } 8976 } else { 8977 pkg.applicationInfo.primaryCpuAbi = abi; 8978 } 8979 } 8980 8981 } else { 8982 String[] abiList = (cpuAbiOverride != null) ? 8983 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8984 8985 // Enable gross and lame hacks for apps that are built with old 8986 // SDK tools. We must scan their APKs for renderscript bitcode and 8987 // not launch them if it's present. Don't bother checking on devices 8988 // that don't have 64 bit support. 8989 boolean needsRenderScriptOverride = false; 8990 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8991 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8992 abiList = Build.SUPPORTED_32_BIT_ABIS; 8993 needsRenderScriptOverride = true; 8994 } 8995 8996 final int copyRet; 8997 if (extractLibs) { 8998 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8999 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9000 } else { 9001 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9002 } 9003 9004 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9005 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9006 "Error unpackaging native libs for app, errorCode=" + copyRet); 9007 } 9008 9009 if (copyRet >= 0) { 9010 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9011 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9012 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9013 } else if (needsRenderScriptOverride) { 9014 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9015 } 9016 } 9017 } catch (IOException ioe) { 9018 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9019 } finally { 9020 IoUtils.closeQuietly(handle); 9021 } 9022 9023 // Now that we've calculated the ABIs and determined if it's an internal app, 9024 // we will go ahead and populate the nativeLibraryPath. 9025 setNativeLibraryPaths(pkg); 9026 } 9027 9028 /** 9029 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9030 * i.e, so that all packages can be run inside a single process if required. 9031 * 9032 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9033 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9034 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9035 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9036 * updating a package that belongs to a shared user. 9037 * 9038 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9039 * adds unnecessary complexity. 9040 */ 9041 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9042 PackageParser.Package scannedPackage, boolean bootComplete) { 9043 String requiredInstructionSet = null; 9044 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9045 requiredInstructionSet = VMRuntime.getInstructionSet( 9046 scannedPackage.applicationInfo.primaryCpuAbi); 9047 } 9048 9049 PackageSetting requirer = null; 9050 for (PackageSetting ps : packagesForUser) { 9051 // If packagesForUser contains scannedPackage, we skip it. This will happen 9052 // when scannedPackage is an update of an existing package. Without this check, 9053 // we will never be able to change the ABI of any package belonging to a shared 9054 // user, even if it's compatible with other packages. 9055 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9056 if (ps.primaryCpuAbiString == null) { 9057 continue; 9058 } 9059 9060 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9061 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9062 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9063 // this but there's not much we can do. 9064 String errorMessage = "Instruction set mismatch, " 9065 + ((requirer == null) ? "[caller]" : requirer) 9066 + " requires " + requiredInstructionSet + " whereas " + ps 9067 + " requires " + instructionSet; 9068 Slog.w(TAG, errorMessage); 9069 } 9070 9071 if (requiredInstructionSet == null) { 9072 requiredInstructionSet = instructionSet; 9073 requirer = ps; 9074 } 9075 } 9076 } 9077 9078 if (requiredInstructionSet != null) { 9079 String adjustedAbi; 9080 if (requirer != null) { 9081 // requirer != null implies that either scannedPackage was null or that scannedPackage 9082 // did not require an ABI, in which case we have to adjust scannedPackage to match 9083 // the ABI of the set (which is the same as requirer's ABI) 9084 adjustedAbi = requirer.primaryCpuAbiString; 9085 if (scannedPackage != null) { 9086 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9087 } 9088 } else { 9089 // requirer == null implies that we're updating all ABIs in the set to 9090 // match scannedPackage. 9091 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9092 } 9093 9094 for (PackageSetting ps : packagesForUser) { 9095 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9096 if (ps.primaryCpuAbiString != null) { 9097 continue; 9098 } 9099 9100 ps.primaryCpuAbiString = adjustedAbi; 9101 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9102 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9103 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9104 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9105 + " (requirer=" 9106 + (requirer == null ? "null" : requirer.pkg.packageName) 9107 + ", scannedPackage=" 9108 + (scannedPackage != null ? scannedPackage.packageName : "null") 9109 + ")"); 9110 try { 9111 mInstaller.rmdex(ps.codePathString, 9112 getDexCodeInstructionSet(getPreferredInstructionSet())); 9113 } catch (InstallerException ignored) { 9114 } 9115 } 9116 } 9117 } 9118 } 9119 } 9120 9121 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9122 synchronized (mPackages) { 9123 mResolverReplaced = true; 9124 // Set up information for custom user intent resolution activity. 9125 mResolveActivity.applicationInfo = pkg.applicationInfo; 9126 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9127 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9128 mResolveActivity.processName = pkg.applicationInfo.packageName; 9129 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9130 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9131 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9132 mResolveActivity.theme = 0; 9133 mResolveActivity.exported = true; 9134 mResolveActivity.enabled = true; 9135 mResolveInfo.activityInfo = mResolveActivity; 9136 mResolveInfo.priority = 0; 9137 mResolveInfo.preferredOrder = 0; 9138 mResolveInfo.match = 0; 9139 mResolveComponentName = mCustomResolverComponentName; 9140 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9141 mResolveComponentName); 9142 } 9143 } 9144 9145 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9146 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9147 9148 // Set up information for ephemeral installer activity 9149 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9150 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9151 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9152 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9153 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9154 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9155 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9156 mEphemeralInstallerActivity.theme = 0; 9157 mEphemeralInstallerActivity.exported = true; 9158 mEphemeralInstallerActivity.enabled = true; 9159 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9160 mEphemeralInstallerInfo.priority = 0; 9161 mEphemeralInstallerInfo.preferredOrder = 0; 9162 mEphemeralInstallerInfo.match = 0; 9163 9164 if (DEBUG_EPHEMERAL) { 9165 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9166 } 9167 } 9168 9169 private static String calculateBundledApkRoot(final String codePathString) { 9170 final File codePath = new File(codePathString); 9171 final File codeRoot; 9172 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9173 codeRoot = Environment.getRootDirectory(); 9174 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9175 codeRoot = Environment.getOemDirectory(); 9176 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9177 codeRoot = Environment.getVendorDirectory(); 9178 } else { 9179 // Unrecognized code path; take its top real segment as the apk root: 9180 // e.g. /something/app/blah.apk => /something 9181 try { 9182 File f = codePath.getCanonicalFile(); 9183 File parent = f.getParentFile(); // non-null because codePath is a file 9184 File tmp; 9185 while ((tmp = parent.getParentFile()) != null) { 9186 f = parent; 9187 parent = tmp; 9188 } 9189 codeRoot = f; 9190 Slog.w(TAG, "Unrecognized code path " 9191 + codePath + " - using " + codeRoot); 9192 } catch (IOException e) { 9193 // Can't canonicalize the code path -- shenanigans? 9194 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9195 return Environment.getRootDirectory().getPath(); 9196 } 9197 } 9198 return codeRoot.getPath(); 9199 } 9200 9201 /** 9202 * Derive and set the location of native libraries for the given package, 9203 * which varies depending on where and how the package was installed. 9204 */ 9205 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9206 final ApplicationInfo info = pkg.applicationInfo; 9207 final String codePath = pkg.codePath; 9208 final File codeFile = new File(codePath); 9209 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9210 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9211 9212 info.nativeLibraryRootDir = null; 9213 info.nativeLibraryRootRequiresIsa = false; 9214 info.nativeLibraryDir = null; 9215 info.secondaryNativeLibraryDir = null; 9216 9217 if (isApkFile(codeFile)) { 9218 // Monolithic install 9219 if (bundledApp) { 9220 // If "/system/lib64/apkname" exists, assume that is the per-package 9221 // native library directory to use; otherwise use "/system/lib/apkname". 9222 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9223 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9224 getPrimaryInstructionSet(info)); 9225 9226 // This is a bundled system app so choose the path based on the ABI. 9227 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9228 // is just the default path. 9229 final String apkName = deriveCodePathName(codePath); 9230 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9231 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9232 apkName).getAbsolutePath(); 9233 9234 if (info.secondaryCpuAbi != null) { 9235 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9236 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9237 secondaryLibDir, apkName).getAbsolutePath(); 9238 } 9239 } else if (asecApp) { 9240 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9241 .getAbsolutePath(); 9242 } else { 9243 final String apkName = deriveCodePathName(codePath); 9244 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9245 .getAbsolutePath(); 9246 } 9247 9248 info.nativeLibraryRootRequiresIsa = false; 9249 info.nativeLibraryDir = info.nativeLibraryRootDir; 9250 } else { 9251 // Cluster install 9252 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9253 info.nativeLibraryRootRequiresIsa = true; 9254 9255 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9256 getPrimaryInstructionSet(info)).getAbsolutePath(); 9257 9258 if (info.secondaryCpuAbi != null) { 9259 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9260 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9261 } 9262 } 9263 } 9264 9265 /** 9266 * Calculate the abis and roots for a bundled app. These can uniquely 9267 * be determined from the contents of the system partition, i.e whether 9268 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9269 * of this information, and instead assume that the system was built 9270 * sensibly. 9271 */ 9272 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9273 PackageSetting pkgSetting) { 9274 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9275 9276 // If "/system/lib64/apkname" exists, assume that is the per-package 9277 // native library directory to use; otherwise use "/system/lib/apkname". 9278 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9279 setBundledAppAbi(pkg, apkRoot, apkName); 9280 // pkgSetting might be null during rescan following uninstall of updates 9281 // to a bundled app, so accommodate that possibility. The settings in 9282 // that case will be established later from the parsed package. 9283 // 9284 // If the settings aren't null, sync them up with what we've just derived. 9285 // note that apkRoot isn't stored in the package settings. 9286 if (pkgSetting != null) { 9287 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9288 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9289 } 9290 } 9291 9292 /** 9293 * Deduces the ABI of a bundled app and sets the relevant fields on the 9294 * parsed pkg object. 9295 * 9296 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9297 * under which system libraries are installed. 9298 * @param apkName the name of the installed package. 9299 */ 9300 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9301 final File codeFile = new File(pkg.codePath); 9302 9303 final boolean has64BitLibs; 9304 final boolean has32BitLibs; 9305 if (isApkFile(codeFile)) { 9306 // Monolithic install 9307 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9308 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9309 } else { 9310 // Cluster install 9311 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9312 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9313 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9314 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9315 has64BitLibs = (new File(rootDir, isa)).exists(); 9316 } else { 9317 has64BitLibs = false; 9318 } 9319 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9320 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9321 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9322 has32BitLibs = (new File(rootDir, isa)).exists(); 9323 } else { 9324 has32BitLibs = false; 9325 } 9326 } 9327 9328 if (has64BitLibs && !has32BitLibs) { 9329 // The package has 64 bit libs, but not 32 bit libs. Its primary 9330 // ABI should be 64 bit. We can safely assume here that the bundled 9331 // native libraries correspond to the most preferred ABI in the list. 9332 9333 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9334 pkg.applicationInfo.secondaryCpuAbi = null; 9335 } else if (has32BitLibs && !has64BitLibs) { 9336 // The package has 32 bit libs but not 64 bit libs. Its primary 9337 // ABI should be 32 bit. 9338 9339 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9340 pkg.applicationInfo.secondaryCpuAbi = null; 9341 } else if (has32BitLibs && has64BitLibs) { 9342 // The application has both 64 and 32 bit bundled libraries. We check 9343 // here that the app declares multiArch support, and warn if it doesn't. 9344 // 9345 // We will be lenient here and record both ABIs. The primary will be the 9346 // ABI that's higher on the list, i.e, a device that's configured to prefer 9347 // 64 bit apps will see a 64 bit primary ABI, 9348 9349 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9350 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9351 } 9352 9353 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9354 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9355 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9356 } else { 9357 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9358 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9359 } 9360 } else { 9361 pkg.applicationInfo.primaryCpuAbi = null; 9362 pkg.applicationInfo.secondaryCpuAbi = null; 9363 } 9364 } 9365 9366 private void killApplication(String pkgName, int appId, String reason) { 9367 // Request the ActivityManager to kill the process(only for existing packages) 9368 // so that we do not end up in a confused state while the user is still using the older 9369 // version of the application while the new one gets installed. 9370 final long token = Binder.clearCallingIdentity(); 9371 try { 9372 IActivityManager am = ActivityManagerNative.getDefault(); 9373 if (am != null) { 9374 try { 9375 am.killApplicationWithAppId(pkgName, appId, reason); 9376 } catch (RemoteException e) { 9377 } 9378 } 9379 } finally { 9380 Binder.restoreCallingIdentity(token); 9381 } 9382 } 9383 9384 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9385 // Remove the parent package setting 9386 PackageSetting ps = (PackageSetting) pkg.mExtras; 9387 if (ps != null) { 9388 removePackageLI(ps, chatty); 9389 } 9390 // Remove the child package setting 9391 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9392 for (int i = 0; i < childCount; i++) { 9393 PackageParser.Package childPkg = pkg.childPackages.get(i); 9394 ps = (PackageSetting) childPkg.mExtras; 9395 if (ps != null) { 9396 removePackageLI(ps, chatty); 9397 } 9398 } 9399 } 9400 9401 void removePackageLI(PackageSetting ps, boolean chatty) { 9402 if (DEBUG_INSTALL) { 9403 if (chatty) 9404 Log.d(TAG, "Removing package " + ps.name); 9405 } 9406 9407 // writer 9408 synchronized (mPackages) { 9409 mPackages.remove(ps.name); 9410 final PackageParser.Package pkg = ps.pkg; 9411 if (pkg != null) { 9412 cleanPackageDataStructuresLILPw(pkg, chatty); 9413 } 9414 } 9415 } 9416 9417 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9418 if (DEBUG_INSTALL) { 9419 if (chatty) 9420 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9421 } 9422 9423 // writer 9424 synchronized (mPackages) { 9425 // Remove the parent package 9426 mPackages.remove(pkg.applicationInfo.packageName); 9427 cleanPackageDataStructuresLILPw(pkg, chatty); 9428 9429 // Remove the child packages 9430 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9431 for (int i = 0; i < childCount; i++) { 9432 PackageParser.Package childPkg = pkg.childPackages.get(i); 9433 mPackages.remove(childPkg.applicationInfo.packageName); 9434 cleanPackageDataStructuresLILPw(childPkg, chatty); 9435 } 9436 } 9437 } 9438 9439 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9440 int N = pkg.providers.size(); 9441 StringBuilder r = null; 9442 int i; 9443 for (i=0; i<N; i++) { 9444 PackageParser.Provider p = pkg.providers.get(i); 9445 mProviders.removeProvider(p); 9446 if (p.info.authority == null) { 9447 9448 /* There was another ContentProvider with this authority when 9449 * this app was installed so this authority is null, 9450 * Ignore it as we don't have to unregister the provider. 9451 */ 9452 continue; 9453 } 9454 String names[] = p.info.authority.split(";"); 9455 for (int j = 0; j < names.length; j++) { 9456 if (mProvidersByAuthority.get(names[j]) == p) { 9457 mProvidersByAuthority.remove(names[j]); 9458 if (DEBUG_REMOVE) { 9459 if (chatty) 9460 Log.d(TAG, "Unregistered content provider: " + names[j] 9461 + ", className = " + p.info.name + ", isSyncable = " 9462 + p.info.isSyncable); 9463 } 9464 } 9465 } 9466 if (DEBUG_REMOVE && chatty) { 9467 if (r == null) { 9468 r = new StringBuilder(256); 9469 } else { 9470 r.append(' '); 9471 } 9472 r.append(p.info.name); 9473 } 9474 } 9475 if (r != null) { 9476 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9477 } 9478 9479 N = pkg.services.size(); 9480 r = null; 9481 for (i=0; i<N; i++) { 9482 PackageParser.Service s = pkg.services.get(i); 9483 mServices.removeService(s); 9484 if (chatty) { 9485 if (r == null) { 9486 r = new StringBuilder(256); 9487 } else { 9488 r.append(' '); 9489 } 9490 r.append(s.info.name); 9491 } 9492 } 9493 if (r != null) { 9494 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9495 } 9496 9497 N = pkg.receivers.size(); 9498 r = null; 9499 for (i=0; i<N; i++) { 9500 PackageParser.Activity a = pkg.receivers.get(i); 9501 mReceivers.removeActivity(a, "receiver"); 9502 if (DEBUG_REMOVE && chatty) { 9503 if (r == null) { 9504 r = new StringBuilder(256); 9505 } else { 9506 r.append(' '); 9507 } 9508 r.append(a.info.name); 9509 } 9510 } 9511 if (r != null) { 9512 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9513 } 9514 9515 N = pkg.activities.size(); 9516 r = null; 9517 for (i=0; i<N; i++) { 9518 PackageParser.Activity a = pkg.activities.get(i); 9519 mActivities.removeActivity(a, "activity"); 9520 if (DEBUG_REMOVE && chatty) { 9521 if (r == null) { 9522 r = new StringBuilder(256); 9523 } else { 9524 r.append(' '); 9525 } 9526 r.append(a.info.name); 9527 } 9528 } 9529 if (r != null) { 9530 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9531 } 9532 9533 N = pkg.permissions.size(); 9534 r = null; 9535 for (i=0; i<N; i++) { 9536 PackageParser.Permission p = pkg.permissions.get(i); 9537 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9538 if (bp == null) { 9539 bp = mSettings.mPermissionTrees.get(p.info.name); 9540 } 9541 if (bp != null && bp.perm == p) { 9542 bp.perm = null; 9543 if (DEBUG_REMOVE && chatty) { 9544 if (r == null) { 9545 r = new StringBuilder(256); 9546 } else { 9547 r.append(' '); 9548 } 9549 r.append(p.info.name); 9550 } 9551 } 9552 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9553 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9554 if (appOpPkgs != null) { 9555 appOpPkgs.remove(pkg.packageName); 9556 } 9557 } 9558 } 9559 if (r != null) { 9560 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9561 } 9562 9563 N = pkg.requestedPermissions.size(); 9564 r = null; 9565 for (i=0; i<N; i++) { 9566 String perm = pkg.requestedPermissions.get(i); 9567 BasePermission bp = mSettings.mPermissions.get(perm); 9568 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9569 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9570 if (appOpPkgs != null) { 9571 appOpPkgs.remove(pkg.packageName); 9572 if (appOpPkgs.isEmpty()) { 9573 mAppOpPermissionPackages.remove(perm); 9574 } 9575 } 9576 } 9577 } 9578 if (r != null) { 9579 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9580 } 9581 9582 N = pkg.instrumentation.size(); 9583 r = null; 9584 for (i=0; i<N; i++) { 9585 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9586 mInstrumentation.remove(a.getComponentName()); 9587 if (DEBUG_REMOVE && chatty) { 9588 if (r == null) { 9589 r = new StringBuilder(256); 9590 } else { 9591 r.append(' '); 9592 } 9593 r.append(a.info.name); 9594 } 9595 } 9596 if (r != null) { 9597 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9598 } 9599 9600 r = null; 9601 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9602 // Only system apps can hold shared libraries. 9603 if (pkg.libraryNames != null) { 9604 for (i=0; i<pkg.libraryNames.size(); i++) { 9605 String name = pkg.libraryNames.get(i); 9606 SharedLibraryEntry cur = mSharedLibraries.get(name); 9607 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9608 mSharedLibraries.remove(name); 9609 if (DEBUG_REMOVE && chatty) { 9610 if (r == null) { 9611 r = new StringBuilder(256); 9612 } else { 9613 r.append(' '); 9614 } 9615 r.append(name); 9616 } 9617 } 9618 } 9619 } 9620 } 9621 if (r != null) { 9622 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9623 } 9624 } 9625 9626 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9627 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9628 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9629 return true; 9630 } 9631 } 9632 return false; 9633 } 9634 9635 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9636 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9637 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9638 9639 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9640 // Update the parent permissions 9641 updatePermissionsLPw(pkg.packageName, pkg, flags); 9642 // Update the child permissions 9643 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9644 for (int i = 0; i < childCount; i++) { 9645 PackageParser.Package childPkg = pkg.childPackages.get(i); 9646 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9647 } 9648 } 9649 9650 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9651 int flags) { 9652 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9653 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9654 } 9655 9656 private void updatePermissionsLPw(String changingPkg, 9657 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9658 // Make sure there are no dangling permission trees. 9659 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9660 while (it.hasNext()) { 9661 final BasePermission bp = it.next(); 9662 if (bp.packageSetting == null) { 9663 // We may not yet have parsed the package, so just see if 9664 // we still know about its settings. 9665 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9666 } 9667 if (bp.packageSetting == null) { 9668 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9669 + " from package " + bp.sourcePackage); 9670 it.remove(); 9671 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9672 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9673 Slog.i(TAG, "Removing old permission tree: " + bp.name 9674 + " from package " + bp.sourcePackage); 9675 flags |= UPDATE_PERMISSIONS_ALL; 9676 it.remove(); 9677 } 9678 } 9679 } 9680 9681 // Make sure all dynamic permissions have been assigned to a package, 9682 // and make sure there are no dangling permissions. 9683 it = mSettings.mPermissions.values().iterator(); 9684 while (it.hasNext()) { 9685 final BasePermission bp = it.next(); 9686 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9687 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9688 + bp.name + " pkg=" + bp.sourcePackage 9689 + " info=" + bp.pendingInfo); 9690 if (bp.packageSetting == null && bp.pendingInfo != null) { 9691 final BasePermission tree = findPermissionTreeLP(bp.name); 9692 if (tree != null && tree.perm != null) { 9693 bp.packageSetting = tree.packageSetting; 9694 bp.perm = new PackageParser.Permission(tree.perm.owner, 9695 new PermissionInfo(bp.pendingInfo)); 9696 bp.perm.info.packageName = tree.perm.info.packageName; 9697 bp.perm.info.name = bp.name; 9698 bp.uid = tree.uid; 9699 } 9700 } 9701 } 9702 if (bp.packageSetting == null) { 9703 // We may not yet have parsed the package, so just see if 9704 // we still know about its settings. 9705 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9706 } 9707 if (bp.packageSetting == null) { 9708 Slog.w(TAG, "Removing dangling permission: " + bp.name 9709 + " from package " + bp.sourcePackage); 9710 it.remove(); 9711 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9712 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9713 Slog.i(TAG, "Removing old permission: " + bp.name 9714 + " from package " + bp.sourcePackage); 9715 flags |= UPDATE_PERMISSIONS_ALL; 9716 it.remove(); 9717 } 9718 } 9719 } 9720 9721 // Now update the permissions for all packages, in particular 9722 // replace the granted permissions of the system packages. 9723 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9724 for (PackageParser.Package pkg : mPackages.values()) { 9725 if (pkg != pkgInfo) { 9726 // Only replace for packages on requested volume 9727 final String volumeUuid = getVolumeUuidForPackage(pkg); 9728 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9729 && Objects.equals(replaceVolumeUuid, volumeUuid); 9730 grantPermissionsLPw(pkg, replace, changingPkg); 9731 } 9732 } 9733 } 9734 9735 if (pkgInfo != null) { 9736 // Only replace for packages on requested volume 9737 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9738 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9739 && Objects.equals(replaceVolumeUuid, volumeUuid); 9740 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9741 } 9742 } 9743 9744 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9745 String packageOfInterest) { 9746 // IMPORTANT: There are two types of permissions: install and runtime. 9747 // Install time permissions are granted when the app is installed to 9748 // all device users and users added in the future. Runtime permissions 9749 // are granted at runtime explicitly to specific users. Normal and signature 9750 // protected permissions are install time permissions. Dangerous permissions 9751 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9752 // otherwise they are runtime permissions. This function does not manage 9753 // runtime permissions except for the case an app targeting Lollipop MR1 9754 // being upgraded to target a newer SDK, in which case dangerous permissions 9755 // are transformed from install time to runtime ones. 9756 9757 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9758 if (ps == null) { 9759 return; 9760 } 9761 9762 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9763 9764 PermissionsState permissionsState = ps.getPermissionsState(); 9765 PermissionsState origPermissions = permissionsState; 9766 9767 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9768 9769 boolean runtimePermissionsRevoked = false; 9770 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9771 9772 boolean changedInstallPermission = false; 9773 9774 if (replace) { 9775 ps.installPermissionsFixed = false; 9776 if (!ps.isSharedUser()) { 9777 origPermissions = new PermissionsState(permissionsState); 9778 permissionsState.reset(); 9779 } else { 9780 // We need to know only about runtime permission changes since the 9781 // calling code always writes the install permissions state but 9782 // the runtime ones are written only if changed. The only cases of 9783 // changed runtime permissions here are promotion of an install to 9784 // runtime and revocation of a runtime from a shared user. 9785 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9786 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9787 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9788 runtimePermissionsRevoked = true; 9789 } 9790 } 9791 } 9792 9793 permissionsState.setGlobalGids(mGlobalGids); 9794 9795 final int N = pkg.requestedPermissions.size(); 9796 for (int i=0; i<N; i++) { 9797 final String name = pkg.requestedPermissions.get(i); 9798 final BasePermission bp = mSettings.mPermissions.get(name); 9799 9800 if (DEBUG_INSTALL) { 9801 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9802 } 9803 9804 if (bp == null || bp.packageSetting == null) { 9805 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9806 Slog.w(TAG, "Unknown permission " + name 9807 + " in package " + pkg.packageName); 9808 } 9809 continue; 9810 } 9811 9812 final String perm = bp.name; 9813 boolean allowedSig = false; 9814 int grant = GRANT_DENIED; 9815 9816 // Keep track of app op permissions. 9817 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9818 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9819 if (pkgs == null) { 9820 pkgs = new ArraySet<>(); 9821 mAppOpPermissionPackages.put(bp.name, pkgs); 9822 } 9823 pkgs.add(pkg.packageName); 9824 } 9825 9826 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9827 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9828 >= Build.VERSION_CODES.M; 9829 switch (level) { 9830 case PermissionInfo.PROTECTION_NORMAL: { 9831 // For all apps normal permissions are install time ones. 9832 grant = GRANT_INSTALL; 9833 } break; 9834 9835 case PermissionInfo.PROTECTION_DANGEROUS: { 9836 // If a permission review is required for legacy apps we represent 9837 // their permissions as always granted runtime ones since we need 9838 // to keep the review required permission flag per user while an 9839 // install permission's state is shared across all users. 9840 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9841 // For legacy apps dangerous permissions are install time ones. 9842 grant = GRANT_INSTALL; 9843 } else if (origPermissions.hasInstallPermission(bp.name)) { 9844 // For legacy apps that became modern, install becomes runtime. 9845 grant = GRANT_UPGRADE; 9846 } else if (mPromoteSystemApps 9847 && isSystemApp(ps) 9848 && mExistingSystemPackages.contains(ps.name)) { 9849 // For legacy system apps, install becomes runtime. 9850 // We cannot check hasInstallPermission() for system apps since those 9851 // permissions were granted implicitly and not persisted pre-M. 9852 grant = GRANT_UPGRADE; 9853 } else { 9854 // For modern apps keep runtime permissions unchanged. 9855 grant = GRANT_RUNTIME; 9856 } 9857 } break; 9858 9859 case PermissionInfo.PROTECTION_SIGNATURE: { 9860 // For all apps signature permissions are install time ones. 9861 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9862 if (allowedSig) { 9863 grant = GRANT_INSTALL; 9864 } 9865 } break; 9866 } 9867 9868 if (DEBUG_INSTALL) { 9869 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9870 } 9871 9872 if (grant != GRANT_DENIED) { 9873 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9874 // If this is an existing, non-system package, then 9875 // we can't add any new permissions to it. 9876 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9877 // Except... if this is a permission that was added 9878 // to the platform (note: need to only do this when 9879 // updating the platform). 9880 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9881 grant = GRANT_DENIED; 9882 } 9883 } 9884 } 9885 9886 switch (grant) { 9887 case GRANT_INSTALL: { 9888 // Revoke this as runtime permission to handle the case of 9889 // a runtime permission being downgraded to an install one. 9890 // Also in permission review mode we keep dangerous permissions 9891 // for legacy apps 9892 for (int userId : UserManagerService.getInstance().getUserIds()) { 9893 if (origPermissions.getRuntimePermissionState( 9894 bp.name, userId) != null) { 9895 // Revoke the runtime permission and clear the flags. 9896 origPermissions.revokeRuntimePermission(bp, userId); 9897 origPermissions.updatePermissionFlags(bp, userId, 9898 PackageManager.MASK_PERMISSION_FLAGS, 0); 9899 // If we revoked a permission permission, we have to write. 9900 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9901 changedRuntimePermissionUserIds, userId); 9902 } 9903 } 9904 // Grant an install permission. 9905 if (permissionsState.grantInstallPermission(bp) != 9906 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9907 changedInstallPermission = true; 9908 } 9909 } break; 9910 9911 case GRANT_RUNTIME: { 9912 // Grant previously granted runtime permissions. 9913 for (int userId : UserManagerService.getInstance().getUserIds()) { 9914 PermissionState permissionState = origPermissions 9915 .getRuntimePermissionState(bp.name, userId); 9916 int flags = permissionState != null 9917 ? permissionState.getFlags() : 0; 9918 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9919 if (permissionsState.grantRuntimePermission(bp, userId) == 9920 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9921 // If we cannot put the permission as it was, we have to write. 9922 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9923 changedRuntimePermissionUserIds, userId); 9924 } 9925 // If the app supports runtime permissions no need for a review. 9926 if (Build.PERMISSIONS_REVIEW_REQUIRED 9927 && appSupportsRuntimePermissions 9928 && (flags & PackageManager 9929 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9930 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9931 // Since we changed the flags, we have to write. 9932 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9933 changedRuntimePermissionUserIds, userId); 9934 } 9935 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9936 && !appSupportsRuntimePermissions) { 9937 // For legacy apps that need a permission review, every new 9938 // runtime permission is granted but it is pending a review. 9939 // We also need to review only platform defined runtime 9940 // permissions as these are the only ones the platform knows 9941 // how to disable the API to simulate revocation as legacy 9942 // apps don't expect to run with revoked permissions. 9943 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9944 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9945 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9946 // We changed the flags, hence have to write. 9947 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9948 changedRuntimePermissionUserIds, userId); 9949 } 9950 } 9951 if (permissionsState.grantRuntimePermission(bp, userId) 9952 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9953 // We changed the permission, hence have to write. 9954 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9955 changedRuntimePermissionUserIds, userId); 9956 } 9957 } 9958 // Propagate the permission flags. 9959 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9960 } 9961 } break; 9962 9963 case GRANT_UPGRADE: { 9964 // Grant runtime permissions for a previously held install permission. 9965 PermissionState permissionState = origPermissions 9966 .getInstallPermissionState(bp.name); 9967 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9968 9969 if (origPermissions.revokeInstallPermission(bp) 9970 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9971 // We will be transferring the permission flags, so clear them. 9972 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9973 PackageManager.MASK_PERMISSION_FLAGS, 0); 9974 changedInstallPermission = true; 9975 } 9976 9977 // If the permission is not to be promoted to runtime we ignore it and 9978 // also its other flags as they are not applicable to install permissions. 9979 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9980 for (int userId : currentUserIds) { 9981 if (permissionsState.grantRuntimePermission(bp, userId) != 9982 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9983 // Transfer the permission flags. 9984 permissionsState.updatePermissionFlags(bp, userId, 9985 flags, flags); 9986 // If we granted the permission, we have to write. 9987 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9988 changedRuntimePermissionUserIds, userId); 9989 } 9990 } 9991 } 9992 } break; 9993 9994 default: { 9995 if (packageOfInterest == null 9996 || packageOfInterest.equals(pkg.packageName)) { 9997 Slog.w(TAG, "Not granting permission " + perm 9998 + " to package " + pkg.packageName 9999 + " because it was previously installed without"); 10000 } 10001 } break; 10002 } 10003 } else { 10004 if (permissionsState.revokeInstallPermission(bp) != 10005 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10006 // Also drop the permission flags. 10007 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10008 PackageManager.MASK_PERMISSION_FLAGS, 0); 10009 changedInstallPermission = true; 10010 Slog.i(TAG, "Un-granting permission " + perm 10011 + " from package " + pkg.packageName 10012 + " (protectionLevel=" + bp.protectionLevel 10013 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10014 + ")"); 10015 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10016 // Don't print warning for app op permissions, since it is fine for them 10017 // not to be granted, there is a UI for the user to decide. 10018 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10019 Slog.w(TAG, "Not granting permission " + perm 10020 + " to package " + pkg.packageName 10021 + " (protectionLevel=" + bp.protectionLevel 10022 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10023 + ")"); 10024 } 10025 } 10026 } 10027 } 10028 10029 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10030 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10031 // This is the first that we have heard about this package, so the 10032 // permissions we have now selected are fixed until explicitly 10033 // changed. 10034 ps.installPermissionsFixed = true; 10035 } 10036 10037 // Persist the runtime permissions state for users with changes. If permissions 10038 // were revoked because no app in the shared user declares them we have to 10039 // write synchronously to avoid losing runtime permissions state. 10040 for (int userId : changedRuntimePermissionUserIds) { 10041 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10042 } 10043 10044 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10045 } 10046 10047 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10048 boolean allowed = false; 10049 final int NP = PackageParser.NEW_PERMISSIONS.length; 10050 for (int ip=0; ip<NP; ip++) { 10051 final PackageParser.NewPermissionInfo npi 10052 = PackageParser.NEW_PERMISSIONS[ip]; 10053 if (npi.name.equals(perm) 10054 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10055 allowed = true; 10056 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10057 + pkg.packageName); 10058 break; 10059 } 10060 } 10061 return allowed; 10062 } 10063 10064 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10065 BasePermission bp, PermissionsState origPermissions) { 10066 boolean allowed; 10067 allowed = (compareSignatures( 10068 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10069 == PackageManager.SIGNATURE_MATCH) 10070 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10071 == PackageManager.SIGNATURE_MATCH); 10072 if (!allowed && (bp.protectionLevel 10073 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10074 if (isSystemApp(pkg)) { 10075 // For updated system applications, a system permission 10076 // is granted only if it had been defined by the original application. 10077 if (pkg.isUpdatedSystemApp()) { 10078 final PackageSetting sysPs = mSettings 10079 .getDisabledSystemPkgLPr(pkg.packageName); 10080 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10081 // If the original was granted this permission, we take 10082 // that grant decision as read and propagate it to the 10083 // update. 10084 if (sysPs.isPrivileged()) { 10085 allowed = true; 10086 } 10087 } else { 10088 // The system apk may have been updated with an older 10089 // version of the one on the data partition, but which 10090 // granted a new system permission that it didn't have 10091 // before. In this case we do want to allow the app to 10092 // now get the new permission if the ancestral apk is 10093 // privileged to get it. 10094 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10095 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10096 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10097 allowed = true; 10098 break; 10099 } 10100 } 10101 } 10102 // Also if a privileged parent package on the system image or any of 10103 // its children requested a privileged permission, the updated child 10104 // packages can also get the permission. 10105 if (pkg.parentPackage != null) { 10106 final PackageSetting disabledSysParentPs = mSettings 10107 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10108 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10109 && disabledSysParentPs.isPrivileged()) { 10110 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10111 allowed = true; 10112 } else if (disabledSysParentPs.pkg.childPackages != null) { 10113 final int count = disabledSysParentPs.pkg.childPackages.size(); 10114 for (int i = 0; i < count; i++) { 10115 PackageParser.Package disabledSysChildPkg = 10116 disabledSysParentPs.pkg.childPackages.get(i); 10117 if (isPackageRequestingPermission(disabledSysChildPkg, 10118 perm)) { 10119 allowed = true; 10120 break; 10121 } 10122 } 10123 } 10124 } 10125 } 10126 } 10127 } else { 10128 allowed = isPrivilegedApp(pkg); 10129 } 10130 } 10131 } 10132 if (!allowed) { 10133 if (!allowed && (bp.protectionLevel 10134 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10135 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10136 // If this was a previously normal/dangerous permission that got moved 10137 // to a system permission as part of the runtime permission redesign, then 10138 // we still want to blindly grant it to old apps. 10139 allowed = true; 10140 } 10141 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10142 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10143 // If this permission is to be granted to the system installer and 10144 // this app is an installer, then it gets the permission. 10145 allowed = true; 10146 } 10147 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10148 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10149 // If this permission is to be granted to the system verifier and 10150 // this app is a verifier, then it gets the permission. 10151 allowed = true; 10152 } 10153 if (!allowed && (bp.protectionLevel 10154 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10155 && isSystemApp(pkg)) { 10156 // Any pre-installed system app is allowed to get this permission. 10157 allowed = true; 10158 } 10159 if (!allowed && (bp.protectionLevel 10160 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10161 // For development permissions, a development permission 10162 // is granted only if it was already granted. 10163 allowed = origPermissions.hasInstallPermission(perm); 10164 } 10165 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10166 && pkg.packageName.equals(mSetupWizardPackage)) { 10167 // If this permission is to be granted to the system setup wizard and 10168 // this app is a setup wizard, then it gets the permission. 10169 allowed = true; 10170 } 10171 } 10172 return allowed; 10173 } 10174 10175 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10176 final int permCount = pkg.requestedPermissions.size(); 10177 for (int j = 0; j < permCount; j++) { 10178 String requestedPermission = pkg.requestedPermissions.get(j); 10179 if (permission.equals(requestedPermission)) { 10180 return true; 10181 } 10182 } 10183 return false; 10184 } 10185 10186 final class ActivityIntentResolver 10187 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10188 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10189 boolean defaultOnly, int userId) { 10190 if (!sUserManager.exists(userId)) return null; 10191 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10192 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10193 } 10194 10195 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10196 int userId) { 10197 if (!sUserManager.exists(userId)) return null; 10198 mFlags = flags; 10199 return super.queryIntent(intent, resolvedType, 10200 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10201 } 10202 10203 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10204 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10205 if (!sUserManager.exists(userId)) return null; 10206 if (packageActivities == null) { 10207 return null; 10208 } 10209 mFlags = flags; 10210 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10211 final int N = packageActivities.size(); 10212 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10213 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10214 10215 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10216 for (int i = 0; i < N; ++i) { 10217 intentFilters = packageActivities.get(i).intents; 10218 if (intentFilters != null && intentFilters.size() > 0) { 10219 PackageParser.ActivityIntentInfo[] array = 10220 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10221 intentFilters.toArray(array); 10222 listCut.add(array); 10223 } 10224 } 10225 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10226 } 10227 10228 /** 10229 * Finds a privileged activity that matches the specified activity names. 10230 */ 10231 private PackageParser.Activity findMatchingActivity( 10232 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10233 for (PackageParser.Activity sysActivity : activityList) { 10234 if (sysActivity.info.name.equals(activityInfo.name)) { 10235 return sysActivity; 10236 } 10237 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10238 return sysActivity; 10239 } 10240 if (sysActivity.info.targetActivity != null) { 10241 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10242 return sysActivity; 10243 } 10244 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10245 return sysActivity; 10246 } 10247 } 10248 } 10249 return null; 10250 } 10251 10252 public class IterGenerator<E> { 10253 public Iterator<E> generate(ActivityIntentInfo info) { 10254 return null; 10255 } 10256 } 10257 10258 public class ActionIterGenerator extends IterGenerator<String> { 10259 @Override 10260 public Iterator<String> generate(ActivityIntentInfo info) { 10261 return info.actionsIterator(); 10262 } 10263 } 10264 10265 public class CategoriesIterGenerator extends IterGenerator<String> { 10266 @Override 10267 public Iterator<String> generate(ActivityIntentInfo info) { 10268 return info.categoriesIterator(); 10269 } 10270 } 10271 10272 public class SchemesIterGenerator extends IterGenerator<String> { 10273 @Override 10274 public Iterator<String> generate(ActivityIntentInfo info) { 10275 return info.schemesIterator(); 10276 } 10277 } 10278 10279 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10280 @Override 10281 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10282 return info.authoritiesIterator(); 10283 } 10284 } 10285 10286 /** 10287 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10288 * MODIFIED. Do not pass in a list that should not be changed. 10289 */ 10290 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10291 IterGenerator<T> generator, Iterator<T> searchIterator) { 10292 // loop through the set of actions; every one must be found in the intent filter 10293 while (searchIterator.hasNext()) { 10294 // we must have at least one filter in the list to consider a match 10295 if (intentList.size() == 0) { 10296 break; 10297 } 10298 10299 final T searchAction = searchIterator.next(); 10300 10301 // loop through the set of intent filters 10302 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10303 while (intentIter.hasNext()) { 10304 final ActivityIntentInfo intentInfo = intentIter.next(); 10305 boolean selectionFound = false; 10306 10307 // loop through the intent filter's selection criteria; at least one 10308 // of them must match the searched criteria 10309 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10310 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10311 final T intentSelection = intentSelectionIter.next(); 10312 if (intentSelection != null && intentSelection.equals(searchAction)) { 10313 selectionFound = true; 10314 break; 10315 } 10316 } 10317 10318 // the selection criteria wasn't found in this filter's set; this filter 10319 // is not a potential match 10320 if (!selectionFound) { 10321 intentIter.remove(); 10322 } 10323 } 10324 } 10325 } 10326 10327 private boolean isProtectedAction(ActivityIntentInfo filter) { 10328 final Iterator<String> actionsIter = filter.actionsIterator(); 10329 while (actionsIter != null && actionsIter.hasNext()) { 10330 final String filterAction = actionsIter.next(); 10331 if (PROTECTED_ACTIONS.contains(filterAction)) { 10332 return true; 10333 } 10334 } 10335 return false; 10336 } 10337 10338 /** 10339 * Adjusts the priority of the given intent filter according to policy. 10340 * <p> 10341 * <ul> 10342 * <li>The priority for non privileged applications is capped to '0'</li> 10343 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10344 * <li>The priority for unbundled updates to privileged applications is capped to the 10345 * priority defined on the system partition</li> 10346 * </ul> 10347 * <p> 10348 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10349 * allowed to obtain any priority on any action. 10350 */ 10351 private void adjustPriority( 10352 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10353 // nothing to do; priority is fine as-is 10354 if (intent.getPriority() <= 0) { 10355 return; 10356 } 10357 10358 final ActivityInfo activityInfo = intent.activity.info; 10359 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10360 10361 final boolean privilegedApp = 10362 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10363 if (!privilegedApp) { 10364 // non-privileged applications can never define a priority >0 10365 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10366 + " package: " + applicationInfo.packageName 10367 + " activity: " + intent.activity.className 10368 + " origPrio: " + intent.getPriority()); 10369 intent.setPriority(0); 10370 return; 10371 } 10372 10373 if (systemActivities == null) { 10374 // the system package is not disabled; we're parsing the system partition 10375 if (isProtectedAction(intent)) { 10376 if (mDeferProtectedFilters) { 10377 // We can't deal with these just yet. No component should ever obtain a 10378 // >0 priority for a protected actions, with ONE exception -- the setup 10379 // wizard. The setup wizard, however, cannot be known until we're able to 10380 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10381 // until all intent filters have been processed. Chicken, meet egg. 10382 // Let the filter temporarily have a high priority and rectify the 10383 // priorities after all system packages have been scanned. 10384 mProtectedFilters.add(intent); 10385 if (DEBUG_FILTERS) { 10386 Slog.i(TAG, "Protected action; save for later;" 10387 + " package: " + applicationInfo.packageName 10388 + " activity: " + intent.activity.className 10389 + " origPrio: " + intent.getPriority()); 10390 } 10391 return; 10392 } else { 10393 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10394 Slog.i(TAG, "No setup wizard;" 10395 + " All protected intents capped to priority 0"); 10396 } 10397 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10398 if (DEBUG_FILTERS) { 10399 Slog.i(TAG, "Found setup wizard;" 10400 + " allow priority " + intent.getPriority() + ";" 10401 + " package: " + intent.activity.info.packageName 10402 + " activity: " + intent.activity.className 10403 + " priority: " + intent.getPriority()); 10404 } 10405 // setup wizard gets whatever it wants 10406 return; 10407 } 10408 Slog.w(TAG, "Protected action; cap priority to 0;" 10409 + " package: " + intent.activity.info.packageName 10410 + " activity: " + intent.activity.className 10411 + " origPrio: " + intent.getPriority()); 10412 intent.setPriority(0); 10413 return; 10414 } 10415 } 10416 // privileged apps on the system image get whatever priority they request 10417 return; 10418 } 10419 10420 // privileged app unbundled update ... try to find the same activity 10421 final PackageParser.Activity foundActivity = 10422 findMatchingActivity(systemActivities, activityInfo); 10423 if (foundActivity == null) { 10424 // this is a new activity; it cannot obtain >0 priority 10425 if (DEBUG_FILTERS) { 10426 Slog.i(TAG, "New activity; cap priority to 0;" 10427 + " package: " + applicationInfo.packageName 10428 + " activity: " + intent.activity.className 10429 + " origPrio: " + intent.getPriority()); 10430 } 10431 intent.setPriority(0); 10432 return; 10433 } 10434 10435 // found activity, now check for filter equivalence 10436 10437 // a shallow copy is enough; we modify the list, not its contents 10438 final List<ActivityIntentInfo> intentListCopy = 10439 new ArrayList<>(foundActivity.intents); 10440 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10441 10442 // find matching action subsets 10443 final Iterator<String> actionsIterator = intent.actionsIterator(); 10444 if (actionsIterator != null) { 10445 getIntentListSubset( 10446 intentListCopy, new ActionIterGenerator(), actionsIterator); 10447 if (intentListCopy.size() == 0) { 10448 // no more intents to match; we're not equivalent 10449 if (DEBUG_FILTERS) { 10450 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10451 + " package: " + applicationInfo.packageName 10452 + " activity: " + intent.activity.className 10453 + " origPrio: " + intent.getPriority()); 10454 } 10455 intent.setPriority(0); 10456 return; 10457 } 10458 } 10459 10460 // find matching category subsets 10461 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10462 if (categoriesIterator != null) { 10463 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10464 categoriesIterator); 10465 if (intentListCopy.size() == 0) { 10466 // no more intents to match; we're not equivalent 10467 if (DEBUG_FILTERS) { 10468 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10469 + " package: " + applicationInfo.packageName 10470 + " activity: " + intent.activity.className 10471 + " origPrio: " + intent.getPriority()); 10472 } 10473 intent.setPriority(0); 10474 return; 10475 } 10476 } 10477 10478 // find matching schemes subsets 10479 final Iterator<String> schemesIterator = intent.schemesIterator(); 10480 if (schemesIterator != null) { 10481 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10482 schemesIterator); 10483 if (intentListCopy.size() == 0) { 10484 // no more intents to match; we're not equivalent 10485 if (DEBUG_FILTERS) { 10486 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10487 + " package: " + applicationInfo.packageName 10488 + " activity: " + intent.activity.className 10489 + " origPrio: " + intent.getPriority()); 10490 } 10491 intent.setPriority(0); 10492 return; 10493 } 10494 } 10495 10496 // find matching authorities subsets 10497 final Iterator<IntentFilter.AuthorityEntry> 10498 authoritiesIterator = intent.authoritiesIterator(); 10499 if (authoritiesIterator != null) { 10500 getIntentListSubset(intentListCopy, 10501 new AuthoritiesIterGenerator(), 10502 authoritiesIterator); 10503 if (intentListCopy.size() == 0) { 10504 // no more intents to match; we're not equivalent 10505 if (DEBUG_FILTERS) { 10506 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10507 + " package: " + applicationInfo.packageName 10508 + " activity: " + intent.activity.className 10509 + " origPrio: " + intent.getPriority()); 10510 } 10511 intent.setPriority(0); 10512 return; 10513 } 10514 } 10515 10516 // we found matching filter(s); app gets the max priority of all intents 10517 int cappedPriority = 0; 10518 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10519 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10520 } 10521 if (intent.getPriority() > cappedPriority) { 10522 if (DEBUG_FILTERS) { 10523 Slog.i(TAG, "Found matching filter(s);" 10524 + " cap priority to " + cappedPriority + ";" 10525 + " package: " + applicationInfo.packageName 10526 + " activity: " + intent.activity.className 10527 + " origPrio: " + intent.getPriority()); 10528 } 10529 intent.setPriority(cappedPriority); 10530 return; 10531 } 10532 // all this for nothing; the requested priority was <= what was on the system 10533 } 10534 10535 public final void addActivity(PackageParser.Activity a, String type) { 10536 mActivities.put(a.getComponentName(), a); 10537 if (DEBUG_SHOW_INFO) 10538 Log.v( 10539 TAG, " " + type + " " + 10540 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10541 if (DEBUG_SHOW_INFO) 10542 Log.v(TAG, " Class=" + a.info.name); 10543 final int NI = a.intents.size(); 10544 for (int j=0; j<NI; j++) { 10545 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10546 if ("activity".equals(type)) { 10547 final PackageSetting ps = 10548 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10549 final List<PackageParser.Activity> systemActivities = 10550 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10551 adjustPriority(systemActivities, intent); 10552 } 10553 if (DEBUG_SHOW_INFO) { 10554 Log.v(TAG, " IntentFilter:"); 10555 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10556 } 10557 if (!intent.debugCheck()) { 10558 Log.w(TAG, "==> For Activity " + a.info.name); 10559 } 10560 addFilter(intent); 10561 } 10562 } 10563 10564 public final void removeActivity(PackageParser.Activity a, String type) { 10565 mActivities.remove(a.getComponentName()); 10566 if (DEBUG_SHOW_INFO) { 10567 Log.v(TAG, " " + type + " " 10568 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10569 : a.info.name) + ":"); 10570 Log.v(TAG, " Class=" + a.info.name); 10571 } 10572 final int NI = a.intents.size(); 10573 for (int j=0; j<NI; j++) { 10574 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10575 if (DEBUG_SHOW_INFO) { 10576 Log.v(TAG, " IntentFilter:"); 10577 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10578 } 10579 removeFilter(intent); 10580 } 10581 } 10582 10583 @Override 10584 protected boolean allowFilterResult( 10585 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10586 ActivityInfo filterAi = filter.activity.info; 10587 for (int i=dest.size()-1; i>=0; i--) { 10588 ActivityInfo destAi = dest.get(i).activityInfo; 10589 if (destAi.name == filterAi.name 10590 && destAi.packageName == filterAi.packageName) { 10591 return false; 10592 } 10593 } 10594 return true; 10595 } 10596 10597 @Override 10598 protected ActivityIntentInfo[] newArray(int size) { 10599 return new ActivityIntentInfo[size]; 10600 } 10601 10602 @Override 10603 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10604 if (!sUserManager.exists(userId)) return true; 10605 PackageParser.Package p = filter.activity.owner; 10606 if (p != null) { 10607 PackageSetting ps = (PackageSetting)p.mExtras; 10608 if (ps != null) { 10609 // System apps are never considered stopped for purposes of 10610 // filtering, because there may be no way for the user to 10611 // actually re-launch them. 10612 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10613 && ps.getStopped(userId); 10614 } 10615 } 10616 return false; 10617 } 10618 10619 @Override 10620 protected boolean isPackageForFilter(String packageName, 10621 PackageParser.ActivityIntentInfo info) { 10622 return packageName.equals(info.activity.owner.packageName); 10623 } 10624 10625 @Override 10626 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10627 int match, int userId) { 10628 if (!sUserManager.exists(userId)) return null; 10629 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10630 return null; 10631 } 10632 final PackageParser.Activity activity = info.activity; 10633 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10634 if (ps == null) { 10635 return null; 10636 } 10637 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10638 ps.readUserState(userId), userId); 10639 if (ai == null) { 10640 return null; 10641 } 10642 final ResolveInfo res = new ResolveInfo(); 10643 res.activityInfo = ai; 10644 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10645 res.filter = info; 10646 } 10647 if (info != null) { 10648 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10649 } 10650 res.priority = info.getPriority(); 10651 res.preferredOrder = activity.owner.mPreferredOrder; 10652 //System.out.println("Result: " + res.activityInfo.className + 10653 // " = " + res.priority); 10654 res.match = match; 10655 res.isDefault = info.hasDefault; 10656 res.labelRes = info.labelRes; 10657 res.nonLocalizedLabel = info.nonLocalizedLabel; 10658 if (userNeedsBadging(userId)) { 10659 res.noResourceId = true; 10660 } else { 10661 res.icon = info.icon; 10662 } 10663 res.iconResourceId = info.icon; 10664 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10665 return res; 10666 } 10667 10668 @Override 10669 protected void sortResults(List<ResolveInfo> results) { 10670 Collections.sort(results, mResolvePrioritySorter); 10671 } 10672 10673 @Override 10674 protected void dumpFilter(PrintWriter out, String prefix, 10675 PackageParser.ActivityIntentInfo filter) { 10676 out.print(prefix); out.print( 10677 Integer.toHexString(System.identityHashCode(filter.activity))); 10678 out.print(' '); 10679 filter.activity.printComponentShortName(out); 10680 out.print(" filter "); 10681 out.println(Integer.toHexString(System.identityHashCode(filter))); 10682 } 10683 10684 @Override 10685 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10686 return filter.activity; 10687 } 10688 10689 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10690 PackageParser.Activity activity = (PackageParser.Activity)label; 10691 out.print(prefix); out.print( 10692 Integer.toHexString(System.identityHashCode(activity))); 10693 out.print(' '); 10694 activity.printComponentShortName(out); 10695 if (count > 1) { 10696 out.print(" ("); out.print(count); out.print(" filters)"); 10697 } 10698 out.println(); 10699 } 10700 10701 // Keys are String (activity class name), values are Activity. 10702 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10703 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10704 private int mFlags; 10705 } 10706 10707 private final class ServiceIntentResolver 10708 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10709 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10710 boolean defaultOnly, int userId) { 10711 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10712 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10713 } 10714 10715 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10716 int userId) { 10717 if (!sUserManager.exists(userId)) return null; 10718 mFlags = flags; 10719 return super.queryIntent(intent, resolvedType, 10720 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10721 } 10722 10723 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10724 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10725 if (!sUserManager.exists(userId)) return null; 10726 if (packageServices == null) { 10727 return null; 10728 } 10729 mFlags = flags; 10730 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10731 final int N = packageServices.size(); 10732 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10733 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10734 10735 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10736 for (int i = 0; i < N; ++i) { 10737 intentFilters = packageServices.get(i).intents; 10738 if (intentFilters != null && intentFilters.size() > 0) { 10739 PackageParser.ServiceIntentInfo[] array = 10740 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10741 intentFilters.toArray(array); 10742 listCut.add(array); 10743 } 10744 } 10745 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10746 } 10747 10748 public final void addService(PackageParser.Service s) { 10749 mServices.put(s.getComponentName(), s); 10750 if (DEBUG_SHOW_INFO) { 10751 Log.v(TAG, " " 10752 + (s.info.nonLocalizedLabel != null 10753 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10754 Log.v(TAG, " Class=" + s.info.name); 10755 } 10756 final int NI = s.intents.size(); 10757 int j; 10758 for (j=0; j<NI; j++) { 10759 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10760 if (DEBUG_SHOW_INFO) { 10761 Log.v(TAG, " IntentFilter:"); 10762 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10763 } 10764 if (!intent.debugCheck()) { 10765 Log.w(TAG, "==> For Service " + s.info.name); 10766 } 10767 addFilter(intent); 10768 } 10769 } 10770 10771 public final void removeService(PackageParser.Service s) { 10772 mServices.remove(s.getComponentName()); 10773 if (DEBUG_SHOW_INFO) { 10774 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10775 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10776 Log.v(TAG, " Class=" + s.info.name); 10777 } 10778 final int NI = s.intents.size(); 10779 int j; 10780 for (j=0; j<NI; j++) { 10781 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10782 if (DEBUG_SHOW_INFO) { 10783 Log.v(TAG, " IntentFilter:"); 10784 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10785 } 10786 removeFilter(intent); 10787 } 10788 } 10789 10790 @Override 10791 protected boolean allowFilterResult( 10792 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10793 ServiceInfo filterSi = filter.service.info; 10794 for (int i=dest.size()-1; i>=0; i--) { 10795 ServiceInfo destAi = dest.get(i).serviceInfo; 10796 if (destAi.name == filterSi.name 10797 && destAi.packageName == filterSi.packageName) { 10798 return false; 10799 } 10800 } 10801 return true; 10802 } 10803 10804 @Override 10805 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10806 return new PackageParser.ServiceIntentInfo[size]; 10807 } 10808 10809 @Override 10810 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10811 if (!sUserManager.exists(userId)) return true; 10812 PackageParser.Package p = filter.service.owner; 10813 if (p != null) { 10814 PackageSetting ps = (PackageSetting)p.mExtras; 10815 if (ps != null) { 10816 // System apps are never considered stopped for purposes of 10817 // filtering, because there may be no way for the user to 10818 // actually re-launch them. 10819 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10820 && ps.getStopped(userId); 10821 } 10822 } 10823 return false; 10824 } 10825 10826 @Override 10827 protected boolean isPackageForFilter(String packageName, 10828 PackageParser.ServiceIntentInfo info) { 10829 return packageName.equals(info.service.owner.packageName); 10830 } 10831 10832 @Override 10833 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10834 int match, int userId) { 10835 if (!sUserManager.exists(userId)) return null; 10836 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10837 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10838 return null; 10839 } 10840 final PackageParser.Service service = info.service; 10841 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10842 if (ps == null) { 10843 return null; 10844 } 10845 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10846 ps.readUserState(userId), userId); 10847 if (si == null) { 10848 return null; 10849 } 10850 final ResolveInfo res = new ResolveInfo(); 10851 res.serviceInfo = si; 10852 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10853 res.filter = filter; 10854 } 10855 res.priority = info.getPriority(); 10856 res.preferredOrder = service.owner.mPreferredOrder; 10857 res.match = match; 10858 res.isDefault = info.hasDefault; 10859 res.labelRes = info.labelRes; 10860 res.nonLocalizedLabel = info.nonLocalizedLabel; 10861 res.icon = info.icon; 10862 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10863 return res; 10864 } 10865 10866 @Override 10867 protected void sortResults(List<ResolveInfo> results) { 10868 Collections.sort(results, mResolvePrioritySorter); 10869 } 10870 10871 @Override 10872 protected void dumpFilter(PrintWriter out, String prefix, 10873 PackageParser.ServiceIntentInfo filter) { 10874 out.print(prefix); out.print( 10875 Integer.toHexString(System.identityHashCode(filter.service))); 10876 out.print(' '); 10877 filter.service.printComponentShortName(out); 10878 out.print(" filter "); 10879 out.println(Integer.toHexString(System.identityHashCode(filter))); 10880 } 10881 10882 @Override 10883 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10884 return filter.service; 10885 } 10886 10887 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10888 PackageParser.Service service = (PackageParser.Service)label; 10889 out.print(prefix); out.print( 10890 Integer.toHexString(System.identityHashCode(service))); 10891 out.print(' '); 10892 service.printComponentShortName(out); 10893 if (count > 1) { 10894 out.print(" ("); out.print(count); out.print(" filters)"); 10895 } 10896 out.println(); 10897 } 10898 10899// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10900// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10901// final List<ResolveInfo> retList = Lists.newArrayList(); 10902// while (i.hasNext()) { 10903// final ResolveInfo resolveInfo = (ResolveInfo) i; 10904// if (isEnabledLP(resolveInfo.serviceInfo)) { 10905// retList.add(resolveInfo); 10906// } 10907// } 10908// return retList; 10909// } 10910 10911 // Keys are String (activity class name), values are Activity. 10912 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10913 = new ArrayMap<ComponentName, PackageParser.Service>(); 10914 private int mFlags; 10915 }; 10916 10917 private final class ProviderIntentResolver 10918 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10919 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10920 boolean defaultOnly, int userId) { 10921 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10922 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10923 } 10924 10925 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10926 int userId) { 10927 if (!sUserManager.exists(userId)) 10928 return null; 10929 mFlags = flags; 10930 return super.queryIntent(intent, resolvedType, 10931 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10932 } 10933 10934 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10935 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10936 if (!sUserManager.exists(userId)) 10937 return null; 10938 if (packageProviders == null) { 10939 return null; 10940 } 10941 mFlags = flags; 10942 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10943 final int N = packageProviders.size(); 10944 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10945 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10946 10947 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10948 for (int i = 0; i < N; ++i) { 10949 intentFilters = packageProviders.get(i).intents; 10950 if (intentFilters != null && intentFilters.size() > 0) { 10951 PackageParser.ProviderIntentInfo[] array = 10952 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10953 intentFilters.toArray(array); 10954 listCut.add(array); 10955 } 10956 } 10957 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10958 } 10959 10960 public final void addProvider(PackageParser.Provider p) { 10961 if (mProviders.containsKey(p.getComponentName())) { 10962 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10963 return; 10964 } 10965 10966 mProviders.put(p.getComponentName(), p); 10967 if (DEBUG_SHOW_INFO) { 10968 Log.v(TAG, " " 10969 + (p.info.nonLocalizedLabel != null 10970 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10971 Log.v(TAG, " Class=" + p.info.name); 10972 } 10973 final int NI = p.intents.size(); 10974 int j; 10975 for (j = 0; j < NI; j++) { 10976 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10977 if (DEBUG_SHOW_INFO) { 10978 Log.v(TAG, " IntentFilter:"); 10979 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10980 } 10981 if (!intent.debugCheck()) { 10982 Log.w(TAG, "==> For Provider " + p.info.name); 10983 } 10984 addFilter(intent); 10985 } 10986 } 10987 10988 public final void removeProvider(PackageParser.Provider p) { 10989 mProviders.remove(p.getComponentName()); 10990 if (DEBUG_SHOW_INFO) { 10991 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10992 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10993 Log.v(TAG, " Class=" + p.info.name); 10994 } 10995 final int NI = p.intents.size(); 10996 int j; 10997 for (j = 0; j < NI; j++) { 10998 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10999 if (DEBUG_SHOW_INFO) { 11000 Log.v(TAG, " IntentFilter:"); 11001 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11002 } 11003 removeFilter(intent); 11004 } 11005 } 11006 11007 @Override 11008 protected boolean allowFilterResult( 11009 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11010 ProviderInfo filterPi = filter.provider.info; 11011 for (int i = dest.size() - 1; i >= 0; i--) { 11012 ProviderInfo destPi = dest.get(i).providerInfo; 11013 if (destPi.name == filterPi.name 11014 && destPi.packageName == filterPi.packageName) { 11015 return false; 11016 } 11017 } 11018 return true; 11019 } 11020 11021 @Override 11022 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11023 return new PackageParser.ProviderIntentInfo[size]; 11024 } 11025 11026 @Override 11027 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11028 if (!sUserManager.exists(userId)) 11029 return true; 11030 PackageParser.Package p = filter.provider.owner; 11031 if (p != null) { 11032 PackageSetting ps = (PackageSetting) p.mExtras; 11033 if (ps != null) { 11034 // System apps are never considered stopped for purposes of 11035 // filtering, because there may be no way for the user to 11036 // actually re-launch them. 11037 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11038 && ps.getStopped(userId); 11039 } 11040 } 11041 return false; 11042 } 11043 11044 @Override 11045 protected boolean isPackageForFilter(String packageName, 11046 PackageParser.ProviderIntentInfo info) { 11047 return packageName.equals(info.provider.owner.packageName); 11048 } 11049 11050 @Override 11051 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11052 int match, int userId) { 11053 if (!sUserManager.exists(userId)) 11054 return null; 11055 final PackageParser.ProviderIntentInfo info = filter; 11056 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11057 return null; 11058 } 11059 final PackageParser.Provider provider = info.provider; 11060 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11061 if (ps == null) { 11062 return null; 11063 } 11064 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11065 ps.readUserState(userId), userId); 11066 if (pi == null) { 11067 return null; 11068 } 11069 final ResolveInfo res = new ResolveInfo(); 11070 res.providerInfo = pi; 11071 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11072 res.filter = filter; 11073 } 11074 res.priority = info.getPriority(); 11075 res.preferredOrder = provider.owner.mPreferredOrder; 11076 res.match = match; 11077 res.isDefault = info.hasDefault; 11078 res.labelRes = info.labelRes; 11079 res.nonLocalizedLabel = info.nonLocalizedLabel; 11080 res.icon = info.icon; 11081 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11082 return res; 11083 } 11084 11085 @Override 11086 protected void sortResults(List<ResolveInfo> results) { 11087 Collections.sort(results, mResolvePrioritySorter); 11088 } 11089 11090 @Override 11091 protected void dumpFilter(PrintWriter out, String prefix, 11092 PackageParser.ProviderIntentInfo filter) { 11093 out.print(prefix); 11094 out.print( 11095 Integer.toHexString(System.identityHashCode(filter.provider))); 11096 out.print(' '); 11097 filter.provider.printComponentShortName(out); 11098 out.print(" filter "); 11099 out.println(Integer.toHexString(System.identityHashCode(filter))); 11100 } 11101 11102 @Override 11103 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11104 return filter.provider; 11105 } 11106 11107 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11108 PackageParser.Provider provider = (PackageParser.Provider)label; 11109 out.print(prefix); out.print( 11110 Integer.toHexString(System.identityHashCode(provider))); 11111 out.print(' '); 11112 provider.printComponentShortName(out); 11113 if (count > 1) { 11114 out.print(" ("); out.print(count); out.print(" filters)"); 11115 } 11116 out.println(); 11117 } 11118 11119 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11120 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11121 private int mFlags; 11122 } 11123 11124 private static final class EphemeralIntentResolver 11125 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11126 @Override 11127 protected EphemeralResolveIntentInfo[] newArray(int size) { 11128 return new EphemeralResolveIntentInfo[size]; 11129 } 11130 11131 @Override 11132 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11133 return true; 11134 } 11135 11136 @Override 11137 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11138 int userId) { 11139 if (!sUserManager.exists(userId)) { 11140 return null; 11141 } 11142 return info.getEphemeralResolveInfo(); 11143 } 11144 } 11145 11146 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11147 new Comparator<ResolveInfo>() { 11148 public int compare(ResolveInfo r1, ResolveInfo r2) { 11149 int v1 = r1.priority; 11150 int v2 = r2.priority; 11151 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11152 if (v1 != v2) { 11153 return (v1 > v2) ? -1 : 1; 11154 } 11155 v1 = r1.preferredOrder; 11156 v2 = r2.preferredOrder; 11157 if (v1 != v2) { 11158 return (v1 > v2) ? -1 : 1; 11159 } 11160 if (r1.isDefault != r2.isDefault) { 11161 return r1.isDefault ? -1 : 1; 11162 } 11163 v1 = r1.match; 11164 v2 = r2.match; 11165 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11166 if (v1 != v2) { 11167 return (v1 > v2) ? -1 : 1; 11168 } 11169 if (r1.system != r2.system) { 11170 return r1.system ? -1 : 1; 11171 } 11172 if (r1.activityInfo != null) { 11173 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11174 } 11175 if (r1.serviceInfo != null) { 11176 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11177 } 11178 if (r1.providerInfo != null) { 11179 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11180 } 11181 return 0; 11182 } 11183 }; 11184 11185 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11186 new Comparator<ProviderInfo>() { 11187 public int compare(ProviderInfo p1, ProviderInfo p2) { 11188 final int v1 = p1.initOrder; 11189 final int v2 = p2.initOrder; 11190 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11191 } 11192 }; 11193 11194 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11195 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11196 final int[] userIds) { 11197 mHandler.post(new Runnable() { 11198 @Override 11199 public void run() { 11200 try { 11201 final IActivityManager am = ActivityManagerNative.getDefault(); 11202 if (am == null) return; 11203 final int[] resolvedUserIds; 11204 if (userIds == null) { 11205 resolvedUserIds = am.getRunningUserIds(); 11206 } else { 11207 resolvedUserIds = userIds; 11208 } 11209 for (int id : resolvedUserIds) { 11210 final Intent intent = new Intent(action, 11211 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11212 if (extras != null) { 11213 intent.putExtras(extras); 11214 } 11215 if (targetPkg != null) { 11216 intent.setPackage(targetPkg); 11217 } 11218 // Modify the UID when posting to other users 11219 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11220 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11221 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11222 intent.putExtra(Intent.EXTRA_UID, uid); 11223 } 11224 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11225 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11226 if (DEBUG_BROADCASTS) { 11227 RuntimeException here = new RuntimeException("here"); 11228 here.fillInStackTrace(); 11229 Slog.d(TAG, "Sending to user " + id + ": " 11230 + intent.toShortString(false, true, false, false) 11231 + " " + intent.getExtras(), here); 11232 } 11233 am.broadcastIntent(null, intent, null, finishedReceiver, 11234 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11235 null, finishedReceiver != null, false, id); 11236 } 11237 } catch (RemoteException ex) { 11238 } 11239 } 11240 }); 11241 } 11242 11243 /** 11244 * Check if the external storage media is available. This is true if there 11245 * is a mounted external storage medium or if the external storage is 11246 * emulated. 11247 */ 11248 private boolean isExternalMediaAvailable() { 11249 return mMediaMounted || Environment.isExternalStorageEmulated(); 11250 } 11251 11252 @Override 11253 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11254 // writer 11255 synchronized (mPackages) { 11256 if (!isExternalMediaAvailable()) { 11257 // If the external storage is no longer mounted at this point, 11258 // the caller may not have been able to delete all of this 11259 // packages files and can not delete any more. Bail. 11260 return null; 11261 } 11262 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11263 if (lastPackage != null) { 11264 pkgs.remove(lastPackage); 11265 } 11266 if (pkgs.size() > 0) { 11267 return pkgs.get(0); 11268 } 11269 } 11270 return null; 11271 } 11272 11273 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11274 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11275 userId, andCode ? 1 : 0, packageName); 11276 if (mSystemReady) { 11277 msg.sendToTarget(); 11278 } else { 11279 if (mPostSystemReadyMessages == null) { 11280 mPostSystemReadyMessages = new ArrayList<>(); 11281 } 11282 mPostSystemReadyMessages.add(msg); 11283 } 11284 } 11285 11286 void startCleaningPackages() { 11287 // reader 11288 if (!isExternalMediaAvailable()) { 11289 return; 11290 } 11291 synchronized (mPackages) { 11292 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11293 return; 11294 } 11295 } 11296 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11297 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11298 IActivityManager am = ActivityManagerNative.getDefault(); 11299 if (am != null) { 11300 try { 11301 am.startService(null, intent, null, mContext.getOpPackageName(), 11302 UserHandle.USER_SYSTEM); 11303 } catch (RemoteException e) { 11304 } 11305 } 11306 } 11307 11308 @Override 11309 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11310 int installFlags, String installerPackageName, int userId) { 11311 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11312 11313 final int callingUid = Binder.getCallingUid(); 11314 enforceCrossUserPermission(callingUid, userId, 11315 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11316 11317 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11318 try { 11319 if (observer != null) { 11320 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11321 } 11322 } catch (RemoteException re) { 11323 } 11324 return; 11325 } 11326 11327 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11328 installFlags |= PackageManager.INSTALL_FROM_ADB; 11329 11330 } else { 11331 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11332 // about installerPackageName. 11333 11334 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11335 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11336 } 11337 11338 UserHandle user; 11339 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11340 user = UserHandle.ALL; 11341 } else { 11342 user = new UserHandle(userId); 11343 } 11344 11345 // Only system components can circumvent runtime permissions when installing. 11346 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11347 && mContext.checkCallingOrSelfPermission(Manifest.permission 11348 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11349 throw new SecurityException("You need the " 11350 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11351 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11352 } 11353 11354 final File originFile = new File(originPath); 11355 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11356 11357 final Message msg = mHandler.obtainMessage(INIT_COPY); 11358 final VerificationInfo verificationInfo = new VerificationInfo( 11359 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11360 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11361 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11362 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11363 null /*certificates*/); 11364 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11365 msg.obj = params; 11366 11367 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11368 System.identityHashCode(msg.obj)); 11369 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11370 System.identityHashCode(msg.obj)); 11371 11372 mHandler.sendMessage(msg); 11373 } 11374 11375 void installStage(String packageName, File stagedDir, String stagedCid, 11376 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11377 String installerPackageName, int installerUid, UserHandle user, 11378 Certificate[][] certificates) { 11379 if (DEBUG_EPHEMERAL) { 11380 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11381 Slog.d(TAG, "Ephemeral install of " + packageName); 11382 } 11383 } 11384 final VerificationInfo verificationInfo = new VerificationInfo( 11385 sessionParams.originatingUri, sessionParams.referrerUri, 11386 sessionParams.originatingUid, installerUid); 11387 11388 final OriginInfo origin; 11389 if (stagedDir != null) { 11390 origin = OriginInfo.fromStagedFile(stagedDir); 11391 } else { 11392 origin = OriginInfo.fromStagedContainer(stagedCid); 11393 } 11394 11395 final Message msg = mHandler.obtainMessage(INIT_COPY); 11396 final InstallParams params = new InstallParams(origin, null, observer, 11397 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11398 verificationInfo, user, sessionParams.abiOverride, 11399 sessionParams.grantedRuntimePermissions, certificates); 11400 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11401 msg.obj = params; 11402 11403 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11404 System.identityHashCode(msg.obj)); 11405 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11406 System.identityHashCode(msg.obj)); 11407 11408 mHandler.sendMessage(msg); 11409 } 11410 11411 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11412 int userId) { 11413 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11414 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11415 } 11416 11417 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11418 int appId, int userId) { 11419 Bundle extras = new Bundle(1); 11420 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11421 11422 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11423 packageName, extras, 0, null, null, new int[] {userId}); 11424 try { 11425 IActivityManager am = ActivityManagerNative.getDefault(); 11426 if (isSystem && am.isUserRunning(userId, 0)) { 11427 // The just-installed/enabled app is bundled on the system, so presumed 11428 // to be able to run automatically without needing an explicit launch. 11429 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11430 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11431 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11432 .setPackage(packageName); 11433 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11434 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11435 } 11436 } catch (RemoteException e) { 11437 // shouldn't happen 11438 Slog.w(TAG, "Unable to bootstrap installed package", e); 11439 } 11440 } 11441 11442 @Override 11443 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11444 int userId) { 11445 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11446 PackageSetting pkgSetting; 11447 final int uid = Binder.getCallingUid(); 11448 enforceCrossUserPermission(uid, userId, 11449 true /* requireFullPermission */, true /* checkShell */, 11450 "setApplicationHiddenSetting for user " + userId); 11451 11452 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11453 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11454 return false; 11455 } 11456 11457 long callingId = Binder.clearCallingIdentity(); 11458 try { 11459 boolean sendAdded = false; 11460 boolean sendRemoved = false; 11461 // writer 11462 synchronized (mPackages) { 11463 pkgSetting = mSettings.mPackages.get(packageName); 11464 if (pkgSetting == null) { 11465 return false; 11466 } 11467 if (pkgSetting.getHidden(userId) != hidden) { 11468 pkgSetting.setHidden(hidden, userId); 11469 mSettings.writePackageRestrictionsLPr(userId); 11470 if (hidden) { 11471 sendRemoved = true; 11472 } else { 11473 sendAdded = true; 11474 } 11475 } 11476 } 11477 if (sendAdded) { 11478 sendPackageAddedForUser(packageName, pkgSetting, userId); 11479 return true; 11480 } 11481 if (sendRemoved) { 11482 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11483 "hiding pkg"); 11484 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11485 return true; 11486 } 11487 } finally { 11488 Binder.restoreCallingIdentity(callingId); 11489 } 11490 return false; 11491 } 11492 11493 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11494 int userId) { 11495 final PackageRemovedInfo info = new PackageRemovedInfo(); 11496 info.removedPackage = packageName; 11497 info.removedUsers = new int[] {userId}; 11498 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11499 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11500 } 11501 11502 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11503 if (pkgList.length > 0) { 11504 Bundle extras = new Bundle(1); 11505 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11506 11507 sendPackageBroadcast( 11508 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11509 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11510 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11511 new int[] {userId}); 11512 } 11513 } 11514 11515 /** 11516 * Returns true if application is not found or there was an error. Otherwise it returns 11517 * the hidden state of the package for the given user. 11518 */ 11519 @Override 11520 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11521 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11522 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11523 true /* requireFullPermission */, false /* checkShell */, 11524 "getApplicationHidden for user " + userId); 11525 PackageSetting pkgSetting; 11526 long callingId = Binder.clearCallingIdentity(); 11527 try { 11528 // writer 11529 synchronized (mPackages) { 11530 pkgSetting = mSettings.mPackages.get(packageName); 11531 if (pkgSetting == null) { 11532 return true; 11533 } 11534 return pkgSetting.getHidden(userId); 11535 } 11536 } finally { 11537 Binder.restoreCallingIdentity(callingId); 11538 } 11539 } 11540 11541 /** 11542 * @hide 11543 */ 11544 @Override 11545 public int installExistingPackageAsUser(String packageName, int userId) { 11546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11547 null); 11548 PackageSetting pkgSetting; 11549 final int uid = Binder.getCallingUid(); 11550 enforceCrossUserPermission(uid, userId, 11551 true /* requireFullPermission */, true /* checkShell */, 11552 "installExistingPackage for user " + userId); 11553 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11554 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11555 } 11556 11557 long callingId = Binder.clearCallingIdentity(); 11558 try { 11559 boolean installed = false; 11560 11561 // writer 11562 synchronized (mPackages) { 11563 pkgSetting = mSettings.mPackages.get(packageName); 11564 if (pkgSetting == null) { 11565 return PackageManager.INSTALL_FAILED_INVALID_URI; 11566 } 11567 if (!pkgSetting.getInstalled(userId)) { 11568 pkgSetting.setInstalled(true, userId); 11569 pkgSetting.setHidden(false, userId); 11570 mSettings.writePackageRestrictionsLPr(userId); 11571 installed = true; 11572 } 11573 } 11574 11575 if (installed) { 11576 if (pkgSetting.pkg != null) { 11577 synchronized (mInstallLock) { 11578 // We don't need to freeze for a brand new install 11579 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11580 } 11581 } 11582 sendPackageAddedForUser(packageName, pkgSetting, userId); 11583 } 11584 } finally { 11585 Binder.restoreCallingIdentity(callingId); 11586 } 11587 11588 return PackageManager.INSTALL_SUCCEEDED; 11589 } 11590 11591 boolean isUserRestricted(int userId, String restrictionKey) { 11592 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11593 if (restrictions.getBoolean(restrictionKey, false)) { 11594 Log.w(TAG, "User is restricted: " + restrictionKey); 11595 return true; 11596 } 11597 return false; 11598 } 11599 11600 @Override 11601 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11602 int userId) { 11603 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11604 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11605 true /* requireFullPermission */, true /* checkShell */, 11606 "setPackagesSuspended for user " + userId); 11607 11608 if (ArrayUtils.isEmpty(packageNames)) { 11609 return packageNames; 11610 } 11611 11612 // List of package names for whom the suspended state has changed. 11613 List<String> changedPackages = new ArrayList<>(packageNames.length); 11614 // List of package names for whom the suspended state is not set as requested in this 11615 // method. 11616 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11617 long callingId = Binder.clearCallingIdentity(); 11618 try { 11619 for (int i = 0; i < packageNames.length; i++) { 11620 String packageName = packageNames[i]; 11621 boolean changed = false; 11622 final int appId; 11623 synchronized (mPackages) { 11624 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11625 if (pkgSetting == null) { 11626 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11627 + "\". Skipping suspending/un-suspending."); 11628 unactionedPackages.add(packageName); 11629 continue; 11630 } 11631 appId = pkgSetting.appId; 11632 if (pkgSetting.getSuspended(userId) != suspended) { 11633 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11634 unactionedPackages.add(packageName); 11635 continue; 11636 } 11637 pkgSetting.setSuspended(suspended, userId); 11638 mSettings.writePackageRestrictionsLPr(userId); 11639 changed = true; 11640 changedPackages.add(packageName); 11641 } 11642 } 11643 11644 if (changed && suspended) { 11645 killApplication(packageName, UserHandle.getUid(userId, appId), 11646 "suspending package"); 11647 } 11648 } 11649 } finally { 11650 Binder.restoreCallingIdentity(callingId); 11651 } 11652 11653 if (!changedPackages.isEmpty()) { 11654 sendPackagesSuspendedForUser(changedPackages.toArray( 11655 new String[changedPackages.size()]), userId, suspended); 11656 } 11657 11658 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11659 } 11660 11661 @Override 11662 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11663 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11664 true /* requireFullPermission */, false /* checkShell */, 11665 "isPackageSuspendedForUser for user " + userId); 11666 synchronized (mPackages) { 11667 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11668 if (pkgSetting == null) { 11669 throw new IllegalArgumentException("Unknown target package: " + packageName); 11670 } 11671 return pkgSetting.getSuspended(userId); 11672 } 11673 } 11674 11675 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11676 if (isPackageDeviceAdmin(packageName, userId)) { 11677 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11678 + "\": has an active device admin"); 11679 return false; 11680 } 11681 11682 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11683 if (packageName.equals(activeLauncherPackageName)) { 11684 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11685 + "\": contains the active launcher"); 11686 return false; 11687 } 11688 11689 if (packageName.equals(mRequiredInstallerPackage)) { 11690 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11691 + "\": required for package installation"); 11692 return false; 11693 } 11694 11695 if (packageName.equals(mRequiredVerifierPackage)) { 11696 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11697 + "\": required for package verification"); 11698 return false; 11699 } 11700 11701 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11702 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11703 + "\": is the default dialer"); 11704 return false; 11705 } 11706 11707 return true; 11708 } 11709 11710 private String getActiveLauncherPackageName(int userId) { 11711 Intent intent = new Intent(Intent.ACTION_MAIN); 11712 intent.addCategory(Intent.CATEGORY_HOME); 11713 ResolveInfo resolveInfo = resolveIntent( 11714 intent, 11715 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11716 PackageManager.MATCH_DEFAULT_ONLY, 11717 userId); 11718 11719 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11720 } 11721 11722 private String getDefaultDialerPackageName(int userId) { 11723 synchronized (mPackages) { 11724 return mSettings.getDefaultDialerPackageNameLPw(userId); 11725 } 11726 } 11727 11728 @Override 11729 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11730 mContext.enforceCallingOrSelfPermission( 11731 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11732 "Only package verification agents can verify applications"); 11733 11734 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11735 final PackageVerificationResponse response = new PackageVerificationResponse( 11736 verificationCode, Binder.getCallingUid()); 11737 msg.arg1 = id; 11738 msg.obj = response; 11739 mHandler.sendMessage(msg); 11740 } 11741 11742 @Override 11743 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11744 long millisecondsToDelay) { 11745 mContext.enforceCallingOrSelfPermission( 11746 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11747 "Only package verification agents can extend verification timeouts"); 11748 11749 final PackageVerificationState state = mPendingVerification.get(id); 11750 final PackageVerificationResponse response = new PackageVerificationResponse( 11751 verificationCodeAtTimeout, Binder.getCallingUid()); 11752 11753 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11754 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11755 } 11756 if (millisecondsToDelay < 0) { 11757 millisecondsToDelay = 0; 11758 } 11759 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11760 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11761 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11762 } 11763 11764 if ((state != null) && !state.timeoutExtended()) { 11765 state.extendTimeout(); 11766 11767 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11768 msg.arg1 = id; 11769 msg.obj = response; 11770 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11771 } 11772 } 11773 11774 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11775 int verificationCode, UserHandle user) { 11776 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11777 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11778 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11779 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11780 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11781 11782 mContext.sendBroadcastAsUser(intent, user, 11783 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11784 } 11785 11786 private ComponentName matchComponentForVerifier(String packageName, 11787 List<ResolveInfo> receivers) { 11788 ActivityInfo targetReceiver = null; 11789 11790 final int NR = receivers.size(); 11791 for (int i = 0; i < NR; i++) { 11792 final ResolveInfo info = receivers.get(i); 11793 if (info.activityInfo == null) { 11794 continue; 11795 } 11796 11797 if (packageName.equals(info.activityInfo.packageName)) { 11798 targetReceiver = info.activityInfo; 11799 break; 11800 } 11801 } 11802 11803 if (targetReceiver == null) { 11804 return null; 11805 } 11806 11807 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11808 } 11809 11810 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11811 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11812 if (pkgInfo.verifiers.length == 0) { 11813 return null; 11814 } 11815 11816 final int N = pkgInfo.verifiers.length; 11817 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11818 for (int i = 0; i < N; i++) { 11819 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11820 11821 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11822 receivers); 11823 if (comp == null) { 11824 continue; 11825 } 11826 11827 final int verifierUid = getUidForVerifier(verifierInfo); 11828 if (verifierUid == -1) { 11829 continue; 11830 } 11831 11832 if (DEBUG_VERIFY) { 11833 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11834 + " with the correct signature"); 11835 } 11836 sufficientVerifiers.add(comp); 11837 verificationState.addSufficientVerifier(verifierUid); 11838 } 11839 11840 return sufficientVerifiers; 11841 } 11842 11843 private int getUidForVerifier(VerifierInfo verifierInfo) { 11844 synchronized (mPackages) { 11845 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11846 if (pkg == null) { 11847 return -1; 11848 } else if (pkg.mSignatures.length != 1) { 11849 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11850 + " has more than one signature; ignoring"); 11851 return -1; 11852 } 11853 11854 /* 11855 * If the public key of the package's signature does not match 11856 * our expected public key, then this is a different package and 11857 * we should skip. 11858 */ 11859 11860 final byte[] expectedPublicKey; 11861 try { 11862 final Signature verifierSig = pkg.mSignatures[0]; 11863 final PublicKey publicKey = verifierSig.getPublicKey(); 11864 expectedPublicKey = publicKey.getEncoded(); 11865 } catch (CertificateException e) { 11866 return -1; 11867 } 11868 11869 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11870 11871 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11872 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11873 + " does not have the expected public key; ignoring"); 11874 return -1; 11875 } 11876 11877 return pkg.applicationInfo.uid; 11878 } 11879 } 11880 11881 @Override 11882 public void finishPackageInstall(int token, boolean didLaunch) { 11883 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11884 11885 if (DEBUG_INSTALL) { 11886 Slog.v(TAG, "BM finishing package install for " + token); 11887 } 11888 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11889 11890 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11891 mHandler.sendMessage(msg); 11892 } 11893 11894 /** 11895 * Get the verification agent timeout. 11896 * 11897 * @return verification timeout in milliseconds 11898 */ 11899 private long getVerificationTimeout() { 11900 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11901 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11902 DEFAULT_VERIFICATION_TIMEOUT); 11903 } 11904 11905 /** 11906 * Get the default verification agent response code. 11907 * 11908 * @return default verification response code 11909 */ 11910 private int getDefaultVerificationResponse() { 11911 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11912 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11913 DEFAULT_VERIFICATION_RESPONSE); 11914 } 11915 11916 /** 11917 * Check whether or not package verification has been enabled. 11918 * 11919 * @return true if verification should be performed 11920 */ 11921 private boolean isVerificationEnabled(int userId, int installFlags) { 11922 if (!DEFAULT_VERIFY_ENABLE) { 11923 return false; 11924 } 11925 // Ephemeral apps don't get the full verification treatment 11926 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11927 if (DEBUG_EPHEMERAL) { 11928 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11929 } 11930 return false; 11931 } 11932 11933 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11934 11935 // Check if installing from ADB 11936 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11937 // Do not run verification in a test harness environment 11938 if (ActivityManager.isRunningInTestHarness()) { 11939 return false; 11940 } 11941 if (ensureVerifyAppsEnabled) { 11942 return true; 11943 } 11944 // Check if the developer does not want package verification for ADB installs 11945 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11946 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11947 return false; 11948 } 11949 } 11950 11951 if (ensureVerifyAppsEnabled) { 11952 return true; 11953 } 11954 11955 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11956 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11957 } 11958 11959 @Override 11960 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11961 throws RemoteException { 11962 mContext.enforceCallingOrSelfPermission( 11963 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11964 "Only intentfilter verification agents can verify applications"); 11965 11966 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11967 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11968 Binder.getCallingUid(), verificationCode, failedDomains); 11969 msg.arg1 = id; 11970 msg.obj = response; 11971 mHandler.sendMessage(msg); 11972 } 11973 11974 @Override 11975 public int getIntentVerificationStatus(String packageName, int userId) { 11976 synchronized (mPackages) { 11977 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11978 } 11979 } 11980 11981 @Override 11982 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11983 mContext.enforceCallingOrSelfPermission( 11984 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11985 11986 boolean result = false; 11987 synchronized (mPackages) { 11988 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11989 } 11990 if (result) { 11991 scheduleWritePackageRestrictionsLocked(userId); 11992 } 11993 return result; 11994 } 11995 11996 @Override 11997 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11998 String packageName) { 11999 synchronized (mPackages) { 12000 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12001 } 12002 } 12003 12004 @Override 12005 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12006 if (TextUtils.isEmpty(packageName)) { 12007 return ParceledListSlice.emptyList(); 12008 } 12009 synchronized (mPackages) { 12010 PackageParser.Package pkg = mPackages.get(packageName); 12011 if (pkg == null || pkg.activities == null) { 12012 return ParceledListSlice.emptyList(); 12013 } 12014 final int count = pkg.activities.size(); 12015 ArrayList<IntentFilter> result = new ArrayList<>(); 12016 for (int n=0; n<count; n++) { 12017 PackageParser.Activity activity = pkg.activities.get(n); 12018 if (activity.intents != null && activity.intents.size() > 0) { 12019 result.addAll(activity.intents); 12020 } 12021 } 12022 return new ParceledListSlice<>(result); 12023 } 12024 } 12025 12026 @Override 12027 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12028 mContext.enforceCallingOrSelfPermission( 12029 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12030 12031 synchronized (mPackages) { 12032 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12033 if (packageName != null) { 12034 result |= updateIntentVerificationStatus(packageName, 12035 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12036 userId); 12037 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12038 packageName, userId); 12039 } 12040 return result; 12041 } 12042 } 12043 12044 @Override 12045 public String getDefaultBrowserPackageName(int userId) { 12046 synchronized (mPackages) { 12047 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12048 } 12049 } 12050 12051 /** 12052 * Get the "allow unknown sources" setting. 12053 * 12054 * @return the current "allow unknown sources" setting 12055 */ 12056 private int getUnknownSourcesSettings() { 12057 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12058 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12059 -1); 12060 } 12061 12062 @Override 12063 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12064 final int uid = Binder.getCallingUid(); 12065 // writer 12066 synchronized (mPackages) { 12067 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12068 if (targetPackageSetting == null) { 12069 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12070 } 12071 12072 PackageSetting installerPackageSetting; 12073 if (installerPackageName != null) { 12074 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12075 if (installerPackageSetting == null) { 12076 throw new IllegalArgumentException("Unknown installer package: " 12077 + installerPackageName); 12078 } 12079 } else { 12080 installerPackageSetting = null; 12081 } 12082 12083 Signature[] callerSignature; 12084 Object obj = mSettings.getUserIdLPr(uid); 12085 if (obj != null) { 12086 if (obj instanceof SharedUserSetting) { 12087 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12088 } else if (obj instanceof PackageSetting) { 12089 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12090 } else { 12091 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12092 } 12093 } else { 12094 throw new SecurityException("Unknown calling UID: " + uid); 12095 } 12096 12097 // Verify: can't set installerPackageName to a package that is 12098 // not signed with the same cert as the caller. 12099 if (installerPackageSetting != null) { 12100 if (compareSignatures(callerSignature, 12101 installerPackageSetting.signatures.mSignatures) 12102 != PackageManager.SIGNATURE_MATCH) { 12103 throw new SecurityException( 12104 "Caller does not have same cert as new installer package " 12105 + installerPackageName); 12106 } 12107 } 12108 12109 // Verify: if target already has an installer package, it must 12110 // be signed with the same cert as the caller. 12111 if (targetPackageSetting.installerPackageName != null) { 12112 PackageSetting setting = mSettings.mPackages.get( 12113 targetPackageSetting.installerPackageName); 12114 // If the currently set package isn't valid, then it's always 12115 // okay to change it. 12116 if (setting != null) { 12117 if (compareSignatures(callerSignature, 12118 setting.signatures.mSignatures) 12119 != PackageManager.SIGNATURE_MATCH) { 12120 throw new SecurityException( 12121 "Caller does not have same cert as old installer package " 12122 + targetPackageSetting.installerPackageName); 12123 } 12124 } 12125 } 12126 12127 // Okay! 12128 targetPackageSetting.installerPackageName = installerPackageName; 12129 if (installerPackageName != null) { 12130 mSettings.mInstallerPackages.add(installerPackageName); 12131 } 12132 scheduleWriteSettingsLocked(); 12133 } 12134 } 12135 12136 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12137 // Queue up an async operation since the package installation may take a little while. 12138 mHandler.post(new Runnable() { 12139 public void run() { 12140 mHandler.removeCallbacks(this); 12141 // Result object to be returned 12142 PackageInstalledInfo res = new PackageInstalledInfo(); 12143 res.setReturnCode(currentStatus); 12144 res.uid = -1; 12145 res.pkg = null; 12146 res.removedInfo = null; 12147 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12148 args.doPreInstall(res.returnCode); 12149 synchronized (mInstallLock) { 12150 installPackageTracedLI(args, res); 12151 } 12152 args.doPostInstall(res.returnCode, res.uid); 12153 } 12154 12155 // A restore should be performed at this point if (a) the install 12156 // succeeded, (b) the operation is not an update, and (c) the new 12157 // package has not opted out of backup participation. 12158 final boolean update = res.removedInfo != null 12159 && res.removedInfo.removedPackage != null; 12160 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12161 boolean doRestore = !update 12162 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12163 12164 // Set up the post-install work request bookkeeping. This will be used 12165 // and cleaned up by the post-install event handling regardless of whether 12166 // there's a restore pass performed. Token values are >= 1. 12167 int token; 12168 if (mNextInstallToken < 0) mNextInstallToken = 1; 12169 token = mNextInstallToken++; 12170 12171 PostInstallData data = new PostInstallData(args, res); 12172 mRunningInstalls.put(token, data); 12173 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12174 12175 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12176 // Pass responsibility to the Backup Manager. It will perform a 12177 // restore if appropriate, then pass responsibility back to the 12178 // Package Manager to run the post-install observer callbacks 12179 // and broadcasts. 12180 IBackupManager bm = IBackupManager.Stub.asInterface( 12181 ServiceManager.getService(Context.BACKUP_SERVICE)); 12182 if (bm != null) { 12183 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12184 + " to BM for possible restore"); 12185 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12186 try { 12187 // TODO: http://b/22388012 12188 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12189 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12190 } else { 12191 doRestore = false; 12192 } 12193 } catch (RemoteException e) { 12194 // can't happen; the backup manager is local 12195 } catch (Exception e) { 12196 Slog.e(TAG, "Exception trying to enqueue restore", e); 12197 doRestore = false; 12198 } 12199 } else { 12200 Slog.e(TAG, "Backup Manager not found!"); 12201 doRestore = false; 12202 } 12203 } 12204 12205 if (!doRestore) { 12206 // No restore possible, or the Backup Manager was mysteriously not 12207 // available -- just fire the post-install work request directly. 12208 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12209 12210 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12211 12212 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12213 mHandler.sendMessage(msg); 12214 } 12215 } 12216 }); 12217 } 12218 12219 /** 12220 * Callback from PackageSettings whenever an app is first transitioned out of the 12221 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12222 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12223 * here whether the app is the target of an ongoing install, and only send the 12224 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12225 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12226 * handling. 12227 */ 12228 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12229 // Serialize this with the rest of the install-process message chain. In the 12230 // restore-at-install case, this Runnable will necessarily run before the 12231 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12232 // are coherent. In the non-restore case, the app has already completed install 12233 // and been launched through some other means, so it is not in a problematic 12234 // state for observers to see the FIRST_LAUNCH signal. 12235 mHandler.post(new Runnable() { 12236 @Override 12237 public void run() { 12238 for (int i = 0; i < mRunningInstalls.size(); i++) { 12239 final PostInstallData data = mRunningInstalls.valueAt(i); 12240 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12241 // right package; but is it for the right user? 12242 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12243 if (userId == data.res.newUsers[uIndex]) { 12244 if (DEBUG_BACKUP) { 12245 Slog.i(TAG, "Package " + pkgName 12246 + " being restored so deferring FIRST_LAUNCH"); 12247 } 12248 return; 12249 } 12250 } 12251 } 12252 } 12253 // didn't find it, so not being restored 12254 if (DEBUG_BACKUP) { 12255 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12256 } 12257 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12258 } 12259 }); 12260 } 12261 12262 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12263 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12264 installerPkg, null, userIds); 12265 } 12266 12267 private abstract class HandlerParams { 12268 private static final int MAX_RETRIES = 4; 12269 12270 /** 12271 * Number of times startCopy() has been attempted and had a non-fatal 12272 * error. 12273 */ 12274 private int mRetries = 0; 12275 12276 /** User handle for the user requesting the information or installation. */ 12277 private final UserHandle mUser; 12278 String traceMethod; 12279 int traceCookie; 12280 12281 HandlerParams(UserHandle user) { 12282 mUser = user; 12283 } 12284 12285 UserHandle getUser() { 12286 return mUser; 12287 } 12288 12289 HandlerParams setTraceMethod(String traceMethod) { 12290 this.traceMethod = traceMethod; 12291 return this; 12292 } 12293 12294 HandlerParams setTraceCookie(int traceCookie) { 12295 this.traceCookie = traceCookie; 12296 return this; 12297 } 12298 12299 final boolean startCopy() { 12300 boolean res; 12301 try { 12302 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12303 12304 if (++mRetries > MAX_RETRIES) { 12305 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12306 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12307 handleServiceError(); 12308 return false; 12309 } else { 12310 handleStartCopy(); 12311 res = true; 12312 } 12313 } catch (RemoteException e) { 12314 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12315 mHandler.sendEmptyMessage(MCS_RECONNECT); 12316 res = false; 12317 } 12318 handleReturnCode(); 12319 return res; 12320 } 12321 12322 final void serviceError() { 12323 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12324 handleServiceError(); 12325 handleReturnCode(); 12326 } 12327 12328 abstract void handleStartCopy() throws RemoteException; 12329 abstract void handleServiceError(); 12330 abstract void handleReturnCode(); 12331 } 12332 12333 class MeasureParams extends HandlerParams { 12334 private final PackageStats mStats; 12335 private boolean mSuccess; 12336 12337 private final IPackageStatsObserver mObserver; 12338 12339 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12340 super(new UserHandle(stats.userHandle)); 12341 mObserver = observer; 12342 mStats = stats; 12343 } 12344 12345 @Override 12346 public String toString() { 12347 return "MeasureParams{" 12348 + Integer.toHexString(System.identityHashCode(this)) 12349 + " " + mStats.packageName + "}"; 12350 } 12351 12352 @Override 12353 void handleStartCopy() throws RemoteException { 12354 synchronized (mInstallLock) { 12355 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12356 } 12357 12358 if (mSuccess) { 12359 final boolean mounted; 12360 if (Environment.isExternalStorageEmulated()) { 12361 mounted = true; 12362 } else { 12363 final String status = Environment.getExternalStorageState(); 12364 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12365 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12366 } 12367 12368 if (mounted) { 12369 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12370 12371 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12372 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12373 12374 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12375 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12376 12377 // Always subtract cache size, since it's a subdirectory 12378 mStats.externalDataSize -= mStats.externalCacheSize; 12379 12380 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12381 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12382 12383 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12384 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12385 } 12386 } 12387 } 12388 12389 @Override 12390 void handleReturnCode() { 12391 if (mObserver != null) { 12392 try { 12393 mObserver.onGetStatsCompleted(mStats, mSuccess); 12394 } catch (RemoteException e) { 12395 Slog.i(TAG, "Observer no longer exists."); 12396 } 12397 } 12398 } 12399 12400 @Override 12401 void handleServiceError() { 12402 Slog.e(TAG, "Could not measure application " + mStats.packageName 12403 + " external storage"); 12404 } 12405 } 12406 12407 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12408 throws RemoteException { 12409 long result = 0; 12410 for (File path : paths) { 12411 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12412 } 12413 return result; 12414 } 12415 12416 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12417 for (File path : paths) { 12418 try { 12419 mcs.clearDirectory(path.getAbsolutePath()); 12420 } catch (RemoteException e) { 12421 } 12422 } 12423 } 12424 12425 static class OriginInfo { 12426 /** 12427 * Location where install is coming from, before it has been 12428 * copied/renamed into place. This could be a single monolithic APK 12429 * file, or a cluster directory. This location may be untrusted. 12430 */ 12431 final File file; 12432 final String cid; 12433 12434 /** 12435 * Flag indicating that {@link #file} or {@link #cid} has already been 12436 * staged, meaning downstream users don't need to defensively copy the 12437 * contents. 12438 */ 12439 final boolean staged; 12440 12441 /** 12442 * Flag indicating that {@link #file} or {@link #cid} is an already 12443 * installed app that is being moved. 12444 */ 12445 final boolean existing; 12446 12447 final String resolvedPath; 12448 final File resolvedFile; 12449 12450 static OriginInfo fromNothing() { 12451 return new OriginInfo(null, null, false, false); 12452 } 12453 12454 static OriginInfo fromUntrustedFile(File file) { 12455 return new OriginInfo(file, null, false, false); 12456 } 12457 12458 static OriginInfo fromExistingFile(File file) { 12459 return new OriginInfo(file, null, false, true); 12460 } 12461 12462 static OriginInfo fromStagedFile(File file) { 12463 return new OriginInfo(file, null, true, false); 12464 } 12465 12466 static OriginInfo fromStagedContainer(String cid) { 12467 return new OriginInfo(null, cid, true, false); 12468 } 12469 12470 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12471 this.file = file; 12472 this.cid = cid; 12473 this.staged = staged; 12474 this.existing = existing; 12475 12476 if (cid != null) { 12477 resolvedPath = PackageHelper.getSdDir(cid); 12478 resolvedFile = new File(resolvedPath); 12479 } else if (file != null) { 12480 resolvedPath = file.getAbsolutePath(); 12481 resolvedFile = file; 12482 } else { 12483 resolvedPath = null; 12484 resolvedFile = null; 12485 } 12486 } 12487 } 12488 12489 static class MoveInfo { 12490 final int moveId; 12491 final String fromUuid; 12492 final String toUuid; 12493 final String packageName; 12494 final String dataAppName; 12495 final int appId; 12496 final String seinfo; 12497 final int targetSdkVersion; 12498 12499 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12500 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12501 this.moveId = moveId; 12502 this.fromUuid = fromUuid; 12503 this.toUuid = toUuid; 12504 this.packageName = packageName; 12505 this.dataAppName = dataAppName; 12506 this.appId = appId; 12507 this.seinfo = seinfo; 12508 this.targetSdkVersion = targetSdkVersion; 12509 } 12510 } 12511 12512 static class VerificationInfo { 12513 /** A constant used to indicate that a uid value is not present. */ 12514 public static final int NO_UID = -1; 12515 12516 /** URI referencing where the package was downloaded from. */ 12517 final Uri originatingUri; 12518 12519 /** HTTP referrer URI associated with the originatingURI. */ 12520 final Uri referrer; 12521 12522 /** UID of the application that the install request originated from. */ 12523 final int originatingUid; 12524 12525 /** UID of application requesting the install */ 12526 final int installerUid; 12527 12528 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12529 this.originatingUri = originatingUri; 12530 this.referrer = referrer; 12531 this.originatingUid = originatingUid; 12532 this.installerUid = installerUid; 12533 } 12534 } 12535 12536 class InstallParams extends HandlerParams { 12537 final OriginInfo origin; 12538 final MoveInfo move; 12539 final IPackageInstallObserver2 observer; 12540 int installFlags; 12541 final String installerPackageName; 12542 final String volumeUuid; 12543 private InstallArgs mArgs; 12544 private int mRet; 12545 final String packageAbiOverride; 12546 final String[] grantedRuntimePermissions; 12547 final VerificationInfo verificationInfo; 12548 final Certificate[][] certificates; 12549 12550 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12551 int installFlags, String installerPackageName, String volumeUuid, 12552 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12553 String[] grantedPermissions, Certificate[][] certificates) { 12554 super(user); 12555 this.origin = origin; 12556 this.move = move; 12557 this.observer = observer; 12558 this.installFlags = installFlags; 12559 this.installerPackageName = installerPackageName; 12560 this.volumeUuid = volumeUuid; 12561 this.verificationInfo = verificationInfo; 12562 this.packageAbiOverride = packageAbiOverride; 12563 this.grantedRuntimePermissions = grantedPermissions; 12564 this.certificates = certificates; 12565 } 12566 12567 @Override 12568 public String toString() { 12569 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12570 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12571 } 12572 12573 private int installLocationPolicy(PackageInfoLite pkgLite) { 12574 String packageName = pkgLite.packageName; 12575 int installLocation = pkgLite.installLocation; 12576 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12577 // reader 12578 synchronized (mPackages) { 12579 // Currently installed package which the new package is attempting to replace or 12580 // null if no such package is installed. 12581 PackageParser.Package installedPkg = mPackages.get(packageName); 12582 // Package which currently owns the data which the new package will own if installed. 12583 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12584 // will be null whereas dataOwnerPkg will contain information about the package 12585 // which was uninstalled while keeping its data. 12586 PackageParser.Package dataOwnerPkg = installedPkg; 12587 if (dataOwnerPkg == null) { 12588 PackageSetting ps = mSettings.mPackages.get(packageName); 12589 if (ps != null) { 12590 dataOwnerPkg = ps.pkg; 12591 } 12592 } 12593 12594 if (dataOwnerPkg != null) { 12595 // If installed, the package will get access to data left on the device by its 12596 // predecessor. As a security measure, this is permited only if this is not a 12597 // version downgrade or if the predecessor package is marked as debuggable and 12598 // a downgrade is explicitly requested. 12599 // 12600 // On debuggable platform builds, downgrades are permitted even for 12601 // non-debuggable packages to make testing easier. Debuggable platform builds do 12602 // not offer security guarantees and thus it's OK to disable some security 12603 // mechanisms to make debugging/testing easier on those builds. However, even on 12604 // debuggable builds downgrades of packages are permitted only if requested via 12605 // installFlags. This is because we aim to keep the behavior of debuggable 12606 // platform builds as close as possible to the behavior of non-debuggable 12607 // platform builds. 12608 final boolean downgradeRequested = 12609 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12610 final boolean packageDebuggable = 12611 (dataOwnerPkg.applicationInfo.flags 12612 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12613 final boolean downgradePermitted = 12614 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12615 if (!downgradePermitted) { 12616 try { 12617 checkDowngrade(dataOwnerPkg, pkgLite); 12618 } catch (PackageManagerException e) { 12619 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12620 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12621 } 12622 } 12623 } 12624 12625 if (installedPkg != null) { 12626 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12627 // Check for updated system application. 12628 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12629 if (onSd) { 12630 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12631 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12632 } 12633 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12634 } else { 12635 if (onSd) { 12636 // Install flag overrides everything. 12637 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12638 } 12639 // If current upgrade specifies particular preference 12640 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12641 // Application explicitly specified internal. 12642 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12643 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12644 // App explictly prefers external. Let policy decide 12645 } else { 12646 // Prefer previous location 12647 if (isExternal(installedPkg)) { 12648 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12649 } 12650 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12651 } 12652 } 12653 } else { 12654 // Invalid install. Return error code 12655 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12656 } 12657 } 12658 } 12659 // All the special cases have been taken care of. 12660 // Return result based on recommended install location. 12661 if (onSd) { 12662 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12663 } 12664 return pkgLite.recommendedInstallLocation; 12665 } 12666 12667 /* 12668 * Invoke remote method to get package information and install 12669 * location values. Override install location based on default 12670 * policy if needed and then create install arguments based 12671 * on the install location. 12672 */ 12673 public void handleStartCopy() throws RemoteException { 12674 int ret = PackageManager.INSTALL_SUCCEEDED; 12675 12676 // If we're already staged, we've firmly committed to an install location 12677 if (origin.staged) { 12678 if (origin.file != null) { 12679 installFlags |= PackageManager.INSTALL_INTERNAL; 12680 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12681 } else if (origin.cid != null) { 12682 installFlags |= PackageManager.INSTALL_EXTERNAL; 12683 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12684 } else { 12685 throw new IllegalStateException("Invalid stage location"); 12686 } 12687 } 12688 12689 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12690 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12691 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12692 PackageInfoLite pkgLite = null; 12693 12694 if (onInt && onSd) { 12695 // Check if both bits are set. 12696 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12697 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12698 } else if (onSd && ephemeral) { 12699 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12700 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12701 } else { 12702 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12703 packageAbiOverride); 12704 12705 if (DEBUG_EPHEMERAL && ephemeral) { 12706 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12707 } 12708 12709 /* 12710 * If we have too little free space, try to free cache 12711 * before giving up. 12712 */ 12713 if (!origin.staged && pkgLite.recommendedInstallLocation 12714 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12715 // TODO: focus freeing disk space on the target device 12716 final StorageManager storage = StorageManager.from(mContext); 12717 final long lowThreshold = storage.getStorageLowBytes( 12718 Environment.getDataDirectory()); 12719 12720 final long sizeBytes = mContainerService.calculateInstalledSize( 12721 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12722 12723 try { 12724 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12725 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12726 installFlags, packageAbiOverride); 12727 } catch (InstallerException e) { 12728 Slog.w(TAG, "Failed to free cache", e); 12729 } 12730 12731 /* 12732 * The cache free must have deleted the file we 12733 * downloaded to install. 12734 * 12735 * TODO: fix the "freeCache" call to not delete 12736 * the file we care about. 12737 */ 12738 if (pkgLite.recommendedInstallLocation 12739 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12740 pkgLite.recommendedInstallLocation 12741 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12742 } 12743 } 12744 } 12745 12746 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12747 int loc = pkgLite.recommendedInstallLocation; 12748 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12749 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12750 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12751 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12752 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12753 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12754 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12755 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12756 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12757 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12758 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12759 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12760 } else { 12761 // Override with defaults if needed. 12762 loc = installLocationPolicy(pkgLite); 12763 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12764 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12765 } else if (!onSd && !onInt) { 12766 // Override install location with flags 12767 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12768 // Set the flag to install on external media. 12769 installFlags |= PackageManager.INSTALL_EXTERNAL; 12770 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12771 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12772 if (DEBUG_EPHEMERAL) { 12773 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12774 } 12775 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12776 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12777 |PackageManager.INSTALL_INTERNAL); 12778 } else { 12779 // Make sure the flag for installing on external 12780 // media is unset 12781 installFlags |= PackageManager.INSTALL_INTERNAL; 12782 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12783 } 12784 } 12785 } 12786 } 12787 12788 final InstallArgs args = createInstallArgs(this); 12789 mArgs = args; 12790 12791 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12792 // TODO: http://b/22976637 12793 // Apps installed for "all" users use the device owner to verify the app 12794 UserHandle verifierUser = getUser(); 12795 if (verifierUser == UserHandle.ALL) { 12796 verifierUser = UserHandle.SYSTEM; 12797 } 12798 12799 /* 12800 * Determine if we have any installed package verifiers. If we 12801 * do, then we'll defer to them to verify the packages. 12802 */ 12803 final int requiredUid = mRequiredVerifierPackage == null ? -1 12804 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12805 verifierUser.getIdentifier()); 12806 if (!origin.existing && requiredUid != -1 12807 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12808 final Intent verification = new Intent( 12809 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12810 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12811 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12812 PACKAGE_MIME_TYPE); 12813 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12814 12815 // Query all live verifiers based on current user state 12816 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12817 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12818 12819 if (DEBUG_VERIFY) { 12820 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12821 + verification.toString() + " with " + pkgLite.verifiers.length 12822 + " optional verifiers"); 12823 } 12824 12825 final int verificationId = mPendingVerificationToken++; 12826 12827 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12828 12829 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12830 installerPackageName); 12831 12832 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12833 installFlags); 12834 12835 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12836 pkgLite.packageName); 12837 12838 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12839 pkgLite.versionCode); 12840 12841 if (verificationInfo != null) { 12842 if (verificationInfo.originatingUri != null) { 12843 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12844 verificationInfo.originatingUri); 12845 } 12846 if (verificationInfo.referrer != null) { 12847 verification.putExtra(Intent.EXTRA_REFERRER, 12848 verificationInfo.referrer); 12849 } 12850 if (verificationInfo.originatingUid >= 0) { 12851 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12852 verificationInfo.originatingUid); 12853 } 12854 if (verificationInfo.installerUid >= 0) { 12855 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12856 verificationInfo.installerUid); 12857 } 12858 } 12859 12860 final PackageVerificationState verificationState = new PackageVerificationState( 12861 requiredUid, args); 12862 12863 mPendingVerification.append(verificationId, verificationState); 12864 12865 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12866 receivers, verificationState); 12867 12868 /* 12869 * If any sufficient verifiers were listed in the package 12870 * manifest, attempt to ask them. 12871 */ 12872 if (sufficientVerifiers != null) { 12873 final int N = sufficientVerifiers.size(); 12874 if (N == 0) { 12875 Slog.i(TAG, "Additional verifiers required, but none installed."); 12876 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12877 } else { 12878 for (int i = 0; i < N; i++) { 12879 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12880 12881 final Intent sufficientIntent = new Intent(verification); 12882 sufficientIntent.setComponent(verifierComponent); 12883 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12884 } 12885 } 12886 } 12887 12888 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12889 mRequiredVerifierPackage, receivers); 12890 if (ret == PackageManager.INSTALL_SUCCEEDED 12891 && mRequiredVerifierPackage != null) { 12892 Trace.asyncTraceBegin( 12893 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12894 /* 12895 * Send the intent to the required verification agent, 12896 * but only start the verification timeout after the 12897 * target BroadcastReceivers have run. 12898 */ 12899 verification.setComponent(requiredVerifierComponent); 12900 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12901 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12902 new BroadcastReceiver() { 12903 @Override 12904 public void onReceive(Context context, Intent intent) { 12905 final Message msg = mHandler 12906 .obtainMessage(CHECK_PENDING_VERIFICATION); 12907 msg.arg1 = verificationId; 12908 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12909 } 12910 }, null, 0, null, null); 12911 12912 /* 12913 * We don't want the copy to proceed until verification 12914 * succeeds, so null out this field. 12915 */ 12916 mArgs = null; 12917 } 12918 } else { 12919 /* 12920 * No package verification is enabled, so immediately start 12921 * the remote call to initiate copy using temporary file. 12922 */ 12923 ret = args.copyApk(mContainerService, true); 12924 } 12925 } 12926 12927 mRet = ret; 12928 } 12929 12930 @Override 12931 void handleReturnCode() { 12932 // If mArgs is null, then MCS couldn't be reached. When it 12933 // reconnects, it will try again to install. At that point, this 12934 // will succeed. 12935 if (mArgs != null) { 12936 processPendingInstall(mArgs, mRet); 12937 } 12938 } 12939 12940 @Override 12941 void handleServiceError() { 12942 mArgs = createInstallArgs(this); 12943 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12944 } 12945 12946 public boolean isForwardLocked() { 12947 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12948 } 12949 } 12950 12951 /** 12952 * Used during creation of InstallArgs 12953 * 12954 * @param installFlags package installation flags 12955 * @return true if should be installed on external storage 12956 */ 12957 private static boolean installOnExternalAsec(int installFlags) { 12958 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12959 return false; 12960 } 12961 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12962 return true; 12963 } 12964 return false; 12965 } 12966 12967 /** 12968 * Used during creation of InstallArgs 12969 * 12970 * @param installFlags package installation flags 12971 * @return true if should be installed as forward locked 12972 */ 12973 private static boolean installForwardLocked(int installFlags) { 12974 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12975 } 12976 12977 private InstallArgs createInstallArgs(InstallParams params) { 12978 if (params.move != null) { 12979 return new MoveInstallArgs(params); 12980 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12981 return new AsecInstallArgs(params); 12982 } else { 12983 return new FileInstallArgs(params); 12984 } 12985 } 12986 12987 /** 12988 * Create args that describe an existing installed package. Typically used 12989 * when cleaning up old installs, or used as a move source. 12990 */ 12991 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12992 String resourcePath, String[] instructionSets) { 12993 final boolean isInAsec; 12994 if (installOnExternalAsec(installFlags)) { 12995 /* Apps on SD card are always in ASEC containers. */ 12996 isInAsec = true; 12997 } else if (installForwardLocked(installFlags) 12998 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12999 /* 13000 * Forward-locked apps are only in ASEC containers if they're the 13001 * new style 13002 */ 13003 isInAsec = true; 13004 } else { 13005 isInAsec = false; 13006 } 13007 13008 if (isInAsec) { 13009 return new AsecInstallArgs(codePath, instructionSets, 13010 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13011 } else { 13012 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13013 } 13014 } 13015 13016 static abstract class InstallArgs { 13017 /** @see InstallParams#origin */ 13018 final OriginInfo origin; 13019 /** @see InstallParams#move */ 13020 final MoveInfo move; 13021 13022 final IPackageInstallObserver2 observer; 13023 // Always refers to PackageManager flags only 13024 final int installFlags; 13025 final String installerPackageName; 13026 final String volumeUuid; 13027 final UserHandle user; 13028 final String abiOverride; 13029 final String[] installGrantPermissions; 13030 /** If non-null, drop an async trace when the install completes */ 13031 final String traceMethod; 13032 final int traceCookie; 13033 final Certificate[][] certificates; 13034 13035 // The list of instruction sets supported by this app. This is currently 13036 // only used during the rmdex() phase to clean up resources. We can get rid of this 13037 // if we move dex files under the common app path. 13038 /* nullable */ String[] instructionSets; 13039 13040 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13041 int installFlags, String installerPackageName, String volumeUuid, 13042 UserHandle user, String[] instructionSets, 13043 String abiOverride, String[] installGrantPermissions, 13044 String traceMethod, int traceCookie, Certificate[][] certificates) { 13045 this.origin = origin; 13046 this.move = move; 13047 this.installFlags = installFlags; 13048 this.observer = observer; 13049 this.installerPackageName = installerPackageName; 13050 this.volumeUuid = volumeUuid; 13051 this.user = user; 13052 this.instructionSets = instructionSets; 13053 this.abiOverride = abiOverride; 13054 this.installGrantPermissions = installGrantPermissions; 13055 this.traceMethod = traceMethod; 13056 this.traceCookie = traceCookie; 13057 this.certificates = certificates; 13058 } 13059 13060 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13061 abstract int doPreInstall(int status); 13062 13063 /** 13064 * Rename package into final resting place. All paths on the given 13065 * scanned package should be updated to reflect the rename. 13066 */ 13067 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13068 abstract int doPostInstall(int status, int uid); 13069 13070 /** @see PackageSettingBase#codePathString */ 13071 abstract String getCodePath(); 13072 /** @see PackageSettingBase#resourcePathString */ 13073 abstract String getResourcePath(); 13074 13075 // Need installer lock especially for dex file removal. 13076 abstract void cleanUpResourcesLI(); 13077 abstract boolean doPostDeleteLI(boolean delete); 13078 13079 /** 13080 * Called before the source arguments are copied. This is used mostly 13081 * for MoveParams when it needs to read the source file to put it in the 13082 * destination. 13083 */ 13084 int doPreCopy() { 13085 return PackageManager.INSTALL_SUCCEEDED; 13086 } 13087 13088 /** 13089 * Called after the source arguments are copied. This is used mostly for 13090 * MoveParams when it needs to read the source file to put it in the 13091 * destination. 13092 */ 13093 int doPostCopy(int uid) { 13094 return PackageManager.INSTALL_SUCCEEDED; 13095 } 13096 13097 protected boolean isFwdLocked() { 13098 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13099 } 13100 13101 protected boolean isExternalAsec() { 13102 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13103 } 13104 13105 protected boolean isEphemeral() { 13106 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13107 } 13108 13109 UserHandle getUser() { 13110 return user; 13111 } 13112 } 13113 13114 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13115 if (!allCodePaths.isEmpty()) { 13116 if (instructionSets == null) { 13117 throw new IllegalStateException("instructionSet == null"); 13118 } 13119 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13120 for (String codePath : allCodePaths) { 13121 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13122 try { 13123 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13124 } catch (InstallerException ignored) { 13125 } 13126 } 13127 } 13128 } 13129 } 13130 13131 /** 13132 * Logic to handle installation of non-ASEC applications, including copying 13133 * and renaming logic. 13134 */ 13135 class FileInstallArgs extends InstallArgs { 13136 private File codeFile; 13137 private File resourceFile; 13138 13139 // Example topology: 13140 // /data/app/com.example/base.apk 13141 // /data/app/com.example/split_foo.apk 13142 // /data/app/com.example/lib/arm/libfoo.so 13143 // /data/app/com.example/lib/arm64/libfoo.so 13144 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13145 13146 /** New install */ 13147 FileInstallArgs(InstallParams params) { 13148 super(params.origin, params.move, params.observer, params.installFlags, 13149 params.installerPackageName, params.volumeUuid, 13150 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13151 params.grantedRuntimePermissions, 13152 params.traceMethod, params.traceCookie, params.certificates); 13153 if (isFwdLocked()) { 13154 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13155 } 13156 } 13157 13158 /** Existing install */ 13159 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13160 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13161 null, null, null, 0, null /*certificates*/); 13162 this.codeFile = (codePath != null) ? new File(codePath) : null; 13163 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13164 } 13165 13166 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13168 try { 13169 return doCopyApk(imcs, temp); 13170 } finally { 13171 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13172 } 13173 } 13174 13175 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13176 if (origin.staged) { 13177 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13178 codeFile = origin.file; 13179 resourceFile = origin.file; 13180 return PackageManager.INSTALL_SUCCEEDED; 13181 } 13182 13183 try { 13184 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13185 final File tempDir = 13186 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13187 codeFile = tempDir; 13188 resourceFile = tempDir; 13189 } catch (IOException e) { 13190 Slog.w(TAG, "Failed to create copy file: " + e); 13191 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13192 } 13193 13194 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13195 @Override 13196 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13197 if (!FileUtils.isValidExtFilename(name)) { 13198 throw new IllegalArgumentException("Invalid filename: " + name); 13199 } 13200 try { 13201 final File file = new File(codeFile, name); 13202 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13203 O_RDWR | O_CREAT, 0644); 13204 Os.chmod(file.getAbsolutePath(), 0644); 13205 return new ParcelFileDescriptor(fd); 13206 } catch (ErrnoException e) { 13207 throw new RemoteException("Failed to open: " + e.getMessage()); 13208 } 13209 } 13210 }; 13211 13212 int ret = PackageManager.INSTALL_SUCCEEDED; 13213 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13214 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13215 Slog.e(TAG, "Failed to copy package"); 13216 return ret; 13217 } 13218 13219 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13220 NativeLibraryHelper.Handle handle = null; 13221 try { 13222 handle = NativeLibraryHelper.Handle.create(codeFile); 13223 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13224 abiOverride); 13225 } catch (IOException e) { 13226 Slog.e(TAG, "Copying native libraries failed", e); 13227 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13228 } finally { 13229 IoUtils.closeQuietly(handle); 13230 } 13231 13232 return ret; 13233 } 13234 13235 int doPreInstall(int status) { 13236 if (status != PackageManager.INSTALL_SUCCEEDED) { 13237 cleanUp(); 13238 } 13239 return status; 13240 } 13241 13242 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13243 if (status != PackageManager.INSTALL_SUCCEEDED) { 13244 cleanUp(); 13245 return false; 13246 } 13247 13248 final File targetDir = codeFile.getParentFile(); 13249 final File beforeCodeFile = codeFile; 13250 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13251 13252 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13253 try { 13254 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13255 } catch (ErrnoException e) { 13256 Slog.w(TAG, "Failed to rename", e); 13257 return false; 13258 } 13259 13260 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13261 Slog.w(TAG, "Failed to restorecon"); 13262 return false; 13263 } 13264 13265 // Reflect the rename internally 13266 codeFile = afterCodeFile; 13267 resourceFile = afterCodeFile; 13268 13269 // Reflect the rename in scanned details 13270 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13271 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13272 afterCodeFile, pkg.baseCodePath)); 13273 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13274 afterCodeFile, pkg.splitCodePaths)); 13275 13276 // Reflect the rename in app info 13277 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13278 pkg.setApplicationInfoCodePath(pkg.codePath); 13279 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13280 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13281 pkg.setApplicationInfoResourcePath(pkg.codePath); 13282 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13283 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13284 13285 return true; 13286 } 13287 13288 int doPostInstall(int status, int uid) { 13289 if (status != PackageManager.INSTALL_SUCCEEDED) { 13290 cleanUp(); 13291 } 13292 return status; 13293 } 13294 13295 @Override 13296 String getCodePath() { 13297 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13298 } 13299 13300 @Override 13301 String getResourcePath() { 13302 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13303 } 13304 13305 private boolean cleanUp() { 13306 if (codeFile == null || !codeFile.exists()) { 13307 return false; 13308 } 13309 13310 removeCodePathLI(codeFile); 13311 13312 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13313 resourceFile.delete(); 13314 } 13315 13316 return true; 13317 } 13318 13319 void cleanUpResourcesLI() { 13320 // Try enumerating all code paths before deleting 13321 List<String> allCodePaths = Collections.EMPTY_LIST; 13322 if (codeFile != null && codeFile.exists()) { 13323 try { 13324 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13325 allCodePaths = pkg.getAllCodePaths(); 13326 } catch (PackageParserException e) { 13327 // Ignored; we tried our best 13328 } 13329 } 13330 13331 cleanUp(); 13332 removeDexFiles(allCodePaths, instructionSets); 13333 } 13334 13335 boolean doPostDeleteLI(boolean delete) { 13336 // XXX err, shouldn't we respect the delete flag? 13337 cleanUpResourcesLI(); 13338 return true; 13339 } 13340 } 13341 13342 private boolean isAsecExternal(String cid) { 13343 final String asecPath = PackageHelper.getSdFilesystem(cid); 13344 return !asecPath.startsWith(mAsecInternalPath); 13345 } 13346 13347 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13348 PackageManagerException { 13349 if (copyRet < 0) { 13350 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13351 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13352 throw new PackageManagerException(copyRet, message); 13353 } 13354 } 13355 } 13356 13357 /** 13358 * Extract the MountService "container ID" from the full code path of an 13359 * .apk. 13360 */ 13361 static String cidFromCodePath(String fullCodePath) { 13362 int eidx = fullCodePath.lastIndexOf("/"); 13363 String subStr1 = fullCodePath.substring(0, eidx); 13364 int sidx = subStr1.lastIndexOf("/"); 13365 return subStr1.substring(sidx+1, eidx); 13366 } 13367 13368 /** 13369 * Logic to handle installation of ASEC applications, including copying and 13370 * renaming logic. 13371 */ 13372 class AsecInstallArgs extends InstallArgs { 13373 static final String RES_FILE_NAME = "pkg.apk"; 13374 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13375 13376 String cid; 13377 String packagePath; 13378 String resourcePath; 13379 13380 /** New install */ 13381 AsecInstallArgs(InstallParams params) { 13382 super(params.origin, params.move, params.observer, params.installFlags, 13383 params.installerPackageName, params.volumeUuid, 13384 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13385 params.grantedRuntimePermissions, 13386 params.traceMethod, params.traceCookie, params.certificates); 13387 } 13388 13389 /** Existing install */ 13390 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13391 boolean isExternal, boolean isForwardLocked) { 13392 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13393 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13394 instructionSets, null, null, null, 0, null /*certificates*/); 13395 // Hackily pretend we're still looking at a full code path 13396 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13397 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13398 } 13399 13400 // Extract cid from fullCodePath 13401 int eidx = fullCodePath.lastIndexOf("/"); 13402 String subStr1 = fullCodePath.substring(0, eidx); 13403 int sidx = subStr1.lastIndexOf("/"); 13404 cid = subStr1.substring(sidx+1, eidx); 13405 setMountPath(subStr1); 13406 } 13407 13408 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13409 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13410 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13411 instructionSets, null, null, null, 0, null /*certificates*/); 13412 this.cid = cid; 13413 setMountPath(PackageHelper.getSdDir(cid)); 13414 } 13415 13416 void createCopyFile() { 13417 cid = mInstallerService.allocateExternalStageCidLegacy(); 13418 } 13419 13420 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13421 if (origin.staged && origin.cid != null) { 13422 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13423 cid = origin.cid; 13424 setMountPath(PackageHelper.getSdDir(cid)); 13425 return PackageManager.INSTALL_SUCCEEDED; 13426 } 13427 13428 if (temp) { 13429 createCopyFile(); 13430 } else { 13431 /* 13432 * Pre-emptively destroy the container since it's destroyed if 13433 * copying fails due to it existing anyway. 13434 */ 13435 PackageHelper.destroySdDir(cid); 13436 } 13437 13438 final String newMountPath = imcs.copyPackageToContainer( 13439 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13440 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13441 13442 if (newMountPath != null) { 13443 setMountPath(newMountPath); 13444 return PackageManager.INSTALL_SUCCEEDED; 13445 } else { 13446 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13447 } 13448 } 13449 13450 @Override 13451 String getCodePath() { 13452 return packagePath; 13453 } 13454 13455 @Override 13456 String getResourcePath() { 13457 return resourcePath; 13458 } 13459 13460 int doPreInstall(int status) { 13461 if (status != PackageManager.INSTALL_SUCCEEDED) { 13462 // Destroy container 13463 PackageHelper.destroySdDir(cid); 13464 } else { 13465 boolean mounted = PackageHelper.isContainerMounted(cid); 13466 if (!mounted) { 13467 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13468 Process.SYSTEM_UID); 13469 if (newMountPath != null) { 13470 setMountPath(newMountPath); 13471 } else { 13472 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13473 } 13474 } 13475 } 13476 return status; 13477 } 13478 13479 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13480 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13481 String newMountPath = null; 13482 if (PackageHelper.isContainerMounted(cid)) { 13483 // Unmount the container 13484 if (!PackageHelper.unMountSdDir(cid)) { 13485 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13486 return false; 13487 } 13488 } 13489 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13490 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13491 " which might be stale. Will try to clean up."); 13492 // Clean up the stale container and proceed to recreate. 13493 if (!PackageHelper.destroySdDir(newCacheId)) { 13494 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13495 return false; 13496 } 13497 // Successfully cleaned up stale container. Try to rename again. 13498 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13499 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13500 + " inspite of cleaning it up."); 13501 return false; 13502 } 13503 } 13504 if (!PackageHelper.isContainerMounted(newCacheId)) { 13505 Slog.w(TAG, "Mounting container " + newCacheId); 13506 newMountPath = PackageHelper.mountSdDir(newCacheId, 13507 getEncryptKey(), Process.SYSTEM_UID); 13508 } else { 13509 newMountPath = PackageHelper.getSdDir(newCacheId); 13510 } 13511 if (newMountPath == null) { 13512 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13513 return false; 13514 } 13515 Log.i(TAG, "Succesfully renamed " + cid + 13516 " to " + newCacheId + 13517 " at new path: " + newMountPath); 13518 cid = newCacheId; 13519 13520 final File beforeCodeFile = new File(packagePath); 13521 setMountPath(newMountPath); 13522 final File afterCodeFile = new File(packagePath); 13523 13524 // Reflect the rename in scanned details 13525 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13526 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13527 afterCodeFile, pkg.baseCodePath)); 13528 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13529 afterCodeFile, pkg.splitCodePaths)); 13530 13531 // Reflect the rename in app info 13532 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13533 pkg.setApplicationInfoCodePath(pkg.codePath); 13534 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13535 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13536 pkg.setApplicationInfoResourcePath(pkg.codePath); 13537 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13538 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13539 13540 return true; 13541 } 13542 13543 private void setMountPath(String mountPath) { 13544 final File mountFile = new File(mountPath); 13545 13546 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13547 if (monolithicFile.exists()) { 13548 packagePath = monolithicFile.getAbsolutePath(); 13549 if (isFwdLocked()) { 13550 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13551 } else { 13552 resourcePath = packagePath; 13553 } 13554 } else { 13555 packagePath = mountFile.getAbsolutePath(); 13556 resourcePath = packagePath; 13557 } 13558 } 13559 13560 int doPostInstall(int status, int uid) { 13561 if (status != PackageManager.INSTALL_SUCCEEDED) { 13562 cleanUp(); 13563 } else { 13564 final int groupOwner; 13565 final String protectedFile; 13566 if (isFwdLocked()) { 13567 groupOwner = UserHandle.getSharedAppGid(uid); 13568 protectedFile = RES_FILE_NAME; 13569 } else { 13570 groupOwner = -1; 13571 protectedFile = null; 13572 } 13573 13574 if (uid < Process.FIRST_APPLICATION_UID 13575 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13576 Slog.e(TAG, "Failed to finalize " + cid); 13577 PackageHelper.destroySdDir(cid); 13578 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13579 } 13580 13581 boolean mounted = PackageHelper.isContainerMounted(cid); 13582 if (!mounted) { 13583 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13584 } 13585 } 13586 return status; 13587 } 13588 13589 private void cleanUp() { 13590 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13591 13592 // Destroy secure container 13593 PackageHelper.destroySdDir(cid); 13594 } 13595 13596 private List<String> getAllCodePaths() { 13597 final File codeFile = new File(getCodePath()); 13598 if (codeFile != null && codeFile.exists()) { 13599 try { 13600 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13601 return pkg.getAllCodePaths(); 13602 } catch (PackageParserException e) { 13603 // Ignored; we tried our best 13604 } 13605 } 13606 return Collections.EMPTY_LIST; 13607 } 13608 13609 void cleanUpResourcesLI() { 13610 // Enumerate all code paths before deleting 13611 cleanUpResourcesLI(getAllCodePaths()); 13612 } 13613 13614 private void cleanUpResourcesLI(List<String> allCodePaths) { 13615 cleanUp(); 13616 removeDexFiles(allCodePaths, instructionSets); 13617 } 13618 13619 String getPackageName() { 13620 return getAsecPackageName(cid); 13621 } 13622 13623 boolean doPostDeleteLI(boolean delete) { 13624 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13625 final List<String> allCodePaths = getAllCodePaths(); 13626 boolean mounted = PackageHelper.isContainerMounted(cid); 13627 if (mounted) { 13628 // Unmount first 13629 if (PackageHelper.unMountSdDir(cid)) { 13630 mounted = false; 13631 } 13632 } 13633 if (!mounted && delete) { 13634 cleanUpResourcesLI(allCodePaths); 13635 } 13636 return !mounted; 13637 } 13638 13639 @Override 13640 int doPreCopy() { 13641 if (isFwdLocked()) { 13642 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13643 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13644 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13645 } 13646 } 13647 13648 return PackageManager.INSTALL_SUCCEEDED; 13649 } 13650 13651 @Override 13652 int doPostCopy(int uid) { 13653 if (isFwdLocked()) { 13654 if (uid < Process.FIRST_APPLICATION_UID 13655 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13656 RES_FILE_NAME)) { 13657 Slog.e(TAG, "Failed to finalize " + cid); 13658 PackageHelper.destroySdDir(cid); 13659 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13660 } 13661 } 13662 13663 return PackageManager.INSTALL_SUCCEEDED; 13664 } 13665 } 13666 13667 /** 13668 * Logic to handle movement of existing installed applications. 13669 */ 13670 class MoveInstallArgs extends InstallArgs { 13671 private File codeFile; 13672 private File resourceFile; 13673 13674 /** New install */ 13675 MoveInstallArgs(InstallParams params) { 13676 super(params.origin, params.move, params.observer, params.installFlags, 13677 params.installerPackageName, params.volumeUuid, 13678 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13679 params.grantedRuntimePermissions, 13680 params.traceMethod, params.traceCookie, params.certificates); 13681 } 13682 13683 int copyApk(IMediaContainerService imcs, boolean temp) { 13684 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13685 + move.fromUuid + " to " + move.toUuid); 13686 synchronized (mInstaller) { 13687 try { 13688 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13689 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13690 } catch (InstallerException e) { 13691 Slog.w(TAG, "Failed to move app", e); 13692 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13693 } 13694 } 13695 13696 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13697 resourceFile = codeFile; 13698 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13699 13700 return PackageManager.INSTALL_SUCCEEDED; 13701 } 13702 13703 int doPreInstall(int status) { 13704 if (status != PackageManager.INSTALL_SUCCEEDED) { 13705 cleanUp(move.toUuid); 13706 } 13707 return status; 13708 } 13709 13710 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13711 if (status != PackageManager.INSTALL_SUCCEEDED) { 13712 cleanUp(move.toUuid); 13713 return false; 13714 } 13715 13716 // Reflect the move in app info 13717 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13718 pkg.setApplicationInfoCodePath(pkg.codePath); 13719 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13720 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13721 pkg.setApplicationInfoResourcePath(pkg.codePath); 13722 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13723 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13724 13725 return true; 13726 } 13727 13728 int doPostInstall(int status, int uid) { 13729 if (status == PackageManager.INSTALL_SUCCEEDED) { 13730 cleanUp(move.fromUuid); 13731 } else { 13732 cleanUp(move.toUuid); 13733 } 13734 return status; 13735 } 13736 13737 @Override 13738 String getCodePath() { 13739 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13740 } 13741 13742 @Override 13743 String getResourcePath() { 13744 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13745 } 13746 13747 private boolean cleanUp(String volumeUuid) { 13748 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13749 move.dataAppName); 13750 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13751 final int[] userIds = sUserManager.getUserIds(); 13752 synchronized (mInstallLock) { 13753 // Clean up both app data and code 13754 // All package moves are frozen until finished 13755 for (int userId : userIds) { 13756 try { 13757 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13758 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13759 } catch (InstallerException e) { 13760 Slog.w(TAG, String.valueOf(e)); 13761 } 13762 } 13763 removeCodePathLI(codeFile); 13764 } 13765 return true; 13766 } 13767 13768 void cleanUpResourcesLI() { 13769 throw new UnsupportedOperationException(); 13770 } 13771 13772 boolean doPostDeleteLI(boolean delete) { 13773 throw new UnsupportedOperationException(); 13774 } 13775 } 13776 13777 static String getAsecPackageName(String packageCid) { 13778 int idx = packageCid.lastIndexOf("-"); 13779 if (idx == -1) { 13780 return packageCid; 13781 } 13782 return packageCid.substring(0, idx); 13783 } 13784 13785 // Utility method used to create code paths based on package name and available index. 13786 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13787 String idxStr = ""; 13788 int idx = 1; 13789 // Fall back to default value of idx=1 if prefix is not 13790 // part of oldCodePath 13791 if (oldCodePath != null) { 13792 String subStr = oldCodePath; 13793 // Drop the suffix right away 13794 if (suffix != null && subStr.endsWith(suffix)) { 13795 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13796 } 13797 // If oldCodePath already contains prefix find out the 13798 // ending index to either increment or decrement. 13799 int sidx = subStr.lastIndexOf(prefix); 13800 if (sidx != -1) { 13801 subStr = subStr.substring(sidx + prefix.length()); 13802 if (subStr != null) { 13803 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13804 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13805 } 13806 try { 13807 idx = Integer.parseInt(subStr); 13808 if (idx <= 1) { 13809 idx++; 13810 } else { 13811 idx--; 13812 } 13813 } catch(NumberFormatException e) { 13814 } 13815 } 13816 } 13817 } 13818 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13819 return prefix + idxStr; 13820 } 13821 13822 private File getNextCodePath(File targetDir, String packageName) { 13823 int suffix = 1; 13824 File result; 13825 do { 13826 result = new File(targetDir, packageName + "-" + suffix); 13827 suffix++; 13828 } while (result.exists()); 13829 return result; 13830 } 13831 13832 // Utility method that returns the relative package path with respect 13833 // to the installation directory. Like say for /data/data/com.test-1.apk 13834 // string com.test-1 is returned. 13835 static String deriveCodePathName(String codePath) { 13836 if (codePath == null) { 13837 return null; 13838 } 13839 final File codeFile = new File(codePath); 13840 final String name = codeFile.getName(); 13841 if (codeFile.isDirectory()) { 13842 return name; 13843 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13844 final int lastDot = name.lastIndexOf('.'); 13845 return name.substring(0, lastDot); 13846 } else { 13847 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13848 return null; 13849 } 13850 } 13851 13852 static class PackageInstalledInfo { 13853 String name; 13854 int uid; 13855 // The set of users that originally had this package installed. 13856 int[] origUsers; 13857 // The set of users that now have this package installed. 13858 int[] newUsers; 13859 PackageParser.Package pkg; 13860 int returnCode; 13861 String returnMsg; 13862 PackageRemovedInfo removedInfo; 13863 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13864 13865 public void setError(int code, String msg) { 13866 setReturnCode(code); 13867 setReturnMessage(msg); 13868 Slog.w(TAG, msg); 13869 } 13870 13871 public void setError(String msg, PackageParserException e) { 13872 setReturnCode(e.error); 13873 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13874 Slog.w(TAG, msg, e); 13875 } 13876 13877 public void setError(String msg, PackageManagerException e) { 13878 returnCode = e.error; 13879 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13880 Slog.w(TAG, msg, e); 13881 } 13882 13883 public void setReturnCode(int returnCode) { 13884 this.returnCode = returnCode; 13885 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13886 for (int i = 0; i < childCount; i++) { 13887 addedChildPackages.valueAt(i).returnCode = returnCode; 13888 } 13889 } 13890 13891 private void setReturnMessage(String returnMsg) { 13892 this.returnMsg = returnMsg; 13893 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13894 for (int i = 0; i < childCount; i++) { 13895 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13896 } 13897 } 13898 13899 // In some error cases we want to convey more info back to the observer 13900 String origPackage; 13901 String origPermission; 13902 } 13903 13904 /* 13905 * Install a non-existing package. 13906 */ 13907 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13908 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13909 PackageInstalledInfo res) { 13910 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13911 13912 // Remember this for later, in case we need to rollback this install 13913 String pkgName = pkg.packageName; 13914 13915 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13916 13917 synchronized(mPackages) { 13918 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13919 // A package with the same name is already installed, though 13920 // it has been renamed to an older name. The package we 13921 // are trying to install should be installed as an update to 13922 // the existing one, but that has not been requested, so bail. 13923 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13924 + " without first uninstalling package running as " 13925 + mSettings.mRenamedPackages.get(pkgName)); 13926 return; 13927 } 13928 if (mPackages.containsKey(pkgName)) { 13929 // Don't allow installation over an existing package with the same name. 13930 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13931 + " without first uninstalling."); 13932 return; 13933 } 13934 } 13935 13936 try { 13937 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13938 System.currentTimeMillis(), user); 13939 13940 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13941 13942 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13943 prepareAppDataAfterInstallLIF(newPackage); 13944 13945 } else { 13946 // Remove package from internal structures, but keep around any 13947 // data that might have already existed 13948 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13949 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13950 } 13951 } catch (PackageManagerException e) { 13952 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13953 } 13954 13955 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13956 } 13957 13958 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13959 // Can't rotate keys during boot or if sharedUser. 13960 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13961 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13962 return false; 13963 } 13964 // app is using upgradeKeySets; make sure all are valid 13965 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13966 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13967 for (int i = 0; i < upgradeKeySets.length; i++) { 13968 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13969 Slog.wtf(TAG, "Package " 13970 + (oldPs.name != null ? oldPs.name : "<null>") 13971 + " contains upgrade-key-set reference to unknown key-set: " 13972 + upgradeKeySets[i] 13973 + " reverting to signatures check."); 13974 return false; 13975 } 13976 } 13977 return true; 13978 } 13979 13980 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13981 // Upgrade keysets are being used. Determine if new package has a superset of the 13982 // required keys. 13983 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13984 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13985 for (int i = 0; i < upgradeKeySets.length; i++) { 13986 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13987 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13988 return true; 13989 } 13990 } 13991 return false; 13992 } 13993 13994 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13995 try (DigestInputStream digestStream = 13996 new DigestInputStream(new FileInputStream(file), digest)) { 13997 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13998 } 13999 } 14000 14001 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14002 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14003 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14004 14005 final PackageParser.Package oldPackage; 14006 final String pkgName = pkg.packageName; 14007 final int[] allUsers; 14008 final int[] installedUsers; 14009 14010 synchronized(mPackages) { 14011 oldPackage = mPackages.get(pkgName); 14012 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14013 14014 // don't allow upgrade to target a release SDK from a pre-release SDK 14015 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14016 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14017 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14018 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14019 if (oldTargetsPreRelease 14020 && !newTargetsPreRelease 14021 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14022 Slog.w(TAG, "Can't install package targeting released sdk"); 14023 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14024 return; 14025 } 14026 14027 // don't allow an upgrade from full to ephemeral 14028 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14029 if (isEphemeral && !oldIsEphemeral) { 14030 // can't downgrade from full to ephemeral 14031 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14032 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14033 return; 14034 } 14035 14036 // verify signatures are valid 14037 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14038 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14039 if (!checkUpgradeKeySetLP(ps, pkg)) { 14040 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14041 "New package not signed by keys specified by upgrade-keysets: " 14042 + pkgName); 14043 return; 14044 } 14045 } else { 14046 // default to original signature matching 14047 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14048 != PackageManager.SIGNATURE_MATCH) { 14049 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14050 "New package has a different signature: " + pkgName); 14051 return; 14052 } 14053 } 14054 14055 // don't allow a system upgrade unless the upgrade hash matches 14056 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14057 byte[] digestBytes = null; 14058 try { 14059 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14060 updateDigest(digest, new File(pkg.baseCodePath)); 14061 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14062 for (String path : pkg.splitCodePaths) { 14063 updateDigest(digest, new File(path)); 14064 } 14065 } 14066 digestBytes = digest.digest(); 14067 } catch (NoSuchAlgorithmException | IOException e) { 14068 res.setError(INSTALL_FAILED_INVALID_APK, 14069 "Could not compute hash: " + pkgName); 14070 return; 14071 } 14072 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14073 res.setError(INSTALL_FAILED_INVALID_APK, 14074 "New package fails restrict-update check: " + pkgName); 14075 return; 14076 } 14077 // retain upgrade restriction 14078 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14079 } 14080 14081 // Check for shared user id changes 14082 String invalidPackageName = 14083 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14084 if (invalidPackageName != null) { 14085 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14086 "Package " + invalidPackageName + " tried to change user " 14087 + oldPackage.mSharedUserId); 14088 return; 14089 } 14090 14091 // In case of rollback, remember per-user/profile install state 14092 allUsers = sUserManager.getUserIds(); 14093 installedUsers = ps.queryInstalledUsers(allUsers, true); 14094 } 14095 14096 // Update what is removed 14097 res.removedInfo = new PackageRemovedInfo(); 14098 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14099 res.removedInfo.removedPackage = oldPackage.packageName; 14100 res.removedInfo.isUpdate = true; 14101 res.removedInfo.origUsers = installedUsers; 14102 final int childCount = (oldPackage.childPackages != null) 14103 ? oldPackage.childPackages.size() : 0; 14104 for (int i = 0; i < childCount; i++) { 14105 boolean childPackageUpdated = false; 14106 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14107 if (res.addedChildPackages != null) { 14108 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14109 if (childRes != null) { 14110 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14111 childRes.removedInfo.removedPackage = childPkg.packageName; 14112 childRes.removedInfo.isUpdate = true; 14113 childPackageUpdated = true; 14114 } 14115 } 14116 if (!childPackageUpdated) { 14117 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14118 childRemovedRes.removedPackage = childPkg.packageName; 14119 childRemovedRes.isUpdate = false; 14120 childRemovedRes.dataRemoved = true; 14121 synchronized (mPackages) { 14122 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14123 if (childPs != null) { 14124 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14125 } 14126 } 14127 if (res.removedInfo.removedChildPackages == null) { 14128 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14129 } 14130 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14131 } 14132 } 14133 14134 boolean sysPkg = (isSystemApp(oldPackage)); 14135 if (sysPkg) { 14136 // Set the system/privileged flags as needed 14137 final boolean privileged = 14138 (oldPackage.applicationInfo.privateFlags 14139 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14140 final int systemPolicyFlags = policyFlags 14141 | PackageParser.PARSE_IS_SYSTEM 14142 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14143 14144 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14145 user, allUsers, installerPackageName, res); 14146 } else { 14147 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14148 user, allUsers, installerPackageName, res); 14149 } 14150 } 14151 14152 public List<String> getPreviousCodePaths(String packageName) { 14153 final PackageSetting ps = mSettings.mPackages.get(packageName); 14154 final List<String> result = new ArrayList<String>(); 14155 if (ps != null && ps.oldCodePaths != null) { 14156 result.addAll(ps.oldCodePaths); 14157 } 14158 return result; 14159 } 14160 14161 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14162 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14163 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14164 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14165 + deletedPackage); 14166 14167 String pkgName = deletedPackage.packageName; 14168 boolean deletedPkg = true; 14169 boolean addedPkg = false; 14170 boolean updatedSettings = false; 14171 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14172 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14173 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14174 14175 final long origUpdateTime = (pkg.mExtras != null) 14176 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14177 14178 // First delete the existing package while retaining the data directory 14179 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14180 res.removedInfo, true, pkg)) { 14181 // If the existing package wasn't successfully deleted 14182 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14183 deletedPkg = false; 14184 } else { 14185 // Successfully deleted the old package; proceed with replace. 14186 14187 // If deleted package lived in a container, give users a chance to 14188 // relinquish resources before killing. 14189 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14190 if (DEBUG_INSTALL) { 14191 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14192 } 14193 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14194 final ArrayList<String> pkgList = new ArrayList<String>(1); 14195 pkgList.add(deletedPackage.applicationInfo.packageName); 14196 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14197 } 14198 14199 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14200 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14201 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14202 14203 try { 14204 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14205 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14206 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14207 14208 // Update the in-memory copy of the previous code paths. 14209 PackageSetting ps = mSettings.mPackages.get(pkgName); 14210 if (!killApp) { 14211 if (ps.oldCodePaths == null) { 14212 ps.oldCodePaths = new ArraySet<>(); 14213 } 14214 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14215 if (deletedPackage.splitCodePaths != null) { 14216 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14217 } 14218 } else { 14219 ps.oldCodePaths = null; 14220 } 14221 if (ps.childPackageNames != null) { 14222 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14223 final String childPkgName = ps.childPackageNames.get(i); 14224 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14225 childPs.oldCodePaths = ps.oldCodePaths; 14226 } 14227 } 14228 prepareAppDataAfterInstallLIF(newPackage); 14229 addedPkg = true; 14230 } catch (PackageManagerException e) { 14231 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14232 } 14233 } 14234 14235 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14236 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14237 14238 // Revert all internal state mutations and added folders for the failed install 14239 if (addedPkg) { 14240 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14241 res.removedInfo, true, null); 14242 } 14243 14244 // Restore the old package 14245 if (deletedPkg) { 14246 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14247 File restoreFile = new File(deletedPackage.codePath); 14248 // Parse old package 14249 boolean oldExternal = isExternal(deletedPackage); 14250 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14251 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14252 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14253 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14254 try { 14255 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14256 null); 14257 } catch (PackageManagerException e) { 14258 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14259 + e.getMessage()); 14260 return; 14261 } 14262 14263 synchronized (mPackages) { 14264 // Ensure the installer package name up to date 14265 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14266 14267 // Update permissions for restored package 14268 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14269 14270 mSettings.writeLPr(); 14271 } 14272 14273 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14274 } 14275 } else { 14276 synchronized (mPackages) { 14277 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14278 if (ps != null) { 14279 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14280 if (res.removedInfo.removedChildPackages != null) { 14281 final int childCount = res.removedInfo.removedChildPackages.size(); 14282 // Iterate in reverse as we may modify the collection 14283 for (int i = childCount - 1; i >= 0; i--) { 14284 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14285 if (res.addedChildPackages.containsKey(childPackageName)) { 14286 res.removedInfo.removedChildPackages.removeAt(i); 14287 } else { 14288 PackageRemovedInfo childInfo = res.removedInfo 14289 .removedChildPackages.valueAt(i); 14290 childInfo.removedForAllUsers = mPackages.get( 14291 childInfo.removedPackage) == null; 14292 } 14293 } 14294 } 14295 } 14296 } 14297 } 14298 } 14299 14300 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14301 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14302 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14303 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14304 + ", old=" + deletedPackage); 14305 14306 final boolean disabledSystem; 14307 14308 // Remove existing system package 14309 removePackageLI(deletedPackage, true); 14310 14311 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14312 if (!disabledSystem) { 14313 // We didn't need to disable the .apk as a current system package, 14314 // which means we are replacing another update that is already 14315 // installed. We need to make sure to delete the older one's .apk. 14316 res.removedInfo.args = createInstallArgsForExisting(0, 14317 deletedPackage.applicationInfo.getCodePath(), 14318 deletedPackage.applicationInfo.getResourcePath(), 14319 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14320 } else { 14321 res.removedInfo.args = null; 14322 } 14323 14324 // Successfully disabled the old package. Now proceed with re-installation 14325 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14326 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14327 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14328 14329 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14330 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14331 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14332 14333 PackageParser.Package newPackage = null; 14334 try { 14335 // Add the package to the internal data structures 14336 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14337 14338 // Set the update and install times 14339 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14340 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14341 System.currentTimeMillis()); 14342 14343 // Update the package dynamic state if succeeded 14344 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14345 // Now that the install succeeded make sure we remove data 14346 // directories for any child package the update removed. 14347 final int deletedChildCount = (deletedPackage.childPackages != null) 14348 ? deletedPackage.childPackages.size() : 0; 14349 final int newChildCount = (newPackage.childPackages != null) 14350 ? newPackage.childPackages.size() : 0; 14351 for (int i = 0; i < deletedChildCount; i++) { 14352 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14353 boolean childPackageDeleted = true; 14354 for (int j = 0; j < newChildCount; j++) { 14355 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14356 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14357 childPackageDeleted = false; 14358 break; 14359 } 14360 } 14361 if (childPackageDeleted) { 14362 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14363 deletedChildPkg.packageName); 14364 if (ps != null && res.removedInfo.removedChildPackages != null) { 14365 PackageRemovedInfo removedChildRes = res.removedInfo 14366 .removedChildPackages.get(deletedChildPkg.packageName); 14367 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14368 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14369 } 14370 } 14371 } 14372 14373 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14374 prepareAppDataAfterInstallLIF(newPackage); 14375 } 14376 } catch (PackageManagerException e) { 14377 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14378 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14379 } 14380 14381 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14382 // Re installation failed. Restore old information 14383 // Remove new pkg information 14384 if (newPackage != null) { 14385 removeInstalledPackageLI(newPackage, true); 14386 } 14387 // Add back the old system package 14388 try { 14389 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14390 } catch (PackageManagerException e) { 14391 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14392 } 14393 14394 synchronized (mPackages) { 14395 if (disabledSystem) { 14396 enableSystemPackageLPw(deletedPackage); 14397 } 14398 14399 // Ensure the installer package name up to date 14400 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14401 14402 // Update permissions for restored package 14403 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14404 14405 mSettings.writeLPr(); 14406 } 14407 14408 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14409 + " after failed upgrade"); 14410 } 14411 } 14412 14413 /** 14414 * Checks whether the parent or any of the child packages have a change shared 14415 * user. For a package to be a valid update the shred users of the parent and 14416 * the children should match. We may later support changing child shared users. 14417 * @param oldPkg The updated package. 14418 * @param newPkg The update package. 14419 * @return The shared user that change between the versions. 14420 */ 14421 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14422 PackageParser.Package newPkg) { 14423 // Check parent shared user 14424 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14425 return newPkg.packageName; 14426 } 14427 // Check child shared users 14428 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14429 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14430 for (int i = 0; i < newChildCount; i++) { 14431 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14432 // If this child was present, did it have the same shared user? 14433 for (int j = 0; j < oldChildCount; j++) { 14434 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14435 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14436 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14437 return newChildPkg.packageName; 14438 } 14439 } 14440 } 14441 return null; 14442 } 14443 14444 private void removeNativeBinariesLI(PackageSetting ps) { 14445 // Remove the lib path for the parent package 14446 if (ps != null) { 14447 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14448 // Remove the lib path for the child packages 14449 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14450 for (int i = 0; i < childCount; i++) { 14451 PackageSetting childPs = null; 14452 synchronized (mPackages) { 14453 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14454 } 14455 if (childPs != null) { 14456 NativeLibraryHelper.removeNativeBinariesLI(childPs 14457 .legacyNativeLibraryPathString); 14458 } 14459 } 14460 } 14461 } 14462 14463 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14464 // Enable the parent package 14465 mSettings.enableSystemPackageLPw(pkg.packageName); 14466 // Enable the child packages 14467 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14468 for (int i = 0; i < childCount; i++) { 14469 PackageParser.Package childPkg = pkg.childPackages.get(i); 14470 mSettings.enableSystemPackageLPw(childPkg.packageName); 14471 } 14472 } 14473 14474 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14475 PackageParser.Package newPkg) { 14476 // Disable the parent package (parent always replaced) 14477 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14478 // Disable the child packages 14479 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14480 for (int i = 0; i < childCount; i++) { 14481 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14482 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14483 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14484 } 14485 return disabled; 14486 } 14487 14488 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14489 String installerPackageName) { 14490 // Enable the parent package 14491 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14492 // Enable the child packages 14493 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14494 for (int i = 0; i < childCount; i++) { 14495 PackageParser.Package childPkg = pkg.childPackages.get(i); 14496 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14497 } 14498 } 14499 14500 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14501 // Collect all used permissions in the UID 14502 ArraySet<String> usedPermissions = new ArraySet<>(); 14503 final int packageCount = su.packages.size(); 14504 for (int i = 0; i < packageCount; i++) { 14505 PackageSetting ps = su.packages.valueAt(i); 14506 if (ps.pkg == null) { 14507 continue; 14508 } 14509 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14510 for (int j = 0; j < requestedPermCount; j++) { 14511 String permission = ps.pkg.requestedPermissions.get(j); 14512 BasePermission bp = mSettings.mPermissions.get(permission); 14513 if (bp != null) { 14514 usedPermissions.add(permission); 14515 } 14516 } 14517 } 14518 14519 PermissionsState permissionsState = su.getPermissionsState(); 14520 // Prune install permissions 14521 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14522 final int installPermCount = installPermStates.size(); 14523 for (int i = installPermCount - 1; i >= 0; i--) { 14524 PermissionState permissionState = installPermStates.get(i); 14525 if (!usedPermissions.contains(permissionState.getName())) { 14526 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14527 if (bp != null) { 14528 permissionsState.revokeInstallPermission(bp); 14529 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14530 PackageManager.MASK_PERMISSION_FLAGS, 0); 14531 } 14532 } 14533 } 14534 14535 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14536 14537 // Prune runtime permissions 14538 for (int userId : allUserIds) { 14539 List<PermissionState> runtimePermStates = permissionsState 14540 .getRuntimePermissionStates(userId); 14541 final int runtimePermCount = runtimePermStates.size(); 14542 for (int i = runtimePermCount - 1; i >= 0; i--) { 14543 PermissionState permissionState = runtimePermStates.get(i); 14544 if (!usedPermissions.contains(permissionState.getName())) { 14545 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14546 if (bp != null) { 14547 permissionsState.revokeRuntimePermission(bp, userId); 14548 permissionsState.updatePermissionFlags(bp, userId, 14549 PackageManager.MASK_PERMISSION_FLAGS, 0); 14550 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14551 runtimePermissionChangedUserIds, userId); 14552 } 14553 } 14554 } 14555 } 14556 14557 return runtimePermissionChangedUserIds; 14558 } 14559 14560 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14561 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14562 // Update the parent package setting 14563 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14564 res, user); 14565 // Update the child packages setting 14566 final int childCount = (newPackage.childPackages != null) 14567 ? newPackage.childPackages.size() : 0; 14568 for (int i = 0; i < childCount; i++) { 14569 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14570 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14571 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14572 childRes.origUsers, childRes, user); 14573 } 14574 } 14575 14576 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14577 String installerPackageName, int[] allUsers, int[] installedForUsers, 14578 PackageInstalledInfo res, UserHandle user) { 14579 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14580 14581 String pkgName = newPackage.packageName; 14582 synchronized (mPackages) { 14583 //write settings. the installStatus will be incomplete at this stage. 14584 //note that the new package setting would have already been 14585 //added to mPackages. It hasn't been persisted yet. 14586 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14588 mSettings.writeLPr(); 14589 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14590 } 14591 14592 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14593 synchronized (mPackages) { 14594 updatePermissionsLPw(newPackage.packageName, newPackage, 14595 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14596 ? UPDATE_PERMISSIONS_ALL : 0)); 14597 // For system-bundled packages, we assume that installing an upgraded version 14598 // of the package implies that the user actually wants to run that new code, 14599 // so we enable the package. 14600 PackageSetting ps = mSettings.mPackages.get(pkgName); 14601 final int userId = user.getIdentifier(); 14602 if (ps != null) { 14603 if (isSystemApp(newPackage)) { 14604 if (DEBUG_INSTALL) { 14605 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14606 } 14607 // Enable system package for requested users 14608 if (res.origUsers != null) { 14609 for (int origUserId : res.origUsers) { 14610 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14611 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14612 origUserId, installerPackageName); 14613 } 14614 } 14615 } 14616 // Also convey the prior install/uninstall state 14617 if (allUsers != null && installedForUsers != null) { 14618 for (int currentUserId : allUsers) { 14619 final boolean installed = ArrayUtils.contains( 14620 installedForUsers, currentUserId); 14621 if (DEBUG_INSTALL) { 14622 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14623 } 14624 ps.setInstalled(installed, currentUserId); 14625 } 14626 // these install state changes will be persisted in the 14627 // upcoming call to mSettings.writeLPr(). 14628 } 14629 } 14630 // It's implied that when a user requests installation, they want the app to be 14631 // installed and enabled. 14632 if (userId != UserHandle.USER_ALL) { 14633 ps.setInstalled(true, userId); 14634 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14635 } 14636 } 14637 res.name = pkgName; 14638 res.uid = newPackage.applicationInfo.uid; 14639 res.pkg = newPackage; 14640 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14641 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14642 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14643 //to update install status 14644 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14645 mSettings.writeLPr(); 14646 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14647 } 14648 14649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14650 } 14651 14652 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14653 try { 14654 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14655 installPackageLI(args, res); 14656 } finally { 14657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14658 } 14659 } 14660 14661 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14662 final int installFlags = args.installFlags; 14663 final String installerPackageName = args.installerPackageName; 14664 final String volumeUuid = args.volumeUuid; 14665 final File tmpPackageFile = new File(args.getCodePath()); 14666 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14667 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14668 || (args.volumeUuid != null)); 14669 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14670 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14671 boolean replace = false; 14672 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14673 if (args.move != null) { 14674 // moving a complete application; perform an initial scan on the new install location 14675 scanFlags |= SCAN_INITIAL; 14676 } 14677 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14678 scanFlags |= SCAN_DONT_KILL_APP; 14679 } 14680 14681 // Result object to be returned 14682 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14683 14684 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14685 14686 // Sanity check 14687 if (ephemeral && (forwardLocked || onExternal)) { 14688 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14689 + " external=" + onExternal); 14690 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14691 return; 14692 } 14693 14694 // Retrieve PackageSettings and parse package 14695 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14696 | PackageParser.PARSE_ENFORCE_CODE 14697 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14698 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14699 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14700 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14701 PackageParser pp = new PackageParser(); 14702 pp.setSeparateProcesses(mSeparateProcesses); 14703 pp.setDisplayMetrics(mMetrics); 14704 14705 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14706 final PackageParser.Package pkg; 14707 try { 14708 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14709 } catch (PackageParserException e) { 14710 res.setError("Failed parse during installPackageLI", e); 14711 return; 14712 } finally { 14713 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14714 } 14715 14716 // If we are installing a clustered package add results for the children 14717 if (pkg.childPackages != null) { 14718 synchronized (mPackages) { 14719 final int childCount = pkg.childPackages.size(); 14720 for (int i = 0; i < childCount; i++) { 14721 PackageParser.Package childPkg = pkg.childPackages.get(i); 14722 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14723 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14724 childRes.pkg = childPkg; 14725 childRes.name = childPkg.packageName; 14726 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14727 if (childPs != null) { 14728 childRes.origUsers = childPs.queryInstalledUsers( 14729 sUserManager.getUserIds(), true); 14730 } 14731 if ((mPackages.containsKey(childPkg.packageName))) { 14732 childRes.removedInfo = new PackageRemovedInfo(); 14733 childRes.removedInfo.removedPackage = childPkg.packageName; 14734 } 14735 if (res.addedChildPackages == null) { 14736 res.addedChildPackages = new ArrayMap<>(); 14737 } 14738 res.addedChildPackages.put(childPkg.packageName, childRes); 14739 } 14740 } 14741 } 14742 14743 // If package doesn't declare API override, mark that we have an install 14744 // time CPU ABI override. 14745 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14746 pkg.cpuAbiOverride = args.abiOverride; 14747 } 14748 14749 String pkgName = res.name = pkg.packageName; 14750 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14751 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14752 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14753 return; 14754 } 14755 } 14756 14757 try { 14758 // either use what we've been given or parse directly from the APK 14759 if (args.certificates != null) { 14760 try { 14761 PackageParser.populateCertificates(pkg, args.certificates); 14762 } catch (PackageParserException e) { 14763 // there was something wrong with the certificates we were given; 14764 // try to pull them from the APK 14765 PackageParser.collectCertificates(pkg, parseFlags); 14766 } 14767 } else { 14768 PackageParser.collectCertificates(pkg, parseFlags); 14769 } 14770 } catch (PackageParserException e) { 14771 res.setError("Failed collect during installPackageLI", e); 14772 return; 14773 } 14774 14775 // Get rid of all references to package scan path via parser. 14776 pp = null; 14777 String oldCodePath = null; 14778 boolean systemApp = false; 14779 synchronized (mPackages) { 14780 // Check if installing already existing package 14781 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14782 String oldName = mSettings.mRenamedPackages.get(pkgName); 14783 if (pkg.mOriginalPackages != null 14784 && pkg.mOriginalPackages.contains(oldName) 14785 && mPackages.containsKey(oldName)) { 14786 // This package is derived from an original package, 14787 // and this device has been updating from that original 14788 // name. We must continue using the original name, so 14789 // rename the new package here. 14790 pkg.setPackageName(oldName); 14791 pkgName = pkg.packageName; 14792 replace = true; 14793 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14794 + oldName + " pkgName=" + pkgName); 14795 } else if (mPackages.containsKey(pkgName)) { 14796 // This package, under its official name, already exists 14797 // on the device; we should replace it. 14798 replace = true; 14799 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14800 } 14801 14802 // Child packages are installed through the parent package 14803 if (pkg.parentPackage != null) { 14804 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14805 "Package " + pkg.packageName + " is child of package " 14806 + pkg.parentPackage.parentPackage + ". Child packages " 14807 + "can be updated only through the parent package."); 14808 return; 14809 } 14810 14811 if (replace) { 14812 // Prevent apps opting out from runtime permissions 14813 PackageParser.Package oldPackage = mPackages.get(pkgName); 14814 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14815 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14816 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14817 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14818 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14819 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14820 + " doesn't support runtime permissions but the old" 14821 + " target SDK " + oldTargetSdk + " does."); 14822 return; 14823 } 14824 14825 // Prevent installing of child packages 14826 if (oldPackage.parentPackage != null) { 14827 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14828 "Package " + pkg.packageName + " is child of package " 14829 + oldPackage.parentPackage + ". Child packages " 14830 + "can be updated only through the parent package."); 14831 return; 14832 } 14833 } 14834 } 14835 14836 PackageSetting ps = mSettings.mPackages.get(pkgName); 14837 if (ps != null) { 14838 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14839 14840 // Quick sanity check that we're signed correctly if updating; 14841 // we'll check this again later when scanning, but we want to 14842 // bail early here before tripping over redefined permissions. 14843 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14844 if (!checkUpgradeKeySetLP(ps, pkg)) { 14845 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14846 + pkg.packageName + " upgrade keys do not match the " 14847 + "previously installed version"); 14848 return; 14849 } 14850 } else { 14851 try { 14852 verifySignaturesLP(ps, pkg); 14853 } catch (PackageManagerException e) { 14854 res.setError(e.error, e.getMessage()); 14855 return; 14856 } 14857 } 14858 14859 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14860 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14861 systemApp = (ps.pkg.applicationInfo.flags & 14862 ApplicationInfo.FLAG_SYSTEM) != 0; 14863 } 14864 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14865 } 14866 14867 // Check whether the newly-scanned package wants to define an already-defined perm 14868 int N = pkg.permissions.size(); 14869 for (int i = N-1; i >= 0; i--) { 14870 PackageParser.Permission perm = pkg.permissions.get(i); 14871 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14872 if (bp != null) { 14873 // If the defining package is signed with our cert, it's okay. This 14874 // also includes the "updating the same package" case, of course. 14875 // "updating same package" could also involve key-rotation. 14876 final boolean sigsOk; 14877 if (bp.sourcePackage.equals(pkg.packageName) 14878 && (bp.packageSetting instanceof PackageSetting) 14879 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14880 scanFlags))) { 14881 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14882 } else { 14883 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14884 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14885 } 14886 if (!sigsOk) { 14887 // If the owning package is the system itself, we log but allow 14888 // install to proceed; we fail the install on all other permission 14889 // redefinitions. 14890 if (!bp.sourcePackage.equals("android")) { 14891 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14892 + pkg.packageName + " attempting to redeclare permission " 14893 + perm.info.name + " already owned by " + bp.sourcePackage); 14894 res.origPermission = perm.info.name; 14895 res.origPackage = bp.sourcePackage; 14896 return; 14897 } else { 14898 Slog.w(TAG, "Package " + pkg.packageName 14899 + " attempting to redeclare system permission " 14900 + perm.info.name + "; ignoring new declaration"); 14901 pkg.permissions.remove(i); 14902 } 14903 } 14904 } 14905 } 14906 } 14907 14908 if (systemApp) { 14909 if (onExternal) { 14910 // Abort update; system app can't be replaced with app on sdcard 14911 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14912 "Cannot install updates to system apps on sdcard"); 14913 return; 14914 } else if (ephemeral) { 14915 // Abort update; system app can't be replaced with an ephemeral app 14916 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14917 "Cannot update a system app with an ephemeral app"); 14918 return; 14919 } 14920 } 14921 14922 if (args.move != null) { 14923 // We did an in-place move, so dex is ready to roll 14924 scanFlags |= SCAN_NO_DEX; 14925 scanFlags |= SCAN_MOVE; 14926 14927 synchronized (mPackages) { 14928 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14929 if (ps == null) { 14930 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14931 "Missing settings for moved package " + pkgName); 14932 } 14933 14934 // We moved the entire application as-is, so bring over the 14935 // previously derived ABI information. 14936 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14937 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14938 } 14939 14940 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14941 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14942 scanFlags |= SCAN_NO_DEX; 14943 14944 try { 14945 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14946 args.abiOverride : pkg.cpuAbiOverride); 14947 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14948 true /* extract libs */); 14949 } catch (PackageManagerException pme) { 14950 Slog.e(TAG, "Error deriving application ABI", pme); 14951 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14952 return; 14953 } 14954 14955 // Shared libraries for the package need to be updated. 14956 synchronized (mPackages) { 14957 try { 14958 updateSharedLibrariesLPw(pkg, null); 14959 } catch (PackageManagerException e) { 14960 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14961 } 14962 } 14963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14964 // Do not run PackageDexOptimizer through the local performDexOpt 14965 // method because `pkg` is not in `mPackages` yet. 14966 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14967 null /* instructionSets */, false /* checkProfiles */, 14968 getCompilerFilterForReason(REASON_INSTALL)); 14969 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14970 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14971 String msg = "Extracting package failed for " + pkgName; 14972 res.setError(INSTALL_FAILED_DEXOPT, msg); 14973 return; 14974 } 14975 14976 // Notify BackgroundDexOptService that the package has been changed. 14977 // If this is an update of a package which used to fail to compile, 14978 // BDOS will remove it from its blacklist. 14979 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14980 } 14981 14982 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14983 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14984 return; 14985 } 14986 14987 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14988 14989 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14990 "installPackageLI")) { 14991 if (replace) { 14992 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14993 installerPackageName, res); 14994 } else { 14995 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14996 args.user, installerPackageName, volumeUuid, res); 14997 } 14998 } 14999 synchronized (mPackages) { 15000 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15001 if (ps != null) { 15002 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15003 } 15004 15005 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15006 for (int i = 0; i < childCount; i++) { 15007 PackageParser.Package childPkg = pkg.childPackages.get(i); 15008 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15009 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15010 if (childPs != null) { 15011 childRes.newUsers = childPs.queryInstalledUsers( 15012 sUserManager.getUserIds(), true); 15013 } 15014 } 15015 } 15016 } 15017 15018 private void startIntentFilterVerifications(int userId, boolean replacing, 15019 PackageParser.Package pkg) { 15020 if (mIntentFilterVerifierComponent == null) { 15021 Slog.w(TAG, "No IntentFilter verification will not be done as " 15022 + "there is no IntentFilterVerifier available!"); 15023 return; 15024 } 15025 15026 final int verifierUid = getPackageUid( 15027 mIntentFilterVerifierComponent.getPackageName(), 15028 MATCH_DEBUG_TRIAGED_MISSING, 15029 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15030 15031 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15032 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15033 mHandler.sendMessage(msg); 15034 15035 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15036 for (int i = 0; i < childCount; i++) { 15037 PackageParser.Package childPkg = pkg.childPackages.get(i); 15038 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15039 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15040 mHandler.sendMessage(msg); 15041 } 15042 } 15043 15044 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15045 PackageParser.Package pkg) { 15046 int size = pkg.activities.size(); 15047 if (size == 0) { 15048 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15049 "No activity, so no need to verify any IntentFilter!"); 15050 return; 15051 } 15052 15053 final boolean hasDomainURLs = hasDomainURLs(pkg); 15054 if (!hasDomainURLs) { 15055 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15056 "No domain URLs, so no need to verify any IntentFilter!"); 15057 return; 15058 } 15059 15060 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15061 + " if any IntentFilter from the " + size 15062 + " Activities needs verification ..."); 15063 15064 int count = 0; 15065 final String packageName = pkg.packageName; 15066 15067 synchronized (mPackages) { 15068 // If this is a new install and we see that we've already run verification for this 15069 // package, we have nothing to do: it means the state was restored from backup. 15070 if (!replacing) { 15071 IntentFilterVerificationInfo ivi = 15072 mSettings.getIntentFilterVerificationLPr(packageName); 15073 if (ivi != null) { 15074 if (DEBUG_DOMAIN_VERIFICATION) { 15075 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15076 + ivi.getStatusString()); 15077 } 15078 return; 15079 } 15080 } 15081 15082 // If any filters need to be verified, then all need to be. 15083 boolean needToVerify = false; 15084 for (PackageParser.Activity a : pkg.activities) { 15085 for (ActivityIntentInfo filter : a.intents) { 15086 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15087 if (DEBUG_DOMAIN_VERIFICATION) { 15088 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15089 } 15090 needToVerify = true; 15091 break; 15092 } 15093 } 15094 } 15095 15096 if (needToVerify) { 15097 final int verificationId = mIntentFilterVerificationToken++; 15098 for (PackageParser.Activity a : pkg.activities) { 15099 for (ActivityIntentInfo filter : a.intents) { 15100 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15101 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15102 "Verification needed for IntentFilter:" + filter.toString()); 15103 mIntentFilterVerifier.addOneIntentFilterVerification( 15104 verifierUid, userId, verificationId, filter, packageName); 15105 count++; 15106 } 15107 } 15108 } 15109 } 15110 } 15111 15112 if (count > 0) { 15113 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15114 + " IntentFilter verification" + (count > 1 ? "s" : "") 15115 + " for userId:" + userId); 15116 mIntentFilterVerifier.startVerifications(userId); 15117 } else { 15118 if (DEBUG_DOMAIN_VERIFICATION) { 15119 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15120 } 15121 } 15122 } 15123 15124 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15125 final ComponentName cn = filter.activity.getComponentName(); 15126 final String packageName = cn.getPackageName(); 15127 15128 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15129 packageName); 15130 if (ivi == null) { 15131 return true; 15132 } 15133 int status = ivi.getStatus(); 15134 switch (status) { 15135 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15136 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15137 return true; 15138 15139 default: 15140 // Nothing to do 15141 return false; 15142 } 15143 } 15144 15145 private static boolean isMultiArch(ApplicationInfo info) { 15146 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15147 } 15148 15149 private static boolean isExternal(PackageParser.Package pkg) { 15150 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15151 } 15152 15153 private static boolean isExternal(PackageSetting ps) { 15154 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15155 } 15156 15157 private static boolean isEphemeral(PackageParser.Package pkg) { 15158 return pkg.applicationInfo.isEphemeralApp(); 15159 } 15160 15161 private static boolean isEphemeral(PackageSetting ps) { 15162 return ps.pkg != null && isEphemeral(ps.pkg); 15163 } 15164 15165 private static boolean isSystemApp(PackageParser.Package pkg) { 15166 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15167 } 15168 15169 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15170 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15171 } 15172 15173 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15174 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15175 } 15176 15177 private static boolean isSystemApp(PackageSetting ps) { 15178 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15179 } 15180 15181 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15182 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15183 } 15184 15185 private int packageFlagsToInstallFlags(PackageSetting ps) { 15186 int installFlags = 0; 15187 if (isEphemeral(ps)) { 15188 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15189 } 15190 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15191 // This existing package was an external ASEC install when we have 15192 // the external flag without a UUID 15193 installFlags |= PackageManager.INSTALL_EXTERNAL; 15194 } 15195 if (ps.isForwardLocked()) { 15196 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15197 } 15198 return installFlags; 15199 } 15200 15201 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15202 if (isExternal(pkg)) { 15203 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15204 return StorageManager.UUID_PRIMARY_PHYSICAL; 15205 } else { 15206 return pkg.volumeUuid; 15207 } 15208 } else { 15209 return StorageManager.UUID_PRIVATE_INTERNAL; 15210 } 15211 } 15212 15213 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15214 if (isExternal(pkg)) { 15215 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15216 return mSettings.getExternalVersion(); 15217 } else { 15218 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15219 } 15220 } else { 15221 return mSettings.getInternalVersion(); 15222 } 15223 } 15224 15225 private void deleteTempPackageFiles() { 15226 final FilenameFilter filter = new FilenameFilter() { 15227 public boolean accept(File dir, String name) { 15228 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15229 } 15230 }; 15231 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15232 file.delete(); 15233 } 15234 } 15235 15236 @Override 15237 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15238 int flags) { 15239 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15240 flags); 15241 } 15242 15243 @Override 15244 public void deletePackage(final String packageName, 15245 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15246 mContext.enforceCallingOrSelfPermission( 15247 android.Manifest.permission.DELETE_PACKAGES, null); 15248 Preconditions.checkNotNull(packageName); 15249 Preconditions.checkNotNull(observer); 15250 final int uid = Binder.getCallingUid(); 15251 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15252 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15253 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15254 mContext.enforceCallingOrSelfPermission( 15255 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15256 "deletePackage for user " + userId); 15257 } 15258 15259 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15260 try { 15261 observer.onPackageDeleted(packageName, 15262 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15263 } catch (RemoteException re) { 15264 } 15265 return; 15266 } 15267 15268 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15269 try { 15270 observer.onPackageDeleted(packageName, 15271 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15272 } catch (RemoteException re) { 15273 } 15274 return; 15275 } 15276 15277 if (DEBUG_REMOVE) { 15278 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15279 + " deleteAllUsers: " + deleteAllUsers ); 15280 } 15281 // Queue up an async operation since the package deletion may take a little while. 15282 mHandler.post(new Runnable() { 15283 public void run() { 15284 mHandler.removeCallbacks(this); 15285 int returnCode; 15286 if (!deleteAllUsers) { 15287 returnCode = deletePackageX(packageName, userId, deleteFlags); 15288 } else { 15289 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15290 // If nobody is blocking uninstall, proceed with delete for all users 15291 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15292 returnCode = deletePackageX(packageName, userId, deleteFlags); 15293 } else { 15294 // Otherwise uninstall individually for users with blockUninstalls=false 15295 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15296 for (int userId : users) { 15297 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15298 returnCode = deletePackageX(packageName, userId, userFlags); 15299 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15300 Slog.w(TAG, "Package delete failed for user " + userId 15301 + ", returnCode " + returnCode); 15302 } 15303 } 15304 } 15305 // The app has only been marked uninstalled for certain users. 15306 // We still need to report that delete was blocked 15307 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15308 } 15309 } 15310 try { 15311 observer.onPackageDeleted(packageName, returnCode, null); 15312 } catch (RemoteException e) { 15313 Log.i(TAG, "Observer no longer exists."); 15314 } //end catch 15315 } //end run 15316 }); 15317 } 15318 15319 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15320 int[] result = EMPTY_INT_ARRAY; 15321 for (int userId : userIds) { 15322 if (getBlockUninstallForUser(packageName, userId)) { 15323 result = ArrayUtils.appendInt(result, userId); 15324 } 15325 } 15326 return result; 15327 } 15328 15329 @Override 15330 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15331 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15332 } 15333 15334 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15335 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15336 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15337 try { 15338 if (dpm != null) { 15339 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15340 /* callingUserOnly =*/ false); 15341 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15342 : deviceOwnerComponentName.getPackageName(); 15343 // Does the package contains the device owner? 15344 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15345 // this check is probably not needed, since DO should be registered as a device 15346 // admin on some user too. (Original bug for this: b/17657954) 15347 if (packageName.equals(deviceOwnerPackageName)) { 15348 return true; 15349 } 15350 // Does it contain a device admin for any user? 15351 int[] users; 15352 if (userId == UserHandle.USER_ALL) { 15353 users = sUserManager.getUserIds(); 15354 } else { 15355 users = new int[]{userId}; 15356 } 15357 for (int i = 0; i < users.length; ++i) { 15358 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15359 return true; 15360 } 15361 } 15362 } 15363 } catch (RemoteException e) { 15364 } 15365 return false; 15366 } 15367 15368 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15369 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15370 } 15371 15372 /** 15373 * This method is an internal method that could be get invoked either 15374 * to delete an installed package or to clean up a failed installation. 15375 * After deleting an installed package, a broadcast is sent to notify any 15376 * listeners that the package has been removed. For cleaning up a failed 15377 * installation, the broadcast is not necessary since the package's 15378 * installation wouldn't have sent the initial broadcast either 15379 * The key steps in deleting a package are 15380 * deleting the package information in internal structures like mPackages, 15381 * deleting the packages base directories through installd 15382 * updating mSettings to reflect current status 15383 * persisting settings for later use 15384 * sending a broadcast if necessary 15385 */ 15386 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15387 final PackageRemovedInfo info = new PackageRemovedInfo(); 15388 final boolean res; 15389 15390 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15391 ? UserHandle.ALL : new UserHandle(userId); 15392 15393 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15394 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15395 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15396 } 15397 15398 PackageSetting uninstalledPs = null; 15399 15400 // for the uninstall-updates case and restricted profiles, remember the per- 15401 // user handle installed state 15402 int[] allUsers; 15403 synchronized (mPackages) { 15404 uninstalledPs = mSettings.mPackages.get(packageName); 15405 if (uninstalledPs == null) { 15406 Slog.w(TAG, "Not removing non-existent package " + packageName); 15407 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15408 } 15409 allUsers = sUserManager.getUserIds(); 15410 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15411 } 15412 15413 synchronized (mInstallLock) { 15414 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15415 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15416 "deletePackageX")) { 15417 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15418 deleteFlags | REMOVE_CHATTY, info, true, null); 15419 } 15420 synchronized (mPackages) { 15421 if (res) { 15422 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15423 } 15424 } 15425 } 15426 15427 if (res) { 15428 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15429 info.sendPackageRemovedBroadcasts(killApp); 15430 info.sendSystemPackageUpdatedBroadcasts(); 15431 info.sendSystemPackageAppearedBroadcasts(); 15432 } 15433 // Force a gc here. 15434 Runtime.getRuntime().gc(); 15435 // Delete the resources here after sending the broadcast to let 15436 // other processes clean up before deleting resources. 15437 if (info.args != null) { 15438 synchronized (mInstallLock) { 15439 info.args.doPostDeleteLI(true); 15440 } 15441 } 15442 15443 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15444 } 15445 15446 class PackageRemovedInfo { 15447 String removedPackage; 15448 int uid = -1; 15449 int removedAppId = -1; 15450 int[] origUsers; 15451 int[] removedUsers = null; 15452 boolean isRemovedPackageSystemUpdate = false; 15453 boolean isUpdate; 15454 boolean dataRemoved; 15455 boolean removedForAllUsers; 15456 // Clean up resources deleted packages. 15457 InstallArgs args = null; 15458 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15459 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15460 15461 void sendPackageRemovedBroadcasts(boolean killApp) { 15462 sendPackageRemovedBroadcastInternal(killApp); 15463 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15464 for (int i = 0; i < childCount; i++) { 15465 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15466 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15467 } 15468 } 15469 15470 void sendSystemPackageUpdatedBroadcasts() { 15471 if (isRemovedPackageSystemUpdate) { 15472 sendSystemPackageUpdatedBroadcastsInternal(); 15473 final int childCount = (removedChildPackages != null) 15474 ? removedChildPackages.size() : 0; 15475 for (int i = 0; i < childCount; i++) { 15476 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15477 if (childInfo.isRemovedPackageSystemUpdate) { 15478 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15479 } 15480 } 15481 } 15482 } 15483 15484 void sendSystemPackageAppearedBroadcasts() { 15485 final int packageCount = (appearedChildPackages != null) 15486 ? appearedChildPackages.size() : 0; 15487 for (int i = 0; i < packageCount; i++) { 15488 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15489 for (int userId : installedInfo.newUsers) { 15490 sendPackageAddedForUser(installedInfo.name, true, 15491 UserHandle.getAppId(installedInfo.uid), userId); 15492 } 15493 } 15494 } 15495 15496 private void sendSystemPackageUpdatedBroadcastsInternal() { 15497 Bundle extras = new Bundle(2); 15498 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15499 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15500 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15501 extras, 0, null, null, null); 15502 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15503 extras, 0, null, null, null); 15504 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15505 null, 0, removedPackage, null, null); 15506 } 15507 15508 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15509 Bundle extras = new Bundle(2); 15510 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15511 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15512 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15513 if (isUpdate || isRemovedPackageSystemUpdate) { 15514 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15515 } 15516 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15517 if (removedPackage != null) { 15518 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15519 extras, 0, null, null, removedUsers); 15520 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15521 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15522 removedPackage, extras, 0, null, null, removedUsers); 15523 } 15524 } 15525 if (removedAppId >= 0) { 15526 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15527 removedUsers); 15528 } 15529 } 15530 } 15531 15532 /* 15533 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15534 * flag is not set, the data directory is removed as well. 15535 * make sure this flag is set for partially installed apps. If not its meaningless to 15536 * delete a partially installed application. 15537 */ 15538 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15539 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15540 String packageName = ps.name; 15541 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15542 // Retrieve object to delete permissions for shared user later on 15543 final PackageParser.Package deletedPkg; 15544 final PackageSetting deletedPs; 15545 // reader 15546 synchronized (mPackages) { 15547 deletedPkg = mPackages.get(packageName); 15548 deletedPs = mSettings.mPackages.get(packageName); 15549 if (outInfo != null) { 15550 outInfo.removedPackage = packageName; 15551 outInfo.removedUsers = deletedPs != null 15552 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15553 : null; 15554 } 15555 } 15556 15557 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15558 15559 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15560 final PackageParser.Package resolvedPkg; 15561 if (deletedPkg != null) { 15562 resolvedPkg = deletedPkg; 15563 } else { 15564 // We don't have a parsed package when it lives on an ejected 15565 // adopted storage device, so fake something together 15566 resolvedPkg = new PackageParser.Package(ps.name); 15567 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15568 } 15569 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15570 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15571 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15572 if (outInfo != null) { 15573 outInfo.dataRemoved = true; 15574 } 15575 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15576 } 15577 15578 // writer 15579 synchronized (mPackages) { 15580 if (deletedPs != null) { 15581 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15582 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15583 clearDefaultBrowserIfNeeded(packageName); 15584 if (outInfo != null) { 15585 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15586 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15587 } 15588 updatePermissionsLPw(deletedPs.name, null, 0); 15589 if (deletedPs.sharedUser != null) { 15590 // Remove permissions associated with package. Since runtime 15591 // permissions are per user we have to kill the removed package 15592 // or packages running under the shared user of the removed 15593 // package if revoking the permissions requested only by the removed 15594 // package is successful and this causes a change in gids. 15595 for (int userId : UserManagerService.getInstance().getUserIds()) { 15596 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15597 userId); 15598 if (userIdToKill == UserHandle.USER_ALL 15599 || userIdToKill >= UserHandle.USER_SYSTEM) { 15600 // If gids changed for this user, kill all affected packages. 15601 mHandler.post(new Runnable() { 15602 @Override 15603 public void run() { 15604 // This has to happen with no lock held. 15605 killApplication(deletedPs.name, deletedPs.appId, 15606 KILL_APP_REASON_GIDS_CHANGED); 15607 } 15608 }); 15609 break; 15610 } 15611 } 15612 } 15613 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15614 } 15615 // make sure to preserve per-user disabled state if this removal was just 15616 // a downgrade of a system app to the factory package 15617 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15618 if (DEBUG_REMOVE) { 15619 Slog.d(TAG, "Propagating install state across downgrade"); 15620 } 15621 for (int userId : allUserHandles) { 15622 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15623 if (DEBUG_REMOVE) { 15624 Slog.d(TAG, " user " + userId + " => " + installed); 15625 } 15626 ps.setInstalled(installed, userId); 15627 } 15628 } 15629 } 15630 // can downgrade to reader 15631 if (writeSettings) { 15632 // Save settings now 15633 mSettings.writeLPr(); 15634 } 15635 } 15636 if (outInfo != null) { 15637 // A user ID was deleted here. Go through all users and remove it 15638 // from KeyStore. 15639 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15640 } 15641 } 15642 15643 static boolean locationIsPrivileged(File path) { 15644 try { 15645 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15646 .getCanonicalPath(); 15647 return path.getCanonicalPath().startsWith(privilegedAppDir); 15648 } catch (IOException e) { 15649 Slog.e(TAG, "Unable to access code path " + path); 15650 } 15651 return false; 15652 } 15653 15654 /* 15655 * Tries to delete system package. 15656 */ 15657 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15658 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15659 boolean writeSettings) { 15660 if (deletedPs.parentPackageName != null) { 15661 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15662 return false; 15663 } 15664 15665 final boolean applyUserRestrictions 15666 = (allUserHandles != null) && (outInfo.origUsers != null); 15667 final PackageSetting disabledPs; 15668 // Confirm if the system package has been updated 15669 // An updated system app can be deleted. This will also have to restore 15670 // the system pkg from system partition 15671 // reader 15672 synchronized (mPackages) { 15673 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15674 } 15675 15676 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15677 + " disabledPs=" + disabledPs); 15678 15679 if (disabledPs == null) { 15680 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15681 return false; 15682 } else if (DEBUG_REMOVE) { 15683 Slog.d(TAG, "Deleting system pkg from data partition"); 15684 } 15685 15686 if (DEBUG_REMOVE) { 15687 if (applyUserRestrictions) { 15688 Slog.d(TAG, "Remembering install states:"); 15689 for (int userId : allUserHandles) { 15690 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15691 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15692 } 15693 } 15694 } 15695 15696 // Delete the updated package 15697 outInfo.isRemovedPackageSystemUpdate = true; 15698 if (outInfo.removedChildPackages != null) { 15699 final int childCount = (deletedPs.childPackageNames != null) 15700 ? deletedPs.childPackageNames.size() : 0; 15701 for (int i = 0; i < childCount; i++) { 15702 String childPackageName = deletedPs.childPackageNames.get(i); 15703 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15704 .contains(childPackageName)) { 15705 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15706 childPackageName); 15707 if (childInfo != null) { 15708 childInfo.isRemovedPackageSystemUpdate = true; 15709 } 15710 } 15711 } 15712 } 15713 15714 if (disabledPs.versionCode < deletedPs.versionCode) { 15715 // Delete data for downgrades 15716 flags &= ~PackageManager.DELETE_KEEP_DATA; 15717 } else { 15718 // Preserve data by setting flag 15719 flags |= PackageManager.DELETE_KEEP_DATA; 15720 } 15721 15722 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15723 outInfo, writeSettings, disabledPs.pkg); 15724 if (!ret) { 15725 return false; 15726 } 15727 15728 // writer 15729 synchronized (mPackages) { 15730 // Reinstate the old system package 15731 enableSystemPackageLPw(disabledPs.pkg); 15732 // Remove any native libraries from the upgraded package. 15733 removeNativeBinariesLI(deletedPs); 15734 } 15735 15736 // Install the system package 15737 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15738 int parseFlags = mDefParseFlags 15739 | PackageParser.PARSE_MUST_BE_APK 15740 | PackageParser.PARSE_IS_SYSTEM 15741 | PackageParser.PARSE_IS_SYSTEM_DIR; 15742 if (locationIsPrivileged(disabledPs.codePath)) { 15743 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15744 } 15745 15746 final PackageParser.Package newPkg; 15747 try { 15748 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15749 } catch (PackageManagerException e) { 15750 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15751 + e.getMessage()); 15752 return false; 15753 } 15754 15755 prepareAppDataAfterInstallLIF(newPkg); 15756 15757 // writer 15758 synchronized (mPackages) { 15759 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15760 15761 // Propagate the permissions state as we do not want to drop on the floor 15762 // runtime permissions. The update permissions method below will take 15763 // care of removing obsolete permissions and grant install permissions. 15764 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15765 updatePermissionsLPw(newPkg.packageName, newPkg, 15766 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15767 15768 if (applyUserRestrictions) { 15769 if (DEBUG_REMOVE) { 15770 Slog.d(TAG, "Propagating install state across reinstall"); 15771 } 15772 for (int userId : allUserHandles) { 15773 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15774 if (DEBUG_REMOVE) { 15775 Slog.d(TAG, " user " + userId + " => " + installed); 15776 } 15777 ps.setInstalled(installed, userId); 15778 15779 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15780 } 15781 // Regardless of writeSettings we need to ensure that this restriction 15782 // state propagation is persisted 15783 mSettings.writeAllUsersPackageRestrictionsLPr(); 15784 } 15785 // can downgrade to reader here 15786 if (writeSettings) { 15787 mSettings.writeLPr(); 15788 } 15789 } 15790 return true; 15791 } 15792 15793 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15794 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15795 PackageRemovedInfo outInfo, boolean writeSettings, 15796 PackageParser.Package replacingPackage) { 15797 synchronized (mPackages) { 15798 if (outInfo != null) { 15799 outInfo.uid = ps.appId; 15800 } 15801 15802 if (outInfo != null && outInfo.removedChildPackages != null) { 15803 final int childCount = (ps.childPackageNames != null) 15804 ? ps.childPackageNames.size() : 0; 15805 for (int i = 0; i < childCount; i++) { 15806 String childPackageName = ps.childPackageNames.get(i); 15807 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15808 if (childPs == null) { 15809 return false; 15810 } 15811 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15812 childPackageName); 15813 if (childInfo != null) { 15814 childInfo.uid = childPs.appId; 15815 } 15816 } 15817 } 15818 } 15819 15820 // Delete package data from internal structures and also remove data if flag is set 15821 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15822 15823 // Delete the child packages data 15824 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15825 for (int i = 0; i < childCount; i++) { 15826 PackageSetting childPs; 15827 synchronized (mPackages) { 15828 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15829 } 15830 if (childPs != null) { 15831 PackageRemovedInfo childOutInfo = (outInfo != null 15832 && outInfo.removedChildPackages != null) 15833 ? outInfo.removedChildPackages.get(childPs.name) : null; 15834 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15835 && (replacingPackage != null 15836 && !replacingPackage.hasChildPackage(childPs.name)) 15837 ? flags & ~DELETE_KEEP_DATA : flags; 15838 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15839 deleteFlags, writeSettings); 15840 } 15841 } 15842 15843 // Delete application code and resources only for parent packages 15844 if (ps.parentPackageName == null) { 15845 if (deleteCodeAndResources && (outInfo != null)) { 15846 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15847 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15848 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15849 } 15850 } 15851 15852 return true; 15853 } 15854 15855 @Override 15856 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15857 int userId) { 15858 mContext.enforceCallingOrSelfPermission( 15859 android.Manifest.permission.DELETE_PACKAGES, null); 15860 synchronized (mPackages) { 15861 PackageSetting ps = mSettings.mPackages.get(packageName); 15862 if (ps == null) { 15863 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15864 return false; 15865 } 15866 if (!ps.getInstalled(userId)) { 15867 // Can't block uninstall for an app that is not installed or enabled. 15868 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15869 return false; 15870 } 15871 ps.setBlockUninstall(blockUninstall, userId); 15872 mSettings.writePackageRestrictionsLPr(userId); 15873 } 15874 return true; 15875 } 15876 15877 @Override 15878 public boolean getBlockUninstallForUser(String packageName, int userId) { 15879 synchronized (mPackages) { 15880 PackageSetting ps = mSettings.mPackages.get(packageName); 15881 if (ps == null) { 15882 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15883 return false; 15884 } 15885 return ps.getBlockUninstall(userId); 15886 } 15887 } 15888 15889 @Override 15890 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15891 int callingUid = Binder.getCallingUid(); 15892 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15893 throw new SecurityException( 15894 "setRequiredForSystemUser can only be run by the system or root"); 15895 } 15896 synchronized (mPackages) { 15897 PackageSetting ps = mSettings.mPackages.get(packageName); 15898 if (ps == null) { 15899 Log.w(TAG, "Package doesn't exist: " + packageName); 15900 return false; 15901 } 15902 if (systemUserApp) { 15903 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15904 } else { 15905 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15906 } 15907 mSettings.writeLPr(); 15908 } 15909 return true; 15910 } 15911 15912 /* 15913 * This method handles package deletion in general 15914 */ 15915 private boolean deletePackageLIF(String packageName, UserHandle user, 15916 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15917 PackageRemovedInfo outInfo, boolean writeSettings, 15918 PackageParser.Package replacingPackage) { 15919 if (packageName == null) { 15920 Slog.w(TAG, "Attempt to delete null packageName."); 15921 return false; 15922 } 15923 15924 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15925 15926 PackageSetting ps; 15927 15928 synchronized (mPackages) { 15929 ps = mSettings.mPackages.get(packageName); 15930 if (ps == null) { 15931 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15932 return false; 15933 } 15934 15935 if (ps.parentPackageName != null && (!isSystemApp(ps) 15936 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15937 if (DEBUG_REMOVE) { 15938 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15939 + ((user == null) ? UserHandle.USER_ALL : user)); 15940 } 15941 final int removedUserId = (user != null) ? user.getIdentifier() 15942 : UserHandle.USER_ALL; 15943 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15944 return false; 15945 } 15946 markPackageUninstalledForUserLPw(ps, user); 15947 scheduleWritePackageRestrictionsLocked(user); 15948 return true; 15949 } 15950 } 15951 15952 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15953 && user.getIdentifier() != UserHandle.USER_ALL)) { 15954 // The caller is asking that the package only be deleted for a single 15955 // user. To do this, we just mark its uninstalled state and delete 15956 // its data. If this is a system app, we only allow this to happen if 15957 // they have set the special DELETE_SYSTEM_APP which requests different 15958 // semantics than normal for uninstalling system apps. 15959 markPackageUninstalledForUserLPw(ps, user); 15960 15961 if (!isSystemApp(ps)) { 15962 // Do not uninstall the APK if an app should be cached 15963 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15964 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15965 // Other user still have this package installed, so all 15966 // we need to do is clear this user's data and save that 15967 // it is uninstalled. 15968 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15969 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15970 return false; 15971 } 15972 scheduleWritePackageRestrictionsLocked(user); 15973 return true; 15974 } else { 15975 // We need to set it back to 'installed' so the uninstall 15976 // broadcasts will be sent correctly. 15977 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15978 ps.setInstalled(true, user.getIdentifier()); 15979 } 15980 } else { 15981 // This is a system app, so we assume that the 15982 // other users still have this package installed, so all 15983 // we need to do is clear this user's data and save that 15984 // it is uninstalled. 15985 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15986 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15987 return false; 15988 } 15989 scheduleWritePackageRestrictionsLocked(user); 15990 return true; 15991 } 15992 } 15993 15994 // If we are deleting a composite package for all users, keep track 15995 // of result for each child. 15996 if (ps.childPackageNames != null && outInfo != null) { 15997 synchronized (mPackages) { 15998 final int childCount = ps.childPackageNames.size(); 15999 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16000 for (int i = 0; i < childCount; i++) { 16001 String childPackageName = ps.childPackageNames.get(i); 16002 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16003 childInfo.removedPackage = childPackageName; 16004 outInfo.removedChildPackages.put(childPackageName, childInfo); 16005 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16006 if (childPs != null) { 16007 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16008 } 16009 } 16010 } 16011 } 16012 16013 boolean ret = false; 16014 if (isSystemApp(ps)) { 16015 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16016 // When an updated system application is deleted we delete the existing resources 16017 // as well and fall back to existing code in system partition 16018 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16019 } else { 16020 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16021 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16022 outInfo, writeSettings, replacingPackage); 16023 } 16024 16025 // Take a note whether we deleted the package for all users 16026 if (outInfo != null) { 16027 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16028 if (outInfo.removedChildPackages != null) { 16029 synchronized (mPackages) { 16030 final int childCount = outInfo.removedChildPackages.size(); 16031 for (int i = 0; i < childCount; i++) { 16032 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16033 if (childInfo != null) { 16034 childInfo.removedForAllUsers = mPackages.get( 16035 childInfo.removedPackage) == null; 16036 } 16037 } 16038 } 16039 } 16040 // If we uninstalled an update to a system app there may be some 16041 // child packages that appeared as they are declared in the system 16042 // app but were not declared in the update. 16043 if (isSystemApp(ps)) { 16044 synchronized (mPackages) { 16045 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16046 final int childCount = (updatedPs.childPackageNames != null) 16047 ? updatedPs.childPackageNames.size() : 0; 16048 for (int i = 0; i < childCount; i++) { 16049 String childPackageName = updatedPs.childPackageNames.get(i); 16050 if (outInfo.removedChildPackages == null 16051 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16052 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16053 if (childPs == null) { 16054 continue; 16055 } 16056 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16057 installRes.name = childPackageName; 16058 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16059 installRes.pkg = mPackages.get(childPackageName); 16060 installRes.uid = childPs.pkg.applicationInfo.uid; 16061 if (outInfo.appearedChildPackages == null) { 16062 outInfo.appearedChildPackages = new ArrayMap<>(); 16063 } 16064 outInfo.appearedChildPackages.put(childPackageName, installRes); 16065 } 16066 } 16067 } 16068 } 16069 } 16070 16071 return ret; 16072 } 16073 16074 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16075 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16076 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16077 for (int nextUserId : userIds) { 16078 if (DEBUG_REMOVE) { 16079 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16080 } 16081 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16082 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16083 false /*hidden*/, false /*suspended*/, null, null, null, 16084 false /*blockUninstall*/, 16085 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16086 } 16087 } 16088 16089 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16090 PackageRemovedInfo outInfo) { 16091 final PackageParser.Package pkg; 16092 synchronized (mPackages) { 16093 pkg = mPackages.get(ps.name); 16094 } 16095 16096 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16097 : new int[] {userId}; 16098 for (int nextUserId : userIds) { 16099 if (DEBUG_REMOVE) { 16100 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16101 + nextUserId); 16102 } 16103 16104 destroyAppDataLIF(pkg, userId, 16105 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16106 destroyAppProfilesLIF(pkg, userId); 16107 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16108 schedulePackageCleaning(ps.name, nextUserId, false); 16109 synchronized (mPackages) { 16110 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16111 scheduleWritePackageRestrictionsLocked(nextUserId); 16112 } 16113 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16114 } 16115 } 16116 16117 if (outInfo != null) { 16118 outInfo.removedPackage = ps.name; 16119 outInfo.removedAppId = ps.appId; 16120 outInfo.removedUsers = userIds; 16121 } 16122 16123 return true; 16124 } 16125 16126 private final class ClearStorageConnection implements ServiceConnection { 16127 IMediaContainerService mContainerService; 16128 16129 @Override 16130 public void onServiceConnected(ComponentName name, IBinder service) { 16131 synchronized (this) { 16132 mContainerService = IMediaContainerService.Stub.asInterface(service); 16133 notifyAll(); 16134 } 16135 } 16136 16137 @Override 16138 public void onServiceDisconnected(ComponentName name) { 16139 } 16140 } 16141 16142 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16143 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16144 16145 final boolean mounted; 16146 if (Environment.isExternalStorageEmulated()) { 16147 mounted = true; 16148 } else { 16149 final String status = Environment.getExternalStorageState(); 16150 16151 mounted = status.equals(Environment.MEDIA_MOUNTED) 16152 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16153 } 16154 16155 if (!mounted) { 16156 return; 16157 } 16158 16159 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16160 int[] users; 16161 if (userId == UserHandle.USER_ALL) { 16162 users = sUserManager.getUserIds(); 16163 } else { 16164 users = new int[] { userId }; 16165 } 16166 final ClearStorageConnection conn = new ClearStorageConnection(); 16167 if (mContext.bindServiceAsUser( 16168 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16169 try { 16170 for (int curUser : users) { 16171 long timeout = SystemClock.uptimeMillis() + 5000; 16172 synchronized (conn) { 16173 long now = SystemClock.uptimeMillis(); 16174 while (conn.mContainerService == null && now < timeout) { 16175 try { 16176 conn.wait(timeout - now); 16177 } catch (InterruptedException e) { 16178 } 16179 } 16180 } 16181 if (conn.mContainerService == null) { 16182 return; 16183 } 16184 16185 final UserEnvironment userEnv = new UserEnvironment(curUser); 16186 clearDirectory(conn.mContainerService, 16187 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16188 if (allData) { 16189 clearDirectory(conn.mContainerService, 16190 userEnv.buildExternalStorageAppDataDirs(packageName)); 16191 clearDirectory(conn.mContainerService, 16192 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16193 } 16194 } 16195 } finally { 16196 mContext.unbindService(conn); 16197 } 16198 } 16199 } 16200 16201 @Override 16202 public void clearApplicationProfileData(String packageName) { 16203 enforceSystemOrRoot("Only the system can clear all profile data"); 16204 16205 final PackageParser.Package pkg; 16206 synchronized (mPackages) { 16207 pkg = mPackages.get(packageName); 16208 } 16209 16210 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16211 synchronized (mInstallLock) { 16212 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16213 } 16214 } 16215 } 16216 16217 @Override 16218 public void clearApplicationUserData(final String packageName, 16219 final IPackageDataObserver observer, final int userId) { 16220 mContext.enforceCallingOrSelfPermission( 16221 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16222 16223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16224 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16225 16226 final DevicePolicyManagerInternal dpmi = LocalServices 16227 .getService(DevicePolicyManagerInternal.class); 16228 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16229 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16230 } 16231 // Queue up an async operation since the package deletion may take a little while. 16232 mHandler.post(new Runnable() { 16233 public void run() { 16234 mHandler.removeCallbacks(this); 16235 final boolean succeeded; 16236 try (PackageFreezer freezer = freezePackage(packageName, 16237 "clearApplicationUserData")) { 16238 synchronized (mInstallLock) { 16239 succeeded = clearApplicationUserDataLIF(packageName, userId); 16240 } 16241 clearExternalStorageDataSync(packageName, userId, true); 16242 } 16243 if (succeeded) { 16244 // invoke DeviceStorageMonitor's update method to clear any notifications 16245 DeviceStorageMonitorInternal dsm = LocalServices 16246 .getService(DeviceStorageMonitorInternal.class); 16247 if (dsm != null) { 16248 dsm.checkMemory(); 16249 } 16250 } 16251 if(observer != null) { 16252 try { 16253 observer.onRemoveCompleted(packageName, succeeded); 16254 } catch (RemoteException e) { 16255 Log.i(TAG, "Observer no longer exists."); 16256 } 16257 } //end if observer 16258 } //end run 16259 }); 16260 } 16261 16262 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16263 if (packageName == null) { 16264 Slog.w(TAG, "Attempt to delete null packageName."); 16265 return false; 16266 } 16267 16268 // Try finding details about the requested package 16269 PackageParser.Package pkg; 16270 synchronized (mPackages) { 16271 pkg = mPackages.get(packageName); 16272 if (pkg == null) { 16273 final PackageSetting ps = mSettings.mPackages.get(packageName); 16274 if (ps != null) { 16275 pkg = ps.pkg; 16276 } 16277 } 16278 16279 if (pkg == null) { 16280 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16281 return false; 16282 } 16283 16284 PackageSetting ps = (PackageSetting) pkg.mExtras; 16285 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16286 } 16287 16288 clearAppDataLIF(pkg, userId, 16289 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16290 16291 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16292 removeKeystoreDataIfNeeded(userId, appId); 16293 16294 UserManagerInternal umInternal = getUserManagerInternal(); 16295 final int flags; 16296 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16297 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16298 } else if (umInternal.isUserRunning(userId)) { 16299 flags = StorageManager.FLAG_STORAGE_DE; 16300 } else { 16301 flags = 0; 16302 } 16303 prepareAppDataContentsLIF(pkg, userId, flags); 16304 16305 return true; 16306 } 16307 16308 /** 16309 * Reverts user permission state changes (permissions and flags) in 16310 * all packages for a given user. 16311 * 16312 * @param userId The device user for which to do a reset. 16313 */ 16314 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16315 final int packageCount = mPackages.size(); 16316 for (int i = 0; i < packageCount; i++) { 16317 PackageParser.Package pkg = mPackages.valueAt(i); 16318 PackageSetting ps = (PackageSetting) pkg.mExtras; 16319 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16320 } 16321 } 16322 16323 private void resetNetworkPolicies(int userId) { 16324 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16325 } 16326 16327 /** 16328 * Reverts user permission state changes (permissions and flags). 16329 * 16330 * @param ps The package for which to reset. 16331 * @param userId The device user for which to do a reset. 16332 */ 16333 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16334 final PackageSetting ps, final int userId) { 16335 if (ps.pkg == null) { 16336 return; 16337 } 16338 16339 // These are flags that can change base on user actions. 16340 final int userSettableMask = FLAG_PERMISSION_USER_SET 16341 | FLAG_PERMISSION_USER_FIXED 16342 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16343 | FLAG_PERMISSION_REVIEW_REQUIRED; 16344 16345 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16346 | FLAG_PERMISSION_POLICY_FIXED; 16347 16348 boolean writeInstallPermissions = false; 16349 boolean writeRuntimePermissions = false; 16350 16351 final int permissionCount = ps.pkg.requestedPermissions.size(); 16352 for (int i = 0; i < permissionCount; i++) { 16353 String permission = ps.pkg.requestedPermissions.get(i); 16354 16355 BasePermission bp = mSettings.mPermissions.get(permission); 16356 if (bp == null) { 16357 continue; 16358 } 16359 16360 // If shared user we just reset the state to which only this app contributed. 16361 if (ps.sharedUser != null) { 16362 boolean used = false; 16363 final int packageCount = ps.sharedUser.packages.size(); 16364 for (int j = 0; j < packageCount; j++) { 16365 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16366 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16367 && pkg.pkg.requestedPermissions.contains(permission)) { 16368 used = true; 16369 break; 16370 } 16371 } 16372 if (used) { 16373 continue; 16374 } 16375 } 16376 16377 PermissionsState permissionsState = ps.getPermissionsState(); 16378 16379 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16380 16381 // Always clear the user settable flags. 16382 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16383 bp.name) != null; 16384 // If permission review is enabled and this is a legacy app, mark the 16385 // permission as requiring a review as this is the initial state. 16386 int flags = 0; 16387 if (Build.PERMISSIONS_REVIEW_REQUIRED 16388 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16389 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16390 } 16391 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16392 if (hasInstallState) { 16393 writeInstallPermissions = true; 16394 } else { 16395 writeRuntimePermissions = true; 16396 } 16397 } 16398 16399 // Below is only runtime permission handling. 16400 if (!bp.isRuntime()) { 16401 continue; 16402 } 16403 16404 // Never clobber system or policy. 16405 if ((oldFlags & policyOrSystemFlags) != 0) { 16406 continue; 16407 } 16408 16409 // If this permission was granted by default, make sure it is. 16410 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16411 if (permissionsState.grantRuntimePermission(bp, userId) 16412 != PERMISSION_OPERATION_FAILURE) { 16413 writeRuntimePermissions = true; 16414 } 16415 // If permission review is enabled the permissions for a legacy apps 16416 // are represented as constantly granted runtime ones, so don't revoke. 16417 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16418 // Otherwise, reset the permission. 16419 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16420 switch (revokeResult) { 16421 case PERMISSION_OPERATION_SUCCESS: 16422 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16423 writeRuntimePermissions = true; 16424 final int appId = ps.appId; 16425 mHandler.post(new Runnable() { 16426 @Override 16427 public void run() { 16428 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16429 } 16430 }); 16431 } break; 16432 } 16433 } 16434 } 16435 16436 // Synchronously write as we are taking permissions away. 16437 if (writeRuntimePermissions) { 16438 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16439 } 16440 16441 // Synchronously write as we are taking permissions away. 16442 if (writeInstallPermissions) { 16443 mSettings.writeLPr(); 16444 } 16445 } 16446 16447 /** 16448 * Remove entries from the keystore daemon. Will only remove it if the 16449 * {@code appId} is valid. 16450 */ 16451 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16452 if (appId < 0) { 16453 return; 16454 } 16455 16456 final KeyStore keyStore = KeyStore.getInstance(); 16457 if (keyStore != null) { 16458 if (userId == UserHandle.USER_ALL) { 16459 for (final int individual : sUserManager.getUserIds()) { 16460 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16461 } 16462 } else { 16463 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16464 } 16465 } else { 16466 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16467 } 16468 } 16469 16470 @Override 16471 public void deleteApplicationCacheFiles(final String packageName, 16472 final IPackageDataObserver observer) { 16473 final int userId = UserHandle.getCallingUserId(); 16474 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16475 } 16476 16477 @Override 16478 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16479 final IPackageDataObserver observer) { 16480 mContext.enforceCallingOrSelfPermission( 16481 android.Manifest.permission.DELETE_CACHE_FILES, null); 16482 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16483 /* requireFullPermission= */ true, /* checkShell= */ false, 16484 "delete application cache files"); 16485 16486 final PackageParser.Package pkg; 16487 synchronized (mPackages) { 16488 pkg = mPackages.get(packageName); 16489 } 16490 16491 // Queue up an async operation since the package deletion may take a little while. 16492 mHandler.post(new Runnable() { 16493 public void run() { 16494 synchronized (mInstallLock) { 16495 final int flags = StorageManager.FLAG_STORAGE_DE 16496 | StorageManager.FLAG_STORAGE_CE; 16497 // We're only clearing cache files, so we don't care if the 16498 // app is unfrozen and still able to run 16499 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16500 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16501 } 16502 clearExternalStorageDataSync(packageName, userId, false); 16503 if (observer != null) { 16504 try { 16505 observer.onRemoveCompleted(packageName, true); 16506 } catch (RemoteException e) { 16507 Log.i(TAG, "Observer no longer exists."); 16508 } 16509 } 16510 } 16511 }); 16512 } 16513 16514 @Override 16515 public void getPackageSizeInfo(final String packageName, int userHandle, 16516 final IPackageStatsObserver observer) { 16517 mContext.enforceCallingOrSelfPermission( 16518 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16519 if (packageName == null) { 16520 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16521 } 16522 16523 PackageStats stats = new PackageStats(packageName, userHandle); 16524 16525 /* 16526 * Queue up an async operation since the package measurement may take a 16527 * little while. 16528 */ 16529 Message msg = mHandler.obtainMessage(INIT_COPY); 16530 msg.obj = new MeasureParams(stats, observer); 16531 mHandler.sendMessage(msg); 16532 } 16533 16534 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16535 final PackageSetting ps; 16536 synchronized (mPackages) { 16537 ps = mSettings.mPackages.get(packageName); 16538 if (ps == null) { 16539 Slog.w(TAG, "Failed to find settings for " + packageName); 16540 return false; 16541 } 16542 } 16543 try { 16544 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16545 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16546 ps.getCeDataInode(userId), ps.codePathString, stats); 16547 } catch (InstallerException e) { 16548 Slog.w(TAG, String.valueOf(e)); 16549 return false; 16550 } 16551 16552 // For now, ignore code size of packages on system partition 16553 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16554 stats.codeSize = 0; 16555 } 16556 16557 return true; 16558 } 16559 16560 private int getUidTargetSdkVersionLockedLPr(int uid) { 16561 Object obj = mSettings.getUserIdLPr(uid); 16562 if (obj instanceof SharedUserSetting) { 16563 final SharedUserSetting sus = (SharedUserSetting) obj; 16564 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16565 final Iterator<PackageSetting> it = sus.packages.iterator(); 16566 while (it.hasNext()) { 16567 final PackageSetting ps = it.next(); 16568 if (ps.pkg != null) { 16569 int v = ps.pkg.applicationInfo.targetSdkVersion; 16570 if (v < vers) vers = v; 16571 } 16572 } 16573 return vers; 16574 } else if (obj instanceof PackageSetting) { 16575 final PackageSetting ps = (PackageSetting) obj; 16576 if (ps.pkg != null) { 16577 return ps.pkg.applicationInfo.targetSdkVersion; 16578 } 16579 } 16580 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16581 } 16582 16583 @Override 16584 public void addPreferredActivity(IntentFilter filter, int match, 16585 ComponentName[] set, ComponentName activity, int userId) { 16586 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16587 "Adding preferred"); 16588 } 16589 16590 private void addPreferredActivityInternal(IntentFilter filter, int match, 16591 ComponentName[] set, ComponentName activity, boolean always, int userId, 16592 String opname) { 16593 // writer 16594 int callingUid = Binder.getCallingUid(); 16595 enforceCrossUserPermission(callingUid, userId, 16596 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16597 if (filter.countActions() == 0) { 16598 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16599 return; 16600 } 16601 synchronized (mPackages) { 16602 if (mContext.checkCallingOrSelfPermission( 16603 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16604 != PackageManager.PERMISSION_GRANTED) { 16605 if (getUidTargetSdkVersionLockedLPr(callingUid) 16606 < Build.VERSION_CODES.FROYO) { 16607 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16608 + callingUid); 16609 return; 16610 } 16611 mContext.enforceCallingOrSelfPermission( 16612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16613 } 16614 16615 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16616 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16617 + userId + ":"); 16618 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16619 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16620 scheduleWritePackageRestrictionsLocked(userId); 16621 } 16622 } 16623 16624 @Override 16625 public void replacePreferredActivity(IntentFilter filter, int match, 16626 ComponentName[] set, ComponentName activity, int userId) { 16627 if (filter.countActions() != 1) { 16628 throw new IllegalArgumentException( 16629 "replacePreferredActivity expects filter to have only 1 action."); 16630 } 16631 if (filter.countDataAuthorities() != 0 16632 || filter.countDataPaths() != 0 16633 || filter.countDataSchemes() > 1 16634 || filter.countDataTypes() != 0) { 16635 throw new IllegalArgumentException( 16636 "replacePreferredActivity expects filter to have no data authorities, " + 16637 "paths, or types; and at most one scheme."); 16638 } 16639 16640 final int callingUid = Binder.getCallingUid(); 16641 enforceCrossUserPermission(callingUid, userId, 16642 true /* requireFullPermission */, false /* checkShell */, 16643 "replace preferred activity"); 16644 synchronized (mPackages) { 16645 if (mContext.checkCallingOrSelfPermission( 16646 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16647 != PackageManager.PERMISSION_GRANTED) { 16648 if (getUidTargetSdkVersionLockedLPr(callingUid) 16649 < Build.VERSION_CODES.FROYO) { 16650 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16651 + Binder.getCallingUid()); 16652 return; 16653 } 16654 mContext.enforceCallingOrSelfPermission( 16655 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16656 } 16657 16658 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16659 if (pir != null) { 16660 // Get all of the existing entries that exactly match this filter. 16661 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16662 if (existing != null && existing.size() == 1) { 16663 PreferredActivity cur = existing.get(0); 16664 if (DEBUG_PREFERRED) { 16665 Slog.i(TAG, "Checking replace of preferred:"); 16666 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16667 if (!cur.mPref.mAlways) { 16668 Slog.i(TAG, " -- CUR; not mAlways!"); 16669 } else { 16670 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16671 Slog.i(TAG, " -- CUR: mSet=" 16672 + Arrays.toString(cur.mPref.mSetComponents)); 16673 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16674 Slog.i(TAG, " -- NEW: mMatch=" 16675 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16676 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16677 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16678 } 16679 } 16680 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16681 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16682 && cur.mPref.sameSet(set)) { 16683 // Setting the preferred activity to what it happens to be already 16684 if (DEBUG_PREFERRED) { 16685 Slog.i(TAG, "Replacing with same preferred activity " 16686 + cur.mPref.mShortComponent + " for user " 16687 + userId + ":"); 16688 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16689 } 16690 return; 16691 } 16692 } 16693 16694 if (existing != null) { 16695 if (DEBUG_PREFERRED) { 16696 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16697 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16698 } 16699 for (int i = 0; i < existing.size(); i++) { 16700 PreferredActivity pa = existing.get(i); 16701 if (DEBUG_PREFERRED) { 16702 Slog.i(TAG, "Removing existing preferred activity " 16703 + pa.mPref.mComponent + ":"); 16704 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16705 } 16706 pir.removeFilter(pa); 16707 } 16708 } 16709 } 16710 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16711 "Replacing preferred"); 16712 } 16713 } 16714 16715 @Override 16716 public void clearPackagePreferredActivities(String packageName) { 16717 final int uid = Binder.getCallingUid(); 16718 // writer 16719 synchronized (mPackages) { 16720 PackageParser.Package pkg = mPackages.get(packageName); 16721 if (pkg == null || pkg.applicationInfo.uid != uid) { 16722 if (mContext.checkCallingOrSelfPermission( 16723 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16724 != PackageManager.PERMISSION_GRANTED) { 16725 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16726 < Build.VERSION_CODES.FROYO) { 16727 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16728 + Binder.getCallingUid()); 16729 return; 16730 } 16731 mContext.enforceCallingOrSelfPermission( 16732 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16733 } 16734 } 16735 16736 int user = UserHandle.getCallingUserId(); 16737 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16738 scheduleWritePackageRestrictionsLocked(user); 16739 } 16740 } 16741 } 16742 16743 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16744 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16745 ArrayList<PreferredActivity> removed = null; 16746 boolean changed = false; 16747 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16748 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16749 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16750 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16751 continue; 16752 } 16753 Iterator<PreferredActivity> it = pir.filterIterator(); 16754 while (it.hasNext()) { 16755 PreferredActivity pa = it.next(); 16756 // Mark entry for removal only if it matches the package name 16757 // and the entry is of type "always". 16758 if (packageName == null || 16759 (pa.mPref.mComponent.getPackageName().equals(packageName) 16760 && pa.mPref.mAlways)) { 16761 if (removed == null) { 16762 removed = new ArrayList<PreferredActivity>(); 16763 } 16764 removed.add(pa); 16765 } 16766 } 16767 if (removed != null) { 16768 for (int j=0; j<removed.size(); j++) { 16769 PreferredActivity pa = removed.get(j); 16770 pir.removeFilter(pa); 16771 } 16772 changed = true; 16773 } 16774 } 16775 return changed; 16776 } 16777 16778 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16779 private void clearIntentFilterVerificationsLPw(int userId) { 16780 final int packageCount = mPackages.size(); 16781 for (int i = 0; i < packageCount; i++) { 16782 PackageParser.Package pkg = mPackages.valueAt(i); 16783 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16784 } 16785 } 16786 16787 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16788 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16789 if (userId == UserHandle.USER_ALL) { 16790 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16791 sUserManager.getUserIds())) { 16792 for (int oneUserId : sUserManager.getUserIds()) { 16793 scheduleWritePackageRestrictionsLocked(oneUserId); 16794 } 16795 } 16796 } else { 16797 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16798 scheduleWritePackageRestrictionsLocked(userId); 16799 } 16800 } 16801 } 16802 16803 void clearDefaultBrowserIfNeeded(String packageName) { 16804 for (int oneUserId : sUserManager.getUserIds()) { 16805 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16806 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16807 if (packageName.equals(defaultBrowserPackageName)) { 16808 setDefaultBrowserPackageName(null, oneUserId); 16809 } 16810 } 16811 } 16812 16813 @Override 16814 public void resetApplicationPreferences(int userId) { 16815 mContext.enforceCallingOrSelfPermission( 16816 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16817 final long identity = Binder.clearCallingIdentity(); 16818 // writer 16819 try { 16820 synchronized (mPackages) { 16821 clearPackagePreferredActivitiesLPw(null, userId); 16822 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16823 // TODO: We have to reset the default SMS and Phone. This requires 16824 // significant refactoring to keep all default apps in the package 16825 // manager (cleaner but more work) or have the services provide 16826 // callbacks to the package manager to request a default app reset. 16827 applyFactoryDefaultBrowserLPw(userId); 16828 clearIntentFilterVerificationsLPw(userId); 16829 primeDomainVerificationsLPw(userId); 16830 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16831 scheduleWritePackageRestrictionsLocked(userId); 16832 } 16833 resetNetworkPolicies(userId); 16834 } finally { 16835 Binder.restoreCallingIdentity(identity); 16836 } 16837 } 16838 16839 @Override 16840 public int getPreferredActivities(List<IntentFilter> outFilters, 16841 List<ComponentName> outActivities, String packageName) { 16842 16843 int num = 0; 16844 final int userId = UserHandle.getCallingUserId(); 16845 // reader 16846 synchronized (mPackages) { 16847 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16848 if (pir != null) { 16849 final Iterator<PreferredActivity> it = pir.filterIterator(); 16850 while (it.hasNext()) { 16851 final PreferredActivity pa = it.next(); 16852 if (packageName == null 16853 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16854 && pa.mPref.mAlways)) { 16855 if (outFilters != null) { 16856 outFilters.add(new IntentFilter(pa)); 16857 } 16858 if (outActivities != null) { 16859 outActivities.add(pa.mPref.mComponent); 16860 } 16861 } 16862 } 16863 } 16864 } 16865 16866 return num; 16867 } 16868 16869 @Override 16870 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16871 int userId) { 16872 int callingUid = Binder.getCallingUid(); 16873 if (callingUid != Process.SYSTEM_UID) { 16874 throw new SecurityException( 16875 "addPersistentPreferredActivity can only be run by the system"); 16876 } 16877 if (filter.countActions() == 0) { 16878 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16879 return; 16880 } 16881 synchronized (mPackages) { 16882 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16883 ":"); 16884 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16885 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16886 new PersistentPreferredActivity(filter, activity)); 16887 scheduleWritePackageRestrictionsLocked(userId); 16888 } 16889 } 16890 16891 @Override 16892 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16893 int callingUid = Binder.getCallingUid(); 16894 if (callingUid != Process.SYSTEM_UID) { 16895 throw new SecurityException( 16896 "clearPackagePersistentPreferredActivities can only be run by the system"); 16897 } 16898 ArrayList<PersistentPreferredActivity> removed = null; 16899 boolean changed = false; 16900 synchronized (mPackages) { 16901 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16902 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16903 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16904 .valueAt(i); 16905 if (userId != thisUserId) { 16906 continue; 16907 } 16908 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16909 while (it.hasNext()) { 16910 PersistentPreferredActivity ppa = it.next(); 16911 // Mark entry for removal only if it matches the package name. 16912 if (ppa.mComponent.getPackageName().equals(packageName)) { 16913 if (removed == null) { 16914 removed = new ArrayList<PersistentPreferredActivity>(); 16915 } 16916 removed.add(ppa); 16917 } 16918 } 16919 if (removed != null) { 16920 for (int j=0; j<removed.size(); j++) { 16921 PersistentPreferredActivity ppa = removed.get(j); 16922 ppir.removeFilter(ppa); 16923 } 16924 changed = true; 16925 } 16926 } 16927 16928 if (changed) { 16929 scheduleWritePackageRestrictionsLocked(userId); 16930 } 16931 } 16932 } 16933 16934 /** 16935 * Common machinery for picking apart a restored XML blob and passing 16936 * it to a caller-supplied functor to be applied to the running system. 16937 */ 16938 private void restoreFromXml(XmlPullParser parser, int userId, 16939 String expectedStartTag, BlobXmlRestorer functor) 16940 throws IOException, XmlPullParserException { 16941 int type; 16942 while ((type = parser.next()) != XmlPullParser.START_TAG 16943 && type != XmlPullParser.END_DOCUMENT) { 16944 } 16945 if (type != XmlPullParser.START_TAG) { 16946 // oops didn't find a start tag?! 16947 if (DEBUG_BACKUP) { 16948 Slog.e(TAG, "Didn't find start tag during restore"); 16949 } 16950 return; 16951 } 16952Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16953 // this is supposed to be TAG_PREFERRED_BACKUP 16954 if (!expectedStartTag.equals(parser.getName())) { 16955 if (DEBUG_BACKUP) { 16956 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16957 } 16958 return; 16959 } 16960 16961 // skip interfering stuff, then we're aligned with the backing implementation 16962 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16963Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16964 functor.apply(parser, userId); 16965 } 16966 16967 private interface BlobXmlRestorer { 16968 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16969 } 16970 16971 /** 16972 * Non-Binder method, support for the backup/restore mechanism: write the 16973 * full set of preferred activities in its canonical XML format. Returns the 16974 * XML output as a byte array, or null if there is none. 16975 */ 16976 @Override 16977 public byte[] getPreferredActivityBackup(int userId) { 16978 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16979 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16980 } 16981 16982 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16983 try { 16984 final XmlSerializer serializer = new FastXmlSerializer(); 16985 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16986 serializer.startDocument(null, true); 16987 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16988 16989 synchronized (mPackages) { 16990 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16991 } 16992 16993 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16994 serializer.endDocument(); 16995 serializer.flush(); 16996 } catch (Exception e) { 16997 if (DEBUG_BACKUP) { 16998 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16999 } 17000 return null; 17001 } 17002 17003 return dataStream.toByteArray(); 17004 } 17005 17006 @Override 17007 public void restorePreferredActivities(byte[] backup, int userId) { 17008 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17009 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17010 } 17011 17012 try { 17013 final XmlPullParser parser = Xml.newPullParser(); 17014 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17015 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17016 new BlobXmlRestorer() { 17017 @Override 17018 public void apply(XmlPullParser parser, int userId) 17019 throws XmlPullParserException, IOException { 17020 synchronized (mPackages) { 17021 mSettings.readPreferredActivitiesLPw(parser, userId); 17022 } 17023 } 17024 } ); 17025 } catch (Exception e) { 17026 if (DEBUG_BACKUP) { 17027 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17028 } 17029 } 17030 } 17031 17032 /** 17033 * Non-Binder method, support for the backup/restore mechanism: write the 17034 * default browser (etc) settings in its canonical XML format. Returns the default 17035 * browser XML representation as a byte array, or null if there is none. 17036 */ 17037 @Override 17038 public byte[] getDefaultAppsBackup(int userId) { 17039 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17040 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17041 } 17042 17043 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17044 try { 17045 final XmlSerializer serializer = new FastXmlSerializer(); 17046 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17047 serializer.startDocument(null, true); 17048 serializer.startTag(null, TAG_DEFAULT_APPS); 17049 17050 synchronized (mPackages) { 17051 mSettings.writeDefaultAppsLPr(serializer, userId); 17052 } 17053 17054 serializer.endTag(null, TAG_DEFAULT_APPS); 17055 serializer.endDocument(); 17056 serializer.flush(); 17057 } catch (Exception e) { 17058 if (DEBUG_BACKUP) { 17059 Slog.e(TAG, "Unable to write default apps for backup", e); 17060 } 17061 return null; 17062 } 17063 17064 return dataStream.toByteArray(); 17065 } 17066 17067 @Override 17068 public void restoreDefaultApps(byte[] backup, int userId) { 17069 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17070 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17071 } 17072 17073 try { 17074 final XmlPullParser parser = Xml.newPullParser(); 17075 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17076 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17077 new BlobXmlRestorer() { 17078 @Override 17079 public void apply(XmlPullParser parser, int userId) 17080 throws XmlPullParserException, IOException { 17081 synchronized (mPackages) { 17082 mSettings.readDefaultAppsLPw(parser, userId); 17083 } 17084 } 17085 } ); 17086 } catch (Exception e) { 17087 if (DEBUG_BACKUP) { 17088 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17089 } 17090 } 17091 } 17092 17093 @Override 17094 public byte[] getIntentFilterVerificationBackup(int userId) { 17095 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17096 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17097 } 17098 17099 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17100 try { 17101 final XmlSerializer serializer = new FastXmlSerializer(); 17102 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17103 serializer.startDocument(null, true); 17104 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17105 17106 synchronized (mPackages) { 17107 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17108 } 17109 17110 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17111 serializer.endDocument(); 17112 serializer.flush(); 17113 } catch (Exception e) { 17114 if (DEBUG_BACKUP) { 17115 Slog.e(TAG, "Unable to write default apps for backup", e); 17116 } 17117 return null; 17118 } 17119 17120 return dataStream.toByteArray(); 17121 } 17122 17123 @Override 17124 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17125 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17126 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17127 } 17128 17129 try { 17130 final XmlPullParser parser = Xml.newPullParser(); 17131 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17132 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17133 new BlobXmlRestorer() { 17134 @Override 17135 public void apply(XmlPullParser parser, int userId) 17136 throws XmlPullParserException, IOException { 17137 synchronized (mPackages) { 17138 mSettings.readAllDomainVerificationsLPr(parser, userId); 17139 mSettings.writeLPr(); 17140 } 17141 } 17142 } ); 17143 } catch (Exception e) { 17144 if (DEBUG_BACKUP) { 17145 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17146 } 17147 } 17148 } 17149 17150 @Override 17151 public byte[] getPermissionGrantBackup(int userId) { 17152 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17153 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17154 } 17155 17156 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17157 try { 17158 final XmlSerializer serializer = new FastXmlSerializer(); 17159 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17160 serializer.startDocument(null, true); 17161 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17162 17163 synchronized (mPackages) { 17164 serializeRuntimePermissionGrantsLPr(serializer, userId); 17165 } 17166 17167 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17168 serializer.endDocument(); 17169 serializer.flush(); 17170 } catch (Exception e) { 17171 if (DEBUG_BACKUP) { 17172 Slog.e(TAG, "Unable to write default apps for backup", e); 17173 } 17174 return null; 17175 } 17176 17177 return dataStream.toByteArray(); 17178 } 17179 17180 @Override 17181 public void restorePermissionGrants(byte[] backup, int userId) { 17182 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17183 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17184 } 17185 17186 try { 17187 final XmlPullParser parser = Xml.newPullParser(); 17188 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17189 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17190 new BlobXmlRestorer() { 17191 @Override 17192 public void apply(XmlPullParser parser, int userId) 17193 throws XmlPullParserException, IOException { 17194 synchronized (mPackages) { 17195 processRestoredPermissionGrantsLPr(parser, userId); 17196 } 17197 } 17198 } ); 17199 } catch (Exception e) { 17200 if (DEBUG_BACKUP) { 17201 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17202 } 17203 } 17204 } 17205 17206 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17207 throws IOException { 17208 serializer.startTag(null, TAG_ALL_GRANTS); 17209 17210 final int N = mSettings.mPackages.size(); 17211 for (int i = 0; i < N; i++) { 17212 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17213 boolean pkgGrantsKnown = false; 17214 17215 PermissionsState packagePerms = ps.getPermissionsState(); 17216 17217 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17218 final int grantFlags = state.getFlags(); 17219 // only look at grants that are not system/policy fixed 17220 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17221 final boolean isGranted = state.isGranted(); 17222 // And only back up the user-twiddled state bits 17223 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17224 final String packageName = mSettings.mPackages.keyAt(i); 17225 if (!pkgGrantsKnown) { 17226 serializer.startTag(null, TAG_GRANT); 17227 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17228 pkgGrantsKnown = true; 17229 } 17230 17231 final boolean userSet = 17232 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17233 final boolean userFixed = 17234 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17235 final boolean revoke = 17236 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17237 17238 serializer.startTag(null, TAG_PERMISSION); 17239 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17240 if (isGranted) { 17241 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17242 } 17243 if (userSet) { 17244 serializer.attribute(null, ATTR_USER_SET, "true"); 17245 } 17246 if (userFixed) { 17247 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17248 } 17249 if (revoke) { 17250 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17251 } 17252 serializer.endTag(null, TAG_PERMISSION); 17253 } 17254 } 17255 } 17256 17257 if (pkgGrantsKnown) { 17258 serializer.endTag(null, TAG_GRANT); 17259 } 17260 } 17261 17262 serializer.endTag(null, TAG_ALL_GRANTS); 17263 } 17264 17265 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17266 throws XmlPullParserException, IOException { 17267 String pkgName = null; 17268 int outerDepth = parser.getDepth(); 17269 int type; 17270 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17271 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17272 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17273 continue; 17274 } 17275 17276 final String tagName = parser.getName(); 17277 if (tagName.equals(TAG_GRANT)) { 17278 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17279 if (DEBUG_BACKUP) { 17280 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17281 } 17282 } else if (tagName.equals(TAG_PERMISSION)) { 17283 17284 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17285 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17286 17287 int newFlagSet = 0; 17288 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17289 newFlagSet |= FLAG_PERMISSION_USER_SET; 17290 } 17291 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17292 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17293 } 17294 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17295 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17296 } 17297 if (DEBUG_BACKUP) { 17298 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17299 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17300 } 17301 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17302 if (ps != null) { 17303 // Already installed so we apply the grant immediately 17304 if (DEBUG_BACKUP) { 17305 Slog.v(TAG, " + already installed; applying"); 17306 } 17307 PermissionsState perms = ps.getPermissionsState(); 17308 BasePermission bp = mSettings.mPermissions.get(permName); 17309 if (bp != null) { 17310 if (isGranted) { 17311 perms.grantRuntimePermission(bp, userId); 17312 } 17313 if (newFlagSet != 0) { 17314 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17315 } 17316 } 17317 } else { 17318 // Need to wait for post-restore install to apply the grant 17319 if (DEBUG_BACKUP) { 17320 Slog.v(TAG, " - not yet installed; saving for later"); 17321 } 17322 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17323 isGranted, newFlagSet, userId); 17324 } 17325 } else { 17326 PackageManagerService.reportSettingsProblem(Log.WARN, 17327 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17328 XmlUtils.skipCurrentTag(parser); 17329 } 17330 } 17331 17332 scheduleWriteSettingsLocked(); 17333 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17334 } 17335 17336 @Override 17337 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17338 int sourceUserId, int targetUserId, int flags) { 17339 mContext.enforceCallingOrSelfPermission( 17340 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17341 int callingUid = Binder.getCallingUid(); 17342 enforceOwnerRights(ownerPackage, callingUid); 17343 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17344 if (intentFilter.countActions() == 0) { 17345 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17346 return; 17347 } 17348 synchronized (mPackages) { 17349 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17350 ownerPackage, targetUserId, flags); 17351 CrossProfileIntentResolver resolver = 17352 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17353 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17354 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17355 if (existing != null) { 17356 int size = existing.size(); 17357 for (int i = 0; i < size; i++) { 17358 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17359 return; 17360 } 17361 } 17362 } 17363 resolver.addFilter(newFilter); 17364 scheduleWritePackageRestrictionsLocked(sourceUserId); 17365 } 17366 } 17367 17368 @Override 17369 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17370 mContext.enforceCallingOrSelfPermission( 17371 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17372 int callingUid = Binder.getCallingUid(); 17373 enforceOwnerRights(ownerPackage, callingUid); 17374 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17375 synchronized (mPackages) { 17376 CrossProfileIntentResolver resolver = 17377 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17378 ArraySet<CrossProfileIntentFilter> set = 17379 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17380 for (CrossProfileIntentFilter filter : set) { 17381 if (filter.getOwnerPackage().equals(ownerPackage)) { 17382 resolver.removeFilter(filter); 17383 } 17384 } 17385 scheduleWritePackageRestrictionsLocked(sourceUserId); 17386 } 17387 } 17388 17389 // Enforcing that callingUid is owning pkg on userId 17390 private void enforceOwnerRights(String pkg, int callingUid) { 17391 // The system owns everything. 17392 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17393 return; 17394 } 17395 int callingUserId = UserHandle.getUserId(callingUid); 17396 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17397 if (pi == null) { 17398 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17399 + callingUserId); 17400 } 17401 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17402 throw new SecurityException("Calling uid " + callingUid 17403 + " does not own package " + pkg); 17404 } 17405 } 17406 17407 @Override 17408 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17409 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17410 } 17411 17412 private Intent getHomeIntent() { 17413 Intent intent = new Intent(Intent.ACTION_MAIN); 17414 intent.addCategory(Intent.CATEGORY_HOME); 17415 return intent; 17416 } 17417 17418 private IntentFilter getHomeFilter() { 17419 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17420 filter.addCategory(Intent.CATEGORY_HOME); 17421 filter.addCategory(Intent.CATEGORY_DEFAULT); 17422 return filter; 17423 } 17424 17425 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17426 int userId) { 17427 Intent intent = getHomeIntent(); 17428 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17429 PackageManager.GET_META_DATA, userId); 17430 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17431 true, false, false, userId); 17432 17433 allHomeCandidates.clear(); 17434 if (list != null) { 17435 for (ResolveInfo ri : list) { 17436 allHomeCandidates.add(ri); 17437 } 17438 } 17439 return (preferred == null || preferred.activityInfo == null) 17440 ? null 17441 : new ComponentName(preferred.activityInfo.packageName, 17442 preferred.activityInfo.name); 17443 } 17444 17445 @Override 17446 public void setHomeActivity(ComponentName comp, int userId) { 17447 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17448 getHomeActivitiesAsUser(homeActivities, userId); 17449 17450 boolean found = false; 17451 17452 final int size = homeActivities.size(); 17453 final ComponentName[] set = new ComponentName[size]; 17454 for (int i = 0; i < size; i++) { 17455 final ResolveInfo candidate = homeActivities.get(i); 17456 final ActivityInfo info = candidate.activityInfo; 17457 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17458 set[i] = activityName; 17459 if (!found && activityName.equals(comp)) { 17460 found = true; 17461 } 17462 } 17463 if (!found) { 17464 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17465 + userId); 17466 } 17467 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17468 set, comp, userId); 17469 } 17470 17471 private @Nullable String getSetupWizardPackageName() { 17472 final Intent intent = new Intent(Intent.ACTION_MAIN); 17473 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17474 17475 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17476 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17477 | MATCH_DISABLED_COMPONENTS, 17478 UserHandle.myUserId()); 17479 if (matches.size() == 1) { 17480 return matches.get(0).getComponentInfo().packageName; 17481 } else { 17482 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17483 + ": matches=" + matches); 17484 return null; 17485 } 17486 } 17487 17488 @Override 17489 public void setApplicationEnabledSetting(String appPackageName, 17490 int newState, int flags, int userId, String callingPackage) { 17491 if (!sUserManager.exists(userId)) return; 17492 if (callingPackage == null) { 17493 callingPackage = Integer.toString(Binder.getCallingUid()); 17494 } 17495 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17496 } 17497 17498 @Override 17499 public void setComponentEnabledSetting(ComponentName componentName, 17500 int newState, int flags, int userId) { 17501 if (!sUserManager.exists(userId)) return; 17502 setEnabledSetting(componentName.getPackageName(), 17503 componentName.getClassName(), newState, flags, userId, null); 17504 } 17505 17506 private void setEnabledSetting(final String packageName, String className, int newState, 17507 final int flags, int userId, String callingPackage) { 17508 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17509 || newState == COMPONENT_ENABLED_STATE_ENABLED 17510 || newState == COMPONENT_ENABLED_STATE_DISABLED 17511 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17512 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17513 throw new IllegalArgumentException("Invalid new component state: " 17514 + newState); 17515 } 17516 PackageSetting pkgSetting; 17517 final int uid = Binder.getCallingUid(); 17518 final int permission; 17519 if (uid == Process.SYSTEM_UID) { 17520 permission = PackageManager.PERMISSION_GRANTED; 17521 } else { 17522 permission = mContext.checkCallingOrSelfPermission( 17523 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17524 } 17525 enforceCrossUserPermission(uid, userId, 17526 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17527 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17528 boolean sendNow = false; 17529 boolean isApp = (className == null); 17530 String componentName = isApp ? packageName : className; 17531 int packageUid = -1; 17532 ArrayList<String> components; 17533 17534 // writer 17535 synchronized (mPackages) { 17536 pkgSetting = mSettings.mPackages.get(packageName); 17537 if (pkgSetting == null) { 17538 if (className == null) { 17539 throw new IllegalArgumentException("Unknown package: " + packageName); 17540 } 17541 throw new IllegalArgumentException( 17542 "Unknown component: " + packageName + "/" + className); 17543 } 17544 } 17545 17546 // Limit who can change which apps 17547 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17548 // Don't allow apps that don't have permission to modify other apps 17549 if (!allowedByPermission) { 17550 throw new SecurityException( 17551 "Permission Denial: attempt to change component state from pid=" 17552 + Binder.getCallingPid() 17553 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17554 } 17555 // Don't allow changing profile and device owners. Calling into DPMS, so no locking. 17556 final DevicePolicyManagerInternal dpmi = LocalServices 17557 .getService(DevicePolicyManagerInternal.class); 17558 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17559 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17560 } 17561 } 17562 17563 synchronized (mPackages) { 17564 if (uid == Process.SHELL_UID) { 17565 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17566 int oldState = pkgSetting.getEnabled(userId); 17567 if (className == null 17568 && 17569 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17570 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17571 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17572 && 17573 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17574 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17575 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17576 // ok 17577 } else { 17578 throw new SecurityException( 17579 "Shell cannot change component state for " + packageName + "/" 17580 + className + " to " + newState); 17581 } 17582 } 17583 if (className == null) { 17584 // We're dealing with an application/package level state change 17585 if (pkgSetting.getEnabled(userId) == newState) { 17586 // Nothing to do 17587 return; 17588 } 17589 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17590 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17591 // Don't care about who enables an app. 17592 callingPackage = null; 17593 } 17594 pkgSetting.setEnabled(newState, userId, callingPackage); 17595 // pkgSetting.pkg.mSetEnabled = newState; 17596 } else { 17597 // We're dealing with a component level state change 17598 // First, verify that this is a valid class name. 17599 PackageParser.Package pkg = pkgSetting.pkg; 17600 if (pkg == null || !pkg.hasComponentClassName(className)) { 17601 if (pkg != null && 17602 pkg.applicationInfo.targetSdkVersion >= 17603 Build.VERSION_CODES.JELLY_BEAN) { 17604 throw new IllegalArgumentException("Component class " + className 17605 + " does not exist in " + packageName); 17606 } else { 17607 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17608 + className + " does not exist in " + packageName); 17609 } 17610 } 17611 switch (newState) { 17612 case COMPONENT_ENABLED_STATE_ENABLED: 17613 if (!pkgSetting.enableComponentLPw(className, userId)) { 17614 return; 17615 } 17616 break; 17617 case COMPONENT_ENABLED_STATE_DISABLED: 17618 if (!pkgSetting.disableComponentLPw(className, userId)) { 17619 return; 17620 } 17621 break; 17622 case COMPONENT_ENABLED_STATE_DEFAULT: 17623 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17624 return; 17625 } 17626 break; 17627 default: 17628 Slog.e(TAG, "Invalid new component state: " + newState); 17629 return; 17630 } 17631 } 17632 scheduleWritePackageRestrictionsLocked(userId); 17633 components = mPendingBroadcasts.get(userId, packageName); 17634 final boolean newPackage = components == null; 17635 if (newPackage) { 17636 components = new ArrayList<String>(); 17637 } 17638 if (!components.contains(componentName)) { 17639 components.add(componentName); 17640 } 17641 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17642 sendNow = true; 17643 // Purge entry from pending broadcast list if another one exists already 17644 // since we are sending one right away. 17645 mPendingBroadcasts.remove(userId, packageName); 17646 } else { 17647 if (newPackage) { 17648 mPendingBroadcasts.put(userId, packageName, components); 17649 } 17650 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17651 // Schedule a message 17652 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17653 } 17654 } 17655 } 17656 17657 long callingId = Binder.clearCallingIdentity(); 17658 try { 17659 if (sendNow) { 17660 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17661 sendPackageChangedBroadcast(packageName, 17662 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17663 } 17664 } finally { 17665 Binder.restoreCallingIdentity(callingId); 17666 } 17667 } 17668 17669 @Override 17670 public void flushPackageRestrictionsAsUser(int userId) { 17671 if (!sUserManager.exists(userId)) { 17672 return; 17673 } 17674 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17675 false /* checkShell */, "flushPackageRestrictions"); 17676 synchronized (mPackages) { 17677 mSettings.writePackageRestrictionsLPr(userId); 17678 mDirtyUsers.remove(userId); 17679 if (mDirtyUsers.isEmpty()) { 17680 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17681 } 17682 } 17683 } 17684 17685 private void sendPackageChangedBroadcast(String packageName, 17686 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17687 if (DEBUG_INSTALL) 17688 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17689 + componentNames); 17690 Bundle extras = new Bundle(4); 17691 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17692 String nameList[] = new String[componentNames.size()]; 17693 componentNames.toArray(nameList); 17694 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17695 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17696 extras.putInt(Intent.EXTRA_UID, packageUid); 17697 // If this is not reporting a change of the overall package, then only send it 17698 // to registered receivers. We don't want to launch a swath of apps for every 17699 // little component state change. 17700 final int flags = !componentNames.contains(packageName) 17701 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17702 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17703 new int[] {UserHandle.getUserId(packageUid)}); 17704 } 17705 17706 @Override 17707 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17708 if (!sUserManager.exists(userId)) return; 17709 final int uid = Binder.getCallingUid(); 17710 final int permission = mContext.checkCallingOrSelfPermission( 17711 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17712 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17713 enforceCrossUserPermission(uid, userId, 17714 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17715 // writer 17716 synchronized (mPackages) { 17717 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17718 allowedByPermission, uid, userId)) { 17719 scheduleWritePackageRestrictionsLocked(userId); 17720 } 17721 } 17722 } 17723 17724 @Override 17725 public String getInstallerPackageName(String packageName) { 17726 // reader 17727 synchronized (mPackages) { 17728 return mSettings.getInstallerPackageNameLPr(packageName); 17729 } 17730 } 17731 17732 public boolean isOrphaned(String packageName) { 17733 // reader 17734 synchronized (mPackages) { 17735 return mSettings.isOrphaned(packageName); 17736 } 17737 } 17738 17739 @Override 17740 public int getApplicationEnabledSetting(String packageName, int userId) { 17741 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17742 int uid = Binder.getCallingUid(); 17743 enforceCrossUserPermission(uid, userId, 17744 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17745 // reader 17746 synchronized (mPackages) { 17747 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17748 } 17749 } 17750 17751 @Override 17752 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17753 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17754 int uid = Binder.getCallingUid(); 17755 enforceCrossUserPermission(uid, userId, 17756 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17757 // reader 17758 synchronized (mPackages) { 17759 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17760 } 17761 } 17762 17763 @Override 17764 public void enterSafeMode() { 17765 enforceSystemOrRoot("Only the system can request entering safe mode"); 17766 17767 if (!mSystemReady) { 17768 mSafeMode = true; 17769 } 17770 } 17771 17772 @Override 17773 public void systemReady() { 17774 mSystemReady = true; 17775 17776 // Read the compatibilty setting when the system is ready. 17777 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17778 mContext.getContentResolver(), 17779 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17780 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17781 if (DEBUG_SETTINGS) { 17782 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17783 } 17784 17785 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17786 17787 synchronized (mPackages) { 17788 // Verify that all of the preferred activity components actually 17789 // exist. It is possible for applications to be updated and at 17790 // that point remove a previously declared activity component that 17791 // had been set as a preferred activity. We try to clean this up 17792 // the next time we encounter that preferred activity, but it is 17793 // possible for the user flow to never be able to return to that 17794 // situation so here we do a sanity check to make sure we haven't 17795 // left any junk around. 17796 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17797 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17798 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17799 removed.clear(); 17800 for (PreferredActivity pa : pir.filterSet()) { 17801 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17802 removed.add(pa); 17803 } 17804 } 17805 if (removed.size() > 0) { 17806 for (int r=0; r<removed.size(); r++) { 17807 PreferredActivity pa = removed.get(r); 17808 Slog.w(TAG, "Removing dangling preferred activity: " 17809 + pa.mPref.mComponent); 17810 pir.removeFilter(pa); 17811 } 17812 mSettings.writePackageRestrictionsLPr( 17813 mSettings.mPreferredActivities.keyAt(i)); 17814 } 17815 } 17816 17817 for (int userId : UserManagerService.getInstance().getUserIds()) { 17818 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17819 grantPermissionsUserIds = ArrayUtils.appendInt( 17820 grantPermissionsUserIds, userId); 17821 } 17822 } 17823 } 17824 sUserManager.systemReady(); 17825 17826 // If we upgraded grant all default permissions before kicking off. 17827 for (int userId : grantPermissionsUserIds) { 17828 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17829 } 17830 17831 // Kick off any messages waiting for system ready 17832 if (mPostSystemReadyMessages != null) { 17833 for (Message msg : mPostSystemReadyMessages) { 17834 msg.sendToTarget(); 17835 } 17836 mPostSystemReadyMessages = null; 17837 } 17838 17839 // Watch for external volumes that come and go over time 17840 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17841 storage.registerListener(mStorageListener); 17842 17843 mInstallerService.systemReady(); 17844 mPackageDexOptimizer.systemReady(); 17845 17846 MountServiceInternal mountServiceInternal = LocalServices.getService( 17847 MountServiceInternal.class); 17848 mountServiceInternal.addExternalStoragePolicy( 17849 new MountServiceInternal.ExternalStorageMountPolicy() { 17850 @Override 17851 public int getMountMode(int uid, String packageName) { 17852 if (Process.isIsolated(uid)) { 17853 return Zygote.MOUNT_EXTERNAL_NONE; 17854 } 17855 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17856 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17857 } 17858 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17859 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17860 } 17861 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17862 return Zygote.MOUNT_EXTERNAL_READ; 17863 } 17864 return Zygote.MOUNT_EXTERNAL_WRITE; 17865 } 17866 17867 @Override 17868 public boolean hasExternalStorage(int uid, String packageName) { 17869 return true; 17870 } 17871 }); 17872 17873 // Now that we're mostly running, clean up stale users and apps 17874 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17875 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17876 } 17877 17878 @Override 17879 public boolean isSafeMode() { 17880 return mSafeMode; 17881 } 17882 17883 @Override 17884 public boolean hasSystemUidErrors() { 17885 return mHasSystemUidErrors; 17886 } 17887 17888 static String arrayToString(int[] array) { 17889 StringBuffer buf = new StringBuffer(128); 17890 buf.append('['); 17891 if (array != null) { 17892 for (int i=0; i<array.length; i++) { 17893 if (i > 0) buf.append(", "); 17894 buf.append(array[i]); 17895 } 17896 } 17897 buf.append(']'); 17898 return buf.toString(); 17899 } 17900 17901 static class DumpState { 17902 public static final int DUMP_LIBS = 1 << 0; 17903 public static final int DUMP_FEATURES = 1 << 1; 17904 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17905 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17906 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17907 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17908 public static final int DUMP_PERMISSIONS = 1 << 6; 17909 public static final int DUMP_PACKAGES = 1 << 7; 17910 public static final int DUMP_SHARED_USERS = 1 << 8; 17911 public static final int DUMP_MESSAGES = 1 << 9; 17912 public static final int DUMP_PROVIDERS = 1 << 10; 17913 public static final int DUMP_VERIFIERS = 1 << 11; 17914 public static final int DUMP_PREFERRED = 1 << 12; 17915 public static final int DUMP_PREFERRED_XML = 1 << 13; 17916 public static final int DUMP_KEYSETS = 1 << 14; 17917 public static final int DUMP_VERSION = 1 << 15; 17918 public static final int DUMP_INSTALLS = 1 << 16; 17919 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17920 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17921 public static final int DUMP_FROZEN = 1 << 19; 17922 public static final int DUMP_DEXOPT = 1 << 20; 17923 17924 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17925 17926 private int mTypes; 17927 17928 private int mOptions; 17929 17930 private boolean mTitlePrinted; 17931 17932 private SharedUserSetting mSharedUser; 17933 17934 public boolean isDumping(int type) { 17935 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17936 return true; 17937 } 17938 17939 return (mTypes & type) != 0; 17940 } 17941 17942 public void setDump(int type) { 17943 mTypes |= type; 17944 } 17945 17946 public boolean isOptionEnabled(int option) { 17947 return (mOptions & option) != 0; 17948 } 17949 17950 public void setOptionEnabled(int option) { 17951 mOptions |= option; 17952 } 17953 17954 public boolean onTitlePrinted() { 17955 final boolean printed = mTitlePrinted; 17956 mTitlePrinted = true; 17957 return printed; 17958 } 17959 17960 public boolean getTitlePrinted() { 17961 return mTitlePrinted; 17962 } 17963 17964 public void setTitlePrinted(boolean enabled) { 17965 mTitlePrinted = enabled; 17966 } 17967 17968 public SharedUserSetting getSharedUser() { 17969 return mSharedUser; 17970 } 17971 17972 public void setSharedUser(SharedUserSetting user) { 17973 mSharedUser = user; 17974 } 17975 } 17976 17977 @Override 17978 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17979 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17980 (new PackageManagerShellCommand(this)).exec( 17981 this, in, out, err, args, resultReceiver); 17982 } 17983 17984 @Override 17985 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17986 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17987 != PackageManager.PERMISSION_GRANTED) { 17988 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17989 + Binder.getCallingPid() 17990 + ", uid=" + Binder.getCallingUid() 17991 + " without permission " 17992 + android.Manifest.permission.DUMP); 17993 return; 17994 } 17995 17996 DumpState dumpState = new DumpState(); 17997 boolean fullPreferred = false; 17998 boolean checkin = false; 17999 18000 String packageName = null; 18001 ArraySet<String> permissionNames = null; 18002 18003 int opti = 0; 18004 while (opti < args.length) { 18005 String opt = args[opti]; 18006 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18007 break; 18008 } 18009 opti++; 18010 18011 if ("-a".equals(opt)) { 18012 // Right now we only know how to print all. 18013 } else if ("-h".equals(opt)) { 18014 pw.println("Package manager dump options:"); 18015 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18016 pw.println(" --checkin: dump for a checkin"); 18017 pw.println(" -f: print details of intent filters"); 18018 pw.println(" -h: print this help"); 18019 pw.println(" cmd may be one of:"); 18020 pw.println(" l[ibraries]: list known shared libraries"); 18021 pw.println(" f[eatures]: list device features"); 18022 pw.println(" k[eysets]: print known keysets"); 18023 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18024 pw.println(" perm[issions]: dump permissions"); 18025 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18026 pw.println(" pref[erred]: print preferred package settings"); 18027 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18028 pw.println(" prov[iders]: dump content providers"); 18029 pw.println(" p[ackages]: dump installed packages"); 18030 pw.println(" s[hared-users]: dump shared user IDs"); 18031 pw.println(" m[essages]: print collected runtime messages"); 18032 pw.println(" v[erifiers]: print package verifier info"); 18033 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18034 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18035 pw.println(" version: print database version info"); 18036 pw.println(" write: write current settings now"); 18037 pw.println(" installs: details about install sessions"); 18038 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18039 pw.println(" dexopt: dump dexopt state"); 18040 pw.println(" <package.name>: info about given package"); 18041 return; 18042 } else if ("--checkin".equals(opt)) { 18043 checkin = true; 18044 } else if ("-f".equals(opt)) { 18045 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18046 } else { 18047 pw.println("Unknown argument: " + opt + "; use -h for help"); 18048 } 18049 } 18050 18051 // Is the caller requesting to dump a particular piece of data? 18052 if (opti < args.length) { 18053 String cmd = args[opti]; 18054 opti++; 18055 // Is this a package name? 18056 if ("android".equals(cmd) || cmd.contains(".")) { 18057 packageName = cmd; 18058 // When dumping a single package, we always dump all of its 18059 // filter information since the amount of data will be reasonable. 18060 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18061 } else if ("check-permission".equals(cmd)) { 18062 if (opti >= args.length) { 18063 pw.println("Error: check-permission missing permission argument"); 18064 return; 18065 } 18066 String perm = args[opti]; 18067 opti++; 18068 if (opti >= args.length) { 18069 pw.println("Error: check-permission missing package argument"); 18070 return; 18071 } 18072 String pkg = args[opti]; 18073 opti++; 18074 int user = UserHandle.getUserId(Binder.getCallingUid()); 18075 if (opti < args.length) { 18076 try { 18077 user = Integer.parseInt(args[opti]); 18078 } catch (NumberFormatException e) { 18079 pw.println("Error: check-permission user argument is not a number: " 18080 + args[opti]); 18081 return; 18082 } 18083 } 18084 pw.println(checkPermission(perm, pkg, user)); 18085 return; 18086 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18087 dumpState.setDump(DumpState.DUMP_LIBS); 18088 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18089 dumpState.setDump(DumpState.DUMP_FEATURES); 18090 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18091 if (opti >= args.length) { 18092 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18093 | DumpState.DUMP_SERVICE_RESOLVERS 18094 | DumpState.DUMP_RECEIVER_RESOLVERS 18095 | DumpState.DUMP_CONTENT_RESOLVERS); 18096 } else { 18097 while (opti < args.length) { 18098 String name = args[opti]; 18099 if ("a".equals(name) || "activity".equals(name)) { 18100 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18101 } else if ("s".equals(name) || "service".equals(name)) { 18102 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18103 } else if ("r".equals(name) || "receiver".equals(name)) { 18104 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18105 } else if ("c".equals(name) || "content".equals(name)) { 18106 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18107 } else { 18108 pw.println("Error: unknown resolver table type: " + name); 18109 return; 18110 } 18111 opti++; 18112 } 18113 } 18114 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18115 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18116 } else if ("permission".equals(cmd)) { 18117 if (opti >= args.length) { 18118 pw.println("Error: permission requires permission name"); 18119 return; 18120 } 18121 permissionNames = new ArraySet<>(); 18122 while (opti < args.length) { 18123 permissionNames.add(args[opti]); 18124 opti++; 18125 } 18126 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18127 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18128 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18129 dumpState.setDump(DumpState.DUMP_PREFERRED); 18130 } else if ("preferred-xml".equals(cmd)) { 18131 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18132 if (opti < args.length && "--full".equals(args[opti])) { 18133 fullPreferred = true; 18134 opti++; 18135 } 18136 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18137 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18138 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18139 dumpState.setDump(DumpState.DUMP_PACKAGES); 18140 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18141 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18142 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18143 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18144 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18145 dumpState.setDump(DumpState.DUMP_MESSAGES); 18146 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18147 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18148 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18149 || "intent-filter-verifiers".equals(cmd)) { 18150 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18151 } else if ("version".equals(cmd)) { 18152 dumpState.setDump(DumpState.DUMP_VERSION); 18153 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18154 dumpState.setDump(DumpState.DUMP_KEYSETS); 18155 } else if ("installs".equals(cmd)) { 18156 dumpState.setDump(DumpState.DUMP_INSTALLS); 18157 } else if ("frozen".equals(cmd)) { 18158 dumpState.setDump(DumpState.DUMP_FROZEN); 18159 } else if ("dexopt".equals(cmd)) { 18160 dumpState.setDump(DumpState.DUMP_DEXOPT); 18161 } else if ("write".equals(cmd)) { 18162 synchronized (mPackages) { 18163 mSettings.writeLPr(); 18164 pw.println("Settings written."); 18165 return; 18166 } 18167 } 18168 } 18169 18170 if (checkin) { 18171 pw.println("vers,1"); 18172 } 18173 18174 // reader 18175 synchronized (mPackages) { 18176 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18177 if (!checkin) { 18178 if (dumpState.onTitlePrinted()) 18179 pw.println(); 18180 pw.println("Database versions:"); 18181 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18182 } 18183 } 18184 18185 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18186 if (!checkin) { 18187 if (dumpState.onTitlePrinted()) 18188 pw.println(); 18189 pw.println("Verifiers:"); 18190 pw.print(" Required: "); 18191 pw.print(mRequiredVerifierPackage); 18192 pw.print(" (uid="); 18193 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18194 UserHandle.USER_SYSTEM)); 18195 pw.println(")"); 18196 } else if (mRequiredVerifierPackage != null) { 18197 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18198 pw.print(","); 18199 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18200 UserHandle.USER_SYSTEM)); 18201 } 18202 } 18203 18204 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18205 packageName == null) { 18206 if (mIntentFilterVerifierComponent != null) { 18207 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18208 if (!checkin) { 18209 if (dumpState.onTitlePrinted()) 18210 pw.println(); 18211 pw.println("Intent Filter Verifier:"); 18212 pw.print(" Using: "); 18213 pw.print(verifierPackageName); 18214 pw.print(" (uid="); 18215 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18216 UserHandle.USER_SYSTEM)); 18217 pw.println(")"); 18218 } else if (verifierPackageName != null) { 18219 pw.print("ifv,"); pw.print(verifierPackageName); 18220 pw.print(","); 18221 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18222 UserHandle.USER_SYSTEM)); 18223 } 18224 } else { 18225 pw.println(); 18226 pw.println("No Intent Filter Verifier available!"); 18227 } 18228 } 18229 18230 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18231 boolean printedHeader = false; 18232 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18233 while (it.hasNext()) { 18234 String name = it.next(); 18235 SharedLibraryEntry ent = mSharedLibraries.get(name); 18236 if (!checkin) { 18237 if (!printedHeader) { 18238 if (dumpState.onTitlePrinted()) 18239 pw.println(); 18240 pw.println("Libraries:"); 18241 printedHeader = true; 18242 } 18243 pw.print(" "); 18244 } else { 18245 pw.print("lib,"); 18246 } 18247 pw.print(name); 18248 if (!checkin) { 18249 pw.print(" -> "); 18250 } 18251 if (ent.path != null) { 18252 if (!checkin) { 18253 pw.print("(jar) "); 18254 pw.print(ent.path); 18255 } else { 18256 pw.print(",jar,"); 18257 pw.print(ent.path); 18258 } 18259 } else { 18260 if (!checkin) { 18261 pw.print("(apk) "); 18262 pw.print(ent.apk); 18263 } else { 18264 pw.print(",apk,"); 18265 pw.print(ent.apk); 18266 } 18267 } 18268 pw.println(); 18269 } 18270 } 18271 18272 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18273 if (dumpState.onTitlePrinted()) 18274 pw.println(); 18275 if (!checkin) { 18276 pw.println("Features:"); 18277 } 18278 18279 for (FeatureInfo feat : mAvailableFeatures.values()) { 18280 if (checkin) { 18281 pw.print("feat,"); 18282 pw.print(feat.name); 18283 pw.print(","); 18284 pw.println(feat.version); 18285 } else { 18286 pw.print(" "); 18287 pw.print(feat.name); 18288 if (feat.version > 0) { 18289 pw.print(" version="); 18290 pw.print(feat.version); 18291 } 18292 pw.println(); 18293 } 18294 } 18295 } 18296 18297 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18298 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18299 : "Activity Resolver Table:", " ", packageName, 18300 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18301 dumpState.setTitlePrinted(true); 18302 } 18303 } 18304 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18305 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18306 : "Receiver Resolver Table:", " ", packageName, 18307 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18308 dumpState.setTitlePrinted(true); 18309 } 18310 } 18311 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18312 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18313 : "Service Resolver Table:", " ", packageName, 18314 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18315 dumpState.setTitlePrinted(true); 18316 } 18317 } 18318 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18319 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18320 : "Provider Resolver Table:", " ", packageName, 18321 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18322 dumpState.setTitlePrinted(true); 18323 } 18324 } 18325 18326 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18327 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18328 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18329 int user = mSettings.mPreferredActivities.keyAt(i); 18330 if (pir.dump(pw, 18331 dumpState.getTitlePrinted() 18332 ? "\nPreferred Activities User " + user + ":" 18333 : "Preferred Activities User " + user + ":", " ", 18334 packageName, true, false)) { 18335 dumpState.setTitlePrinted(true); 18336 } 18337 } 18338 } 18339 18340 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18341 pw.flush(); 18342 FileOutputStream fout = new FileOutputStream(fd); 18343 BufferedOutputStream str = new BufferedOutputStream(fout); 18344 XmlSerializer serializer = new FastXmlSerializer(); 18345 try { 18346 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18347 serializer.startDocument(null, true); 18348 serializer.setFeature( 18349 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18350 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18351 serializer.endDocument(); 18352 serializer.flush(); 18353 } catch (IllegalArgumentException e) { 18354 pw.println("Failed writing: " + e); 18355 } catch (IllegalStateException e) { 18356 pw.println("Failed writing: " + e); 18357 } catch (IOException e) { 18358 pw.println("Failed writing: " + e); 18359 } 18360 } 18361 18362 if (!checkin 18363 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18364 && packageName == null) { 18365 pw.println(); 18366 int count = mSettings.mPackages.size(); 18367 if (count == 0) { 18368 pw.println("No applications!"); 18369 pw.println(); 18370 } else { 18371 final String prefix = " "; 18372 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18373 if (allPackageSettings.size() == 0) { 18374 pw.println("No domain preferred apps!"); 18375 pw.println(); 18376 } else { 18377 pw.println("App verification status:"); 18378 pw.println(); 18379 count = 0; 18380 for (PackageSetting ps : allPackageSettings) { 18381 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18382 if (ivi == null || ivi.getPackageName() == null) continue; 18383 pw.println(prefix + "Package: " + ivi.getPackageName()); 18384 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18385 pw.println(prefix + "Status: " + ivi.getStatusString()); 18386 pw.println(); 18387 count++; 18388 } 18389 if (count == 0) { 18390 pw.println(prefix + "No app verification established."); 18391 pw.println(); 18392 } 18393 for (int userId : sUserManager.getUserIds()) { 18394 pw.println("App linkages for user " + userId + ":"); 18395 pw.println(); 18396 count = 0; 18397 for (PackageSetting ps : allPackageSettings) { 18398 final long status = ps.getDomainVerificationStatusForUser(userId); 18399 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18400 continue; 18401 } 18402 pw.println(prefix + "Package: " + ps.name); 18403 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18404 String statusStr = IntentFilterVerificationInfo. 18405 getStatusStringFromValue(status); 18406 pw.println(prefix + "Status: " + statusStr); 18407 pw.println(); 18408 count++; 18409 } 18410 if (count == 0) { 18411 pw.println(prefix + "No configured app linkages."); 18412 pw.println(); 18413 } 18414 } 18415 } 18416 } 18417 } 18418 18419 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18420 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18421 if (packageName == null && permissionNames == null) { 18422 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18423 if (iperm == 0) { 18424 if (dumpState.onTitlePrinted()) 18425 pw.println(); 18426 pw.println("AppOp Permissions:"); 18427 } 18428 pw.print(" AppOp Permission "); 18429 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18430 pw.println(":"); 18431 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18432 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18433 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18434 } 18435 } 18436 } 18437 } 18438 18439 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18440 boolean printedSomething = false; 18441 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18442 if (packageName != null && !packageName.equals(p.info.packageName)) { 18443 continue; 18444 } 18445 if (!printedSomething) { 18446 if (dumpState.onTitlePrinted()) 18447 pw.println(); 18448 pw.println("Registered ContentProviders:"); 18449 printedSomething = true; 18450 } 18451 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18452 pw.print(" "); pw.println(p.toString()); 18453 } 18454 printedSomething = false; 18455 for (Map.Entry<String, PackageParser.Provider> entry : 18456 mProvidersByAuthority.entrySet()) { 18457 PackageParser.Provider p = entry.getValue(); 18458 if (packageName != null && !packageName.equals(p.info.packageName)) { 18459 continue; 18460 } 18461 if (!printedSomething) { 18462 if (dumpState.onTitlePrinted()) 18463 pw.println(); 18464 pw.println("ContentProvider Authorities:"); 18465 printedSomething = true; 18466 } 18467 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18468 pw.print(" "); pw.println(p.toString()); 18469 if (p.info != null && p.info.applicationInfo != null) { 18470 final String appInfo = p.info.applicationInfo.toString(); 18471 pw.print(" applicationInfo="); pw.println(appInfo); 18472 } 18473 } 18474 } 18475 18476 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18477 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18478 } 18479 18480 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18481 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18482 } 18483 18484 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18485 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18486 } 18487 18488 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18489 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18490 } 18491 18492 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18493 // XXX should handle packageName != null by dumping only install data that 18494 // the given package is involved with. 18495 if (dumpState.onTitlePrinted()) pw.println(); 18496 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18497 } 18498 18499 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18500 // XXX should handle packageName != null by dumping only install data that 18501 // the given package is involved with. 18502 if (dumpState.onTitlePrinted()) pw.println(); 18503 18504 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18505 ipw.println(); 18506 ipw.println("Frozen packages:"); 18507 ipw.increaseIndent(); 18508 if (mFrozenPackages.size() == 0) { 18509 ipw.println("(none)"); 18510 } else { 18511 for (int i = 0; i < mFrozenPackages.size(); i++) { 18512 ipw.println(mFrozenPackages.valueAt(i)); 18513 } 18514 } 18515 ipw.decreaseIndent(); 18516 } 18517 18518 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18519 if (dumpState.onTitlePrinted()) pw.println(); 18520 dumpDexoptStateLPr(pw, packageName); 18521 } 18522 18523 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18524 if (dumpState.onTitlePrinted()) pw.println(); 18525 mSettings.dumpReadMessagesLPr(pw, dumpState); 18526 18527 pw.println(); 18528 pw.println("Package warning messages:"); 18529 BufferedReader in = null; 18530 String line = null; 18531 try { 18532 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18533 while ((line = in.readLine()) != null) { 18534 if (line.contains("ignored: updated version")) continue; 18535 pw.println(line); 18536 } 18537 } catch (IOException ignored) { 18538 } finally { 18539 IoUtils.closeQuietly(in); 18540 } 18541 } 18542 18543 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18544 BufferedReader in = null; 18545 String line = null; 18546 try { 18547 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18548 while ((line = in.readLine()) != null) { 18549 if (line.contains("ignored: updated version")) continue; 18550 pw.print("msg,"); 18551 pw.println(line); 18552 } 18553 } catch (IOException ignored) { 18554 } finally { 18555 IoUtils.closeQuietly(in); 18556 } 18557 } 18558 } 18559 } 18560 18561 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18562 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18563 ipw.println(); 18564 ipw.println("Dexopt state:"); 18565 ipw.increaseIndent(); 18566 Collection<PackageParser.Package> packages = null; 18567 if (packageName != null) { 18568 PackageParser.Package targetPackage = mPackages.get(packageName); 18569 if (targetPackage != null) { 18570 packages = Collections.singletonList(targetPackage); 18571 } else { 18572 ipw.println("Unable to find package: " + packageName); 18573 return; 18574 } 18575 } else { 18576 packages = mPackages.values(); 18577 } 18578 18579 for (PackageParser.Package pkg : packages) { 18580 ipw.println("[" + pkg.packageName + "]"); 18581 ipw.increaseIndent(); 18582 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18583 ipw.decreaseIndent(); 18584 } 18585 } 18586 18587 private String dumpDomainString(String packageName) { 18588 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18589 .getList(); 18590 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18591 18592 ArraySet<String> result = new ArraySet<>(); 18593 if (iviList.size() > 0) { 18594 for (IntentFilterVerificationInfo ivi : iviList) { 18595 for (String host : ivi.getDomains()) { 18596 result.add(host); 18597 } 18598 } 18599 } 18600 if (filters != null && filters.size() > 0) { 18601 for (IntentFilter filter : filters) { 18602 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18603 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18604 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18605 result.addAll(filter.getHostsList()); 18606 } 18607 } 18608 } 18609 18610 StringBuilder sb = new StringBuilder(result.size() * 16); 18611 for (String domain : result) { 18612 if (sb.length() > 0) sb.append(" "); 18613 sb.append(domain); 18614 } 18615 return sb.toString(); 18616 } 18617 18618 // ------- apps on sdcard specific code ------- 18619 static final boolean DEBUG_SD_INSTALL = false; 18620 18621 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18622 18623 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18624 18625 private boolean mMediaMounted = false; 18626 18627 static String getEncryptKey() { 18628 try { 18629 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18630 SD_ENCRYPTION_KEYSTORE_NAME); 18631 if (sdEncKey == null) { 18632 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18633 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18634 if (sdEncKey == null) { 18635 Slog.e(TAG, "Failed to create encryption keys"); 18636 return null; 18637 } 18638 } 18639 return sdEncKey; 18640 } catch (NoSuchAlgorithmException nsae) { 18641 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18642 return null; 18643 } catch (IOException ioe) { 18644 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18645 return null; 18646 } 18647 } 18648 18649 /* 18650 * Update media status on PackageManager. 18651 */ 18652 @Override 18653 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18654 int callingUid = Binder.getCallingUid(); 18655 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18656 throw new SecurityException("Media status can only be updated by the system"); 18657 } 18658 // reader; this apparently protects mMediaMounted, but should probably 18659 // be a different lock in that case. 18660 synchronized (mPackages) { 18661 Log.i(TAG, "Updating external media status from " 18662 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18663 + (mediaStatus ? "mounted" : "unmounted")); 18664 if (DEBUG_SD_INSTALL) 18665 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18666 + ", mMediaMounted=" + mMediaMounted); 18667 if (mediaStatus == mMediaMounted) { 18668 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18669 : 0, -1); 18670 mHandler.sendMessage(msg); 18671 return; 18672 } 18673 mMediaMounted = mediaStatus; 18674 } 18675 // Queue up an async operation since the package installation may take a 18676 // little while. 18677 mHandler.post(new Runnable() { 18678 public void run() { 18679 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18680 } 18681 }); 18682 } 18683 18684 /** 18685 * Called by MountService when the initial ASECs to scan are available. 18686 * Should block until all the ASEC containers are finished being scanned. 18687 */ 18688 public void scanAvailableAsecs() { 18689 updateExternalMediaStatusInner(true, false, false); 18690 } 18691 18692 /* 18693 * Collect information of applications on external media, map them against 18694 * existing containers and update information based on current mount status. 18695 * Please note that we always have to report status if reportStatus has been 18696 * set to true especially when unloading packages. 18697 */ 18698 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18699 boolean externalStorage) { 18700 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18701 int[] uidArr = EmptyArray.INT; 18702 18703 final String[] list = PackageHelper.getSecureContainerList(); 18704 if (ArrayUtils.isEmpty(list)) { 18705 Log.i(TAG, "No secure containers found"); 18706 } else { 18707 // Process list of secure containers and categorize them 18708 // as active or stale based on their package internal state. 18709 18710 // reader 18711 synchronized (mPackages) { 18712 for (String cid : list) { 18713 // Leave stages untouched for now; installer service owns them 18714 if (PackageInstallerService.isStageName(cid)) continue; 18715 18716 if (DEBUG_SD_INSTALL) 18717 Log.i(TAG, "Processing container " + cid); 18718 String pkgName = getAsecPackageName(cid); 18719 if (pkgName == null) { 18720 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18721 continue; 18722 } 18723 if (DEBUG_SD_INSTALL) 18724 Log.i(TAG, "Looking for pkg : " + pkgName); 18725 18726 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18727 if (ps == null) { 18728 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18729 continue; 18730 } 18731 18732 /* 18733 * Skip packages that are not external if we're unmounting 18734 * external storage. 18735 */ 18736 if (externalStorage && !isMounted && !isExternal(ps)) { 18737 continue; 18738 } 18739 18740 final AsecInstallArgs args = new AsecInstallArgs(cid, 18741 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18742 // The package status is changed only if the code path 18743 // matches between settings and the container id. 18744 if (ps.codePathString != null 18745 && ps.codePathString.startsWith(args.getCodePath())) { 18746 if (DEBUG_SD_INSTALL) { 18747 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18748 + " at code path: " + ps.codePathString); 18749 } 18750 18751 // We do have a valid package installed on sdcard 18752 processCids.put(args, ps.codePathString); 18753 final int uid = ps.appId; 18754 if (uid != -1) { 18755 uidArr = ArrayUtils.appendInt(uidArr, uid); 18756 } 18757 } else { 18758 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18759 + ps.codePathString); 18760 } 18761 } 18762 } 18763 18764 Arrays.sort(uidArr); 18765 } 18766 18767 // Process packages with valid entries. 18768 if (isMounted) { 18769 if (DEBUG_SD_INSTALL) 18770 Log.i(TAG, "Loading packages"); 18771 loadMediaPackages(processCids, uidArr, externalStorage); 18772 startCleaningPackages(); 18773 mInstallerService.onSecureContainersAvailable(); 18774 } else { 18775 if (DEBUG_SD_INSTALL) 18776 Log.i(TAG, "Unloading packages"); 18777 unloadMediaPackages(processCids, uidArr, reportStatus); 18778 } 18779 } 18780 18781 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18782 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18783 final int size = infos.size(); 18784 final String[] packageNames = new String[size]; 18785 final int[] packageUids = new int[size]; 18786 for (int i = 0; i < size; i++) { 18787 final ApplicationInfo info = infos.get(i); 18788 packageNames[i] = info.packageName; 18789 packageUids[i] = info.uid; 18790 } 18791 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18792 finishedReceiver); 18793 } 18794 18795 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18796 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18797 sendResourcesChangedBroadcast(mediaStatus, replacing, 18798 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18799 } 18800 18801 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18802 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18803 int size = pkgList.length; 18804 if (size > 0) { 18805 // Send broadcasts here 18806 Bundle extras = new Bundle(); 18807 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18808 if (uidArr != null) { 18809 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18810 } 18811 if (replacing) { 18812 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18813 } 18814 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18815 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18816 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18817 } 18818 } 18819 18820 /* 18821 * Look at potentially valid container ids from processCids If package 18822 * information doesn't match the one on record or package scanning fails, 18823 * the cid is added to list of removeCids. We currently don't delete stale 18824 * containers. 18825 */ 18826 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18827 boolean externalStorage) { 18828 ArrayList<String> pkgList = new ArrayList<String>(); 18829 Set<AsecInstallArgs> keys = processCids.keySet(); 18830 18831 for (AsecInstallArgs args : keys) { 18832 String codePath = processCids.get(args); 18833 if (DEBUG_SD_INSTALL) 18834 Log.i(TAG, "Loading container : " + args.cid); 18835 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18836 try { 18837 // Make sure there are no container errors first. 18838 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18839 Slog.e(TAG, "Failed to mount cid : " + args.cid 18840 + " when installing from sdcard"); 18841 continue; 18842 } 18843 // Check code path here. 18844 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18845 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18846 + " does not match one in settings " + codePath); 18847 continue; 18848 } 18849 // Parse package 18850 int parseFlags = mDefParseFlags; 18851 if (args.isExternalAsec()) { 18852 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18853 } 18854 if (args.isFwdLocked()) { 18855 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18856 } 18857 18858 synchronized (mInstallLock) { 18859 PackageParser.Package pkg = null; 18860 try { 18861 // Sadly we don't know the package name yet to freeze it 18862 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18863 SCAN_IGNORE_FROZEN, 0, null); 18864 } catch (PackageManagerException e) { 18865 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18866 } 18867 // Scan the package 18868 if (pkg != null) { 18869 /* 18870 * TODO why is the lock being held? doPostInstall is 18871 * called in other places without the lock. This needs 18872 * to be straightened out. 18873 */ 18874 // writer 18875 synchronized (mPackages) { 18876 retCode = PackageManager.INSTALL_SUCCEEDED; 18877 pkgList.add(pkg.packageName); 18878 // Post process args 18879 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18880 pkg.applicationInfo.uid); 18881 } 18882 } else { 18883 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18884 } 18885 } 18886 18887 } finally { 18888 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18889 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18890 } 18891 } 18892 } 18893 // writer 18894 synchronized (mPackages) { 18895 // If the platform SDK has changed since the last time we booted, 18896 // we need to re-grant app permission to catch any new ones that 18897 // appear. This is really a hack, and means that apps can in some 18898 // cases get permissions that the user didn't initially explicitly 18899 // allow... it would be nice to have some better way to handle 18900 // this situation. 18901 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18902 : mSettings.getInternalVersion(); 18903 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18904 : StorageManager.UUID_PRIVATE_INTERNAL; 18905 18906 int updateFlags = UPDATE_PERMISSIONS_ALL; 18907 if (ver.sdkVersion != mSdkVersion) { 18908 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18909 + mSdkVersion + "; regranting permissions for external"); 18910 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18911 } 18912 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18913 18914 // Yay, everything is now upgraded 18915 ver.forceCurrent(); 18916 18917 // can downgrade to reader 18918 // Persist settings 18919 mSettings.writeLPr(); 18920 } 18921 // Send a broadcast to let everyone know we are done processing 18922 if (pkgList.size() > 0) { 18923 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18924 } 18925 } 18926 18927 /* 18928 * Utility method to unload a list of specified containers 18929 */ 18930 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18931 // Just unmount all valid containers. 18932 for (AsecInstallArgs arg : cidArgs) { 18933 synchronized (mInstallLock) { 18934 arg.doPostDeleteLI(false); 18935 } 18936 } 18937 } 18938 18939 /* 18940 * Unload packages mounted on external media. This involves deleting package 18941 * data from internal structures, sending broadcasts about disabled packages, 18942 * gc'ing to free up references, unmounting all secure containers 18943 * corresponding to packages on external media, and posting a 18944 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18945 * that we always have to post this message if status has been requested no 18946 * matter what. 18947 */ 18948 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18949 final boolean reportStatus) { 18950 if (DEBUG_SD_INSTALL) 18951 Log.i(TAG, "unloading media packages"); 18952 ArrayList<String> pkgList = new ArrayList<String>(); 18953 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18954 final Set<AsecInstallArgs> keys = processCids.keySet(); 18955 for (AsecInstallArgs args : keys) { 18956 String pkgName = args.getPackageName(); 18957 if (DEBUG_SD_INSTALL) 18958 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18959 // Delete package internally 18960 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18961 synchronized (mInstallLock) { 18962 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18963 final boolean res; 18964 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18965 "unloadMediaPackages")) { 18966 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18967 null); 18968 } 18969 if (res) { 18970 pkgList.add(pkgName); 18971 } else { 18972 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18973 failedList.add(args); 18974 } 18975 } 18976 } 18977 18978 // reader 18979 synchronized (mPackages) { 18980 // We didn't update the settings after removing each package; 18981 // write them now for all packages. 18982 mSettings.writeLPr(); 18983 } 18984 18985 // We have to absolutely send UPDATED_MEDIA_STATUS only 18986 // after confirming that all the receivers processed the ordered 18987 // broadcast when packages get disabled, force a gc to clean things up. 18988 // and unload all the containers. 18989 if (pkgList.size() > 0) { 18990 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18991 new IIntentReceiver.Stub() { 18992 public void performReceive(Intent intent, int resultCode, String data, 18993 Bundle extras, boolean ordered, boolean sticky, 18994 int sendingUser) throws RemoteException { 18995 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18996 reportStatus ? 1 : 0, 1, keys); 18997 mHandler.sendMessage(msg); 18998 } 18999 }); 19000 } else { 19001 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19002 keys); 19003 mHandler.sendMessage(msg); 19004 } 19005 } 19006 19007 private void loadPrivatePackages(final VolumeInfo vol) { 19008 mHandler.post(new Runnable() { 19009 @Override 19010 public void run() { 19011 loadPrivatePackagesInner(vol); 19012 } 19013 }); 19014 } 19015 19016 private void loadPrivatePackagesInner(VolumeInfo vol) { 19017 final String volumeUuid = vol.fsUuid; 19018 if (TextUtils.isEmpty(volumeUuid)) { 19019 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19020 return; 19021 } 19022 19023 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19024 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19025 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19026 19027 final VersionInfo ver; 19028 final List<PackageSetting> packages; 19029 synchronized (mPackages) { 19030 ver = mSettings.findOrCreateVersion(volumeUuid); 19031 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19032 } 19033 19034 for (PackageSetting ps : packages) { 19035 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19036 synchronized (mInstallLock) { 19037 final PackageParser.Package pkg; 19038 try { 19039 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19040 loaded.add(pkg.applicationInfo); 19041 19042 } catch (PackageManagerException e) { 19043 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19044 } 19045 19046 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19047 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19048 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19049 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19050 } 19051 } 19052 } 19053 19054 // Reconcile app data for all started/unlocked users 19055 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19056 final UserManager um = mContext.getSystemService(UserManager.class); 19057 UserManagerInternal umInternal = getUserManagerInternal(); 19058 for (UserInfo user : um.getUsers()) { 19059 final int flags; 19060 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19061 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19062 } else if (umInternal.isUserRunning(user.id)) { 19063 flags = StorageManager.FLAG_STORAGE_DE; 19064 } else { 19065 continue; 19066 } 19067 19068 try { 19069 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19070 synchronized (mInstallLock) { 19071 reconcileAppsDataLI(volumeUuid, user.id, flags); 19072 } 19073 } catch (IllegalStateException e) { 19074 // Device was probably ejected, and we'll process that event momentarily 19075 Slog.w(TAG, "Failed to prepare storage: " + e); 19076 } 19077 } 19078 19079 synchronized (mPackages) { 19080 int updateFlags = UPDATE_PERMISSIONS_ALL; 19081 if (ver.sdkVersion != mSdkVersion) { 19082 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19083 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19084 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19085 } 19086 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19087 19088 // Yay, everything is now upgraded 19089 ver.forceCurrent(); 19090 19091 mSettings.writeLPr(); 19092 } 19093 19094 for (PackageFreezer freezer : freezers) { 19095 freezer.close(); 19096 } 19097 19098 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19099 sendResourcesChangedBroadcast(true, false, loaded, null); 19100 } 19101 19102 private void unloadPrivatePackages(final VolumeInfo vol) { 19103 mHandler.post(new Runnable() { 19104 @Override 19105 public void run() { 19106 unloadPrivatePackagesInner(vol); 19107 } 19108 }); 19109 } 19110 19111 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19112 final String volumeUuid = vol.fsUuid; 19113 if (TextUtils.isEmpty(volumeUuid)) { 19114 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19115 return; 19116 } 19117 19118 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19119 synchronized (mInstallLock) { 19120 synchronized (mPackages) { 19121 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19122 for (PackageSetting ps : packages) { 19123 if (ps.pkg == null) continue; 19124 19125 final ApplicationInfo info = ps.pkg.applicationInfo; 19126 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19127 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19128 19129 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19130 "unloadPrivatePackagesInner")) { 19131 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19132 false, null)) { 19133 unloaded.add(info); 19134 } else { 19135 Slog.w(TAG, "Failed to unload " + ps.codePath); 19136 } 19137 } 19138 19139 // Try very hard to release any references to this package 19140 // so we don't risk the system server being killed due to 19141 // open FDs 19142 AttributeCache.instance().removePackage(ps.name); 19143 } 19144 19145 mSettings.writeLPr(); 19146 } 19147 } 19148 19149 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19150 sendResourcesChangedBroadcast(false, false, unloaded, null); 19151 19152 // Try very hard to release any references to this path so we don't risk 19153 // the system server being killed due to open FDs 19154 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19155 19156 for (int i = 0; i < 3; i++) { 19157 System.gc(); 19158 System.runFinalization(); 19159 } 19160 } 19161 19162 /** 19163 * Prepare storage areas for given user on all mounted devices. 19164 */ 19165 void prepareUserData(int userId, int userSerial, int flags) { 19166 synchronized (mInstallLock) { 19167 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19168 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19169 final String volumeUuid = vol.getFsUuid(); 19170 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19171 } 19172 } 19173 } 19174 19175 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19176 boolean allowRecover) { 19177 // Prepare storage and verify that serial numbers are consistent; if 19178 // there's a mismatch we need to destroy to avoid leaking data 19179 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19180 try { 19181 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19182 19183 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19184 UserManagerService.enforceSerialNumber( 19185 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19186 } 19187 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19188 UserManagerService.enforceSerialNumber( 19189 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19190 } 19191 19192 synchronized (mInstallLock) { 19193 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19194 } 19195 } catch (Exception e) { 19196 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19197 + " because we failed to prepare: " + e); 19198 destroyUserDataLI(volumeUuid, userId, 19199 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19200 19201 if (allowRecover) { 19202 // Try one last time; if we fail again we're really in trouble 19203 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19204 } 19205 } 19206 } 19207 19208 /** 19209 * Destroy storage areas for given user on all mounted devices. 19210 */ 19211 void destroyUserData(int userId, int flags) { 19212 synchronized (mInstallLock) { 19213 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19214 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19215 final String volumeUuid = vol.getFsUuid(); 19216 destroyUserDataLI(volumeUuid, userId, flags); 19217 } 19218 } 19219 } 19220 19221 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19222 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19223 try { 19224 // Clean up app data, profile data, and media data 19225 mInstaller.destroyUserData(volumeUuid, userId, flags); 19226 19227 // Clean up system data 19228 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19229 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19230 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19231 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19232 } 19233 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19234 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19235 } 19236 } 19237 19238 // Data with special labels is now gone, so finish the job 19239 storage.destroyUserStorage(volumeUuid, userId, flags); 19240 19241 } catch (Exception e) { 19242 logCriticalInfo(Log.WARN, 19243 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19244 } 19245 } 19246 19247 /** 19248 * Examine all users present on given mounted volume, and destroy data 19249 * belonging to users that are no longer valid, or whose user ID has been 19250 * recycled. 19251 */ 19252 private void reconcileUsers(String volumeUuid) { 19253 final List<File> files = new ArrayList<>(); 19254 Collections.addAll(files, FileUtils 19255 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19256 Collections.addAll(files, FileUtils 19257 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19258 for (File file : files) { 19259 if (!file.isDirectory()) continue; 19260 19261 final int userId; 19262 final UserInfo info; 19263 try { 19264 userId = Integer.parseInt(file.getName()); 19265 info = sUserManager.getUserInfo(userId); 19266 } catch (NumberFormatException e) { 19267 Slog.w(TAG, "Invalid user directory " + file); 19268 continue; 19269 } 19270 19271 boolean destroyUser = false; 19272 if (info == null) { 19273 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19274 + " because no matching user was found"); 19275 destroyUser = true; 19276 } else if (!mOnlyCore) { 19277 try { 19278 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19279 } catch (IOException e) { 19280 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19281 + " because we failed to enforce serial number: " + e); 19282 destroyUser = true; 19283 } 19284 } 19285 19286 if (destroyUser) { 19287 synchronized (mInstallLock) { 19288 destroyUserDataLI(volumeUuid, userId, 19289 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19290 } 19291 } 19292 } 19293 } 19294 19295 private void assertPackageKnown(String volumeUuid, String packageName) 19296 throws PackageManagerException { 19297 synchronized (mPackages) { 19298 final PackageSetting ps = mSettings.mPackages.get(packageName); 19299 if (ps == null) { 19300 throw new PackageManagerException("Package " + packageName + " is unknown"); 19301 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19302 throw new PackageManagerException( 19303 "Package " + packageName + " found on unknown volume " + volumeUuid 19304 + "; expected volume " + ps.volumeUuid); 19305 } 19306 } 19307 } 19308 19309 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19310 throws PackageManagerException { 19311 synchronized (mPackages) { 19312 final PackageSetting ps = mSettings.mPackages.get(packageName); 19313 if (ps == null) { 19314 throw new PackageManagerException("Package " + packageName + " is unknown"); 19315 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19316 throw new PackageManagerException( 19317 "Package " + packageName + " found on unknown volume " + volumeUuid 19318 + "; expected volume " + ps.volumeUuid); 19319 } else if (!ps.getInstalled(userId)) { 19320 throw new PackageManagerException( 19321 "Package " + packageName + " not installed for user " + userId); 19322 } 19323 } 19324 } 19325 19326 /** 19327 * Examine all apps present on given mounted volume, and destroy apps that 19328 * aren't expected, either due to uninstallation or reinstallation on 19329 * another volume. 19330 */ 19331 private void reconcileApps(String volumeUuid) { 19332 final File[] files = FileUtils 19333 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19334 for (File file : files) { 19335 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19336 && !PackageInstallerService.isStageName(file.getName()); 19337 if (!isPackage) { 19338 // Ignore entries which are not packages 19339 continue; 19340 } 19341 19342 try { 19343 final PackageLite pkg = PackageParser.parsePackageLite(file, 19344 PackageParser.PARSE_MUST_BE_APK); 19345 assertPackageKnown(volumeUuid, pkg.packageName); 19346 19347 } catch (PackageParserException | PackageManagerException e) { 19348 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19349 synchronized (mInstallLock) { 19350 removeCodePathLI(file); 19351 } 19352 } 19353 } 19354 } 19355 19356 /** 19357 * Reconcile all app data for the given user. 19358 * <p> 19359 * Verifies that directories exist and that ownership and labeling is 19360 * correct for all installed apps on all mounted volumes. 19361 */ 19362 void reconcileAppsData(int userId, int flags) { 19363 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19364 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19365 final String volumeUuid = vol.getFsUuid(); 19366 synchronized (mInstallLock) { 19367 reconcileAppsDataLI(volumeUuid, userId, flags); 19368 } 19369 } 19370 } 19371 19372 /** 19373 * Reconcile all app data on given mounted volume. 19374 * <p> 19375 * Destroys app data that isn't expected, either due to uninstallation or 19376 * reinstallation on another volume. 19377 * <p> 19378 * Verifies that directories exist and that ownership and labeling is 19379 * correct for all installed apps. 19380 */ 19381 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19382 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19383 + Integer.toHexString(flags)); 19384 19385 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19386 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19387 19388 boolean restoreconNeeded = false; 19389 19390 // First look for stale data that doesn't belong, and check if things 19391 // have changed since we did our last restorecon 19392 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19393 if (StorageManager.isFileEncryptedNativeOrEmulated() 19394 && !StorageManager.isUserKeyUnlocked(userId)) { 19395 throw new RuntimeException( 19396 "Yikes, someone asked us to reconcile CE storage while " + userId 19397 + " was still locked; this would have caused massive data loss!"); 19398 } 19399 19400 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19401 19402 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19403 for (File file : files) { 19404 final String packageName = file.getName(); 19405 try { 19406 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19407 } catch (PackageManagerException e) { 19408 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19409 try { 19410 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19411 StorageManager.FLAG_STORAGE_CE, 0); 19412 } catch (InstallerException e2) { 19413 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19414 } 19415 } 19416 } 19417 } 19418 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19419 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19420 19421 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19422 for (File file : files) { 19423 final String packageName = file.getName(); 19424 try { 19425 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19426 } catch (PackageManagerException e) { 19427 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19428 try { 19429 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19430 StorageManager.FLAG_STORAGE_DE, 0); 19431 } catch (InstallerException e2) { 19432 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19433 } 19434 } 19435 } 19436 } 19437 19438 // Ensure that data directories are ready to roll for all packages 19439 // installed for this volume and user 19440 final List<PackageSetting> packages; 19441 synchronized (mPackages) { 19442 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19443 } 19444 int preparedCount = 0; 19445 for (PackageSetting ps : packages) { 19446 final String packageName = ps.name; 19447 if (ps.pkg == null) { 19448 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19449 // TODO: might be due to legacy ASEC apps; we should circle back 19450 // and reconcile again once they're scanned 19451 continue; 19452 } 19453 19454 if (ps.getInstalled(userId)) { 19455 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19456 19457 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19458 // We may have just shuffled around app data directories, so 19459 // prepare them one more time 19460 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19461 } 19462 19463 preparedCount++; 19464 } 19465 } 19466 19467 if (restoreconNeeded) { 19468 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19469 SELinuxMMAC.setRestoreconDone(ceDir); 19470 } 19471 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19472 SELinuxMMAC.setRestoreconDone(deDir); 19473 } 19474 } 19475 19476 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19477 + " packages; restoreconNeeded was " + restoreconNeeded); 19478 } 19479 19480 /** 19481 * Prepare app data for the given app just after it was installed or 19482 * upgraded. This method carefully only touches users that it's installed 19483 * for, and it forces a restorecon to handle any seinfo changes. 19484 * <p> 19485 * Verifies that directories exist and that ownership and labeling is 19486 * correct for all installed apps. If there is an ownership mismatch, it 19487 * will try recovering system apps by wiping data; third-party app data is 19488 * left intact. 19489 * <p> 19490 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19491 */ 19492 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19493 final PackageSetting ps; 19494 synchronized (mPackages) { 19495 ps = mSettings.mPackages.get(pkg.packageName); 19496 mSettings.writeKernelMappingLPr(ps); 19497 } 19498 19499 final UserManager um = mContext.getSystemService(UserManager.class); 19500 UserManagerInternal umInternal = getUserManagerInternal(); 19501 for (UserInfo user : um.getUsers()) { 19502 final int flags; 19503 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19504 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19505 } else if (umInternal.isUserRunning(user.id)) { 19506 flags = StorageManager.FLAG_STORAGE_DE; 19507 } else { 19508 continue; 19509 } 19510 19511 if (ps.getInstalled(user.id)) { 19512 // Whenever an app changes, force a restorecon of its data 19513 // TODO: when user data is locked, mark that we're still dirty 19514 prepareAppDataLIF(pkg, user.id, flags, true); 19515 } 19516 } 19517 } 19518 19519 /** 19520 * Prepare app data for the given app. 19521 * <p> 19522 * Verifies that directories exist and that ownership and labeling is 19523 * correct for all installed apps. If there is an ownership mismatch, this 19524 * will try recovering system apps by wiping data; third-party app data is 19525 * left intact. 19526 */ 19527 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19528 boolean restoreconNeeded) { 19529 if (pkg == null) { 19530 Slog.wtf(TAG, "Package was null!", new Throwable()); 19531 return; 19532 } 19533 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19534 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19535 for (int i = 0; i < childCount; i++) { 19536 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19537 } 19538 } 19539 19540 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19541 boolean restoreconNeeded) { 19542 if (DEBUG_APP_DATA) { 19543 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19544 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19545 } 19546 19547 final String volumeUuid = pkg.volumeUuid; 19548 final String packageName = pkg.packageName; 19549 final ApplicationInfo app = pkg.applicationInfo; 19550 final int appId = UserHandle.getAppId(app.uid); 19551 19552 Preconditions.checkNotNull(app.seinfo); 19553 19554 try { 19555 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19556 appId, app.seinfo, app.targetSdkVersion); 19557 } catch (InstallerException e) { 19558 if (app.isSystemApp()) { 19559 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19560 + ", but trying to recover: " + e); 19561 destroyAppDataLeafLIF(pkg, userId, flags); 19562 try { 19563 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19564 appId, app.seinfo, app.targetSdkVersion); 19565 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19566 } catch (InstallerException e2) { 19567 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19568 } 19569 } else { 19570 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19571 } 19572 } 19573 19574 if (restoreconNeeded) { 19575 try { 19576 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19577 app.seinfo); 19578 } catch (InstallerException e) { 19579 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19580 } 19581 } 19582 19583 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19584 try { 19585 // CE storage is unlocked right now, so read out the inode and 19586 // remember for use later when it's locked 19587 // TODO: mark this structure as dirty so we persist it! 19588 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19589 StorageManager.FLAG_STORAGE_CE); 19590 synchronized (mPackages) { 19591 final PackageSetting ps = mSettings.mPackages.get(packageName); 19592 if (ps != null) { 19593 ps.setCeDataInode(ceDataInode, userId); 19594 } 19595 } 19596 } catch (InstallerException e) { 19597 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19598 } 19599 } 19600 19601 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19602 } 19603 19604 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19605 if (pkg == null) { 19606 Slog.wtf(TAG, "Package was null!", new Throwable()); 19607 return; 19608 } 19609 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19611 for (int i = 0; i < childCount; i++) { 19612 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19613 } 19614 } 19615 19616 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19617 final String volumeUuid = pkg.volumeUuid; 19618 final String packageName = pkg.packageName; 19619 final ApplicationInfo app = pkg.applicationInfo; 19620 19621 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19622 // Create a native library symlink only if we have native libraries 19623 // and if the native libraries are 32 bit libraries. We do not provide 19624 // this symlink for 64 bit libraries. 19625 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19626 final String nativeLibPath = app.nativeLibraryDir; 19627 try { 19628 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19629 nativeLibPath, userId); 19630 } catch (InstallerException e) { 19631 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19632 } 19633 } 19634 } 19635 } 19636 19637 /** 19638 * For system apps on non-FBE devices, this method migrates any existing 19639 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19640 * requested by the app. 19641 */ 19642 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19643 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19644 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19645 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19646 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19647 try { 19648 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19649 storageTarget); 19650 } catch (InstallerException e) { 19651 logCriticalInfo(Log.WARN, 19652 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19653 } 19654 return true; 19655 } else { 19656 return false; 19657 } 19658 } 19659 19660 public PackageFreezer freezePackage(String packageName, String killReason) { 19661 return new PackageFreezer(packageName, killReason); 19662 } 19663 19664 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19665 String killReason) { 19666 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19667 return new PackageFreezer(); 19668 } else { 19669 return freezePackage(packageName, killReason); 19670 } 19671 } 19672 19673 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19674 String killReason) { 19675 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19676 return new PackageFreezer(); 19677 } else { 19678 return freezePackage(packageName, killReason); 19679 } 19680 } 19681 19682 /** 19683 * Class that freezes and kills the given package upon creation, and 19684 * unfreezes it upon closing. This is typically used when doing surgery on 19685 * app code/data to prevent the app from running while you're working. 19686 */ 19687 private class PackageFreezer implements AutoCloseable { 19688 private final String mPackageName; 19689 private final PackageFreezer[] mChildren; 19690 19691 private final boolean mWeFroze; 19692 19693 private final AtomicBoolean mClosed = new AtomicBoolean(); 19694 private final CloseGuard mCloseGuard = CloseGuard.get(); 19695 19696 /** 19697 * Create and return a stub freezer that doesn't actually do anything, 19698 * typically used when someone requested 19699 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19700 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19701 */ 19702 public PackageFreezer() { 19703 mPackageName = null; 19704 mChildren = null; 19705 mWeFroze = false; 19706 mCloseGuard.open("close"); 19707 } 19708 19709 public PackageFreezer(String packageName, String killReason) { 19710 synchronized (mPackages) { 19711 mPackageName = packageName; 19712 mWeFroze = mFrozenPackages.add(mPackageName); 19713 19714 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19715 if (ps != null) { 19716 killApplication(ps.name, ps.appId, killReason); 19717 } 19718 19719 final PackageParser.Package p = mPackages.get(packageName); 19720 if (p != null && p.childPackages != null) { 19721 final int N = p.childPackages.size(); 19722 mChildren = new PackageFreezer[N]; 19723 for (int i = 0; i < N; i++) { 19724 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19725 killReason); 19726 } 19727 } else { 19728 mChildren = null; 19729 } 19730 } 19731 mCloseGuard.open("close"); 19732 } 19733 19734 @Override 19735 protected void finalize() throws Throwable { 19736 try { 19737 mCloseGuard.warnIfOpen(); 19738 close(); 19739 } finally { 19740 super.finalize(); 19741 } 19742 } 19743 19744 @Override 19745 public void close() { 19746 mCloseGuard.close(); 19747 if (mClosed.compareAndSet(false, true)) { 19748 synchronized (mPackages) { 19749 if (mWeFroze) { 19750 mFrozenPackages.remove(mPackageName); 19751 } 19752 19753 if (mChildren != null) { 19754 for (PackageFreezer freezer : mChildren) { 19755 freezer.close(); 19756 } 19757 } 19758 } 19759 } 19760 } 19761 } 19762 19763 /** 19764 * Verify that given package is currently frozen. 19765 */ 19766 private void checkPackageFrozen(String packageName) { 19767 synchronized (mPackages) { 19768 if (!mFrozenPackages.contains(packageName)) { 19769 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19770 } 19771 } 19772 } 19773 19774 @Override 19775 public int movePackage(final String packageName, final String volumeUuid) { 19776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19777 19778 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19779 final int moveId = mNextMoveId.getAndIncrement(); 19780 mHandler.post(new Runnable() { 19781 @Override 19782 public void run() { 19783 try { 19784 movePackageInternal(packageName, volumeUuid, moveId, user); 19785 } catch (PackageManagerException e) { 19786 Slog.w(TAG, "Failed to move " + packageName, e); 19787 mMoveCallbacks.notifyStatusChanged(moveId, 19788 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19789 } 19790 } 19791 }); 19792 return moveId; 19793 } 19794 19795 private void movePackageInternal(final String packageName, final String volumeUuid, 19796 final int moveId, UserHandle user) throws PackageManagerException { 19797 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19798 final PackageManager pm = mContext.getPackageManager(); 19799 19800 final boolean currentAsec; 19801 final String currentVolumeUuid; 19802 final File codeFile; 19803 final String installerPackageName; 19804 final String packageAbiOverride; 19805 final int appId; 19806 final String seinfo; 19807 final String label; 19808 final int targetSdkVersion; 19809 final PackageFreezer freezer; 19810 final int[] installedUserIds; 19811 19812 // reader 19813 synchronized (mPackages) { 19814 final PackageParser.Package pkg = mPackages.get(packageName); 19815 final PackageSetting ps = mSettings.mPackages.get(packageName); 19816 if (pkg == null || ps == null) { 19817 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19818 } 19819 19820 if (pkg.applicationInfo.isSystemApp()) { 19821 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19822 "Cannot move system application"); 19823 } 19824 19825 if (pkg.applicationInfo.isExternalAsec()) { 19826 currentAsec = true; 19827 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19828 } else if (pkg.applicationInfo.isForwardLocked()) { 19829 currentAsec = true; 19830 currentVolumeUuid = "forward_locked"; 19831 } else { 19832 currentAsec = false; 19833 currentVolumeUuid = ps.volumeUuid; 19834 19835 final File probe = new File(pkg.codePath); 19836 final File probeOat = new File(probe, "oat"); 19837 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19838 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19839 "Move only supported for modern cluster style installs"); 19840 } 19841 } 19842 19843 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19844 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19845 "Package already moved to " + volumeUuid); 19846 } 19847 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19848 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19849 "Device admin cannot be moved"); 19850 } 19851 19852 if (mFrozenPackages.contains(packageName)) { 19853 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19854 "Failed to move already frozen package"); 19855 } 19856 19857 codeFile = new File(pkg.codePath); 19858 installerPackageName = ps.installerPackageName; 19859 packageAbiOverride = ps.cpuAbiOverrideString; 19860 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19861 seinfo = pkg.applicationInfo.seinfo; 19862 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19863 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19864 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19865 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19866 } 19867 19868 final Bundle extras = new Bundle(); 19869 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19870 extras.putString(Intent.EXTRA_TITLE, label); 19871 mMoveCallbacks.notifyCreated(moveId, extras); 19872 19873 int installFlags; 19874 final boolean moveCompleteApp; 19875 final File measurePath; 19876 19877 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19878 installFlags = INSTALL_INTERNAL; 19879 moveCompleteApp = !currentAsec; 19880 measurePath = Environment.getDataAppDirectory(volumeUuid); 19881 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19882 installFlags = INSTALL_EXTERNAL; 19883 moveCompleteApp = false; 19884 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19885 } else { 19886 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19887 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19888 || !volume.isMountedWritable()) { 19889 freezer.close(); 19890 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19891 "Move location not mounted private volume"); 19892 } 19893 19894 Preconditions.checkState(!currentAsec); 19895 19896 installFlags = INSTALL_INTERNAL; 19897 moveCompleteApp = true; 19898 measurePath = Environment.getDataAppDirectory(volumeUuid); 19899 } 19900 19901 final PackageStats stats = new PackageStats(null, -1); 19902 synchronized (mInstaller) { 19903 for (int userId : installedUserIds) { 19904 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19905 freezer.close(); 19906 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19907 "Failed to measure package size"); 19908 } 19909 } 19910 } 19911 19912 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19913 + stats.dataSize); 19914 19915 final long startFreeBytes = measurePath.getFreeSpace(); 19916 final long sizeBytes; 19917 if (moveCompleteApp) { 19918 sizeBytes = stats.codeSize + stats.dataSize; 19919 } else { 19920 sizeBytes = stats.codeSize; 19921 } 19922 19923 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19924 freezer.close(); 19925 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19926 "Not enough free space to move"); 19927 } 19928 19929 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19930 19931 final CountDownLatch installedLatch = new CountDownLatch(1); 19932 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19933 @Override 19934 public void onUserActionRequired(Intent intent) throws RemoteException { 19935 throw new IllegalStateException(); 19936 } 19937 19938 @Override 19939 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19940 Bundle extras) throws RemoteException { 19941 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19942 + PackageManager.installStatusToString(returnCode, msg)); 19943 19944 installedLatch.countDown(); 19945 freezer.close(); 19946 19947 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19948 switch (status) { 19949 case PackageInstaller.STATUS_SUCCESS: 19950 mMoveCallbacks.notifyStatusChanged(moveId, 19951 PackageManager.MOVE_SUCCEEDED); 19952 break; 19953 case PackageInstaller.STATUS_FAILURE_STORAGE: 19954 mMoveCallbacks.notifyStatusChanged(moveId, 19955 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19956 break; 19957 default: 19958 mMoveCallbacks.notifyStatusChanged(moveId, 19959 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19960 break; 19961 } 19962 } 19963 }; 19964 19965 final MoveInfo move; 19966 if (moveCompleteApp) { 19967 // Kick off a thread to report progress estimates 19968 new Thread() { 19969 @Override 19970 public void run() { 19971 while (true) { 19972 try { 19973 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19974 break; 19975 } 19976 } catch (InterruptedException ignored) { 19977 } 19978 19979 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19980 final int progress = 10 + (int) MathUtils.constrain( 19981 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19982 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19983 } 19984 } 19985 }.start(); 19986 19987 final String dataAppName = codeFile.getName(); 19988 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19989 dataAppName, appId, seinfo, targetSdkVersion); 19990 } else { 19991 move = null; 19992 } 19993 19994 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19995 19996 final Message msg = mHandler.obtainMessage(INIT_COPY); 19997 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19998 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19999 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20000 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20001 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20002 msg.obj = params; 20003 20004 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20005 System.identityHashCode(msg.obj)); 20006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20007 System.identityHashCode(msg.obj)); 20008 20009 mHandler.sendMessage(msg); 20010 } 20011 20012 @Override 20013 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20014 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20015 20016 final int realMoveId = mNextMoveId.getAndIncrement(); 20017 final Bundle extras = new Bundle(); 20018 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20019 mMoveCallbacks.notifyCreated(realMoveId, extras); 20020 20021 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20022 @Override 20023 public void onCreated(int moveId, Bundle extras) { 20024 // Ignored 20025 } 20026 20027 @Override 20028 public void onStatusChanged(int moveId, int status, long estMillis) { 20029 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20030 } 20031 }; 20032 20033 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20034 storage.setPrimaryStorageUuid(volumeUuid, callback); 20035 return realMoveId; 20036 } 20037 20038 @Override 20039 public int getMoveStatus(int moveId) { 20040 mContext.enforceCallingOrSelfPermission( 20041 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20042 return mMoveCallbacks.mLastStatus.get(moveId); 20043 } 20044 20045 @Override 20046 public void registerMoveCallback(IPackageMoveObserver callback) { 20047 mContext.enforceCallingOrSelfPermission( 20048 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20049 mMoveCallbacks.register(callback); 20050 } 20051 20052 @Override 20053 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20054 mContext.enforceCallingOrSelfPermission( 20055 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20056 mMoveCallbacks.unregister(callback); 20057 } 20058 20059 @Override 20060 public boolean setInstallLocation(int loc) { 20061 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20062 null); 20063 if (getInstallLocation() == loc) { 20064 return true; 20065 } 20066 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20067 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20068 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20069 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20070 return true; 20071 } 20072 return false; 20073 } 20074 20075 @Override 20076 public int getInstallLocation() { 20077 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20078 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20079 PackageHelper.APP_INSTALL_AUTO); 20080 } 20081 20082 /** Called by UserManagerService */ 20083 void cleanUpUser(UserManagerService userManager, int userHandle) { 20084 synchronized (mPackages) { 20085 mDirtyUsers.remove(userHandle); 20086 mUserNeedsBadging.delete(userHandle); 20087 mSettings.removeUserLPw(userHandle); 20088 mPendingBroadcasts.remove(userHandle); 20089 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20090 removeUnusedPackagesLPw(userManager, userHandle); 20091 } 20092 } 20093 20094 /** 20095 * We're removing userHandle and would like to remove any downloaded packages 20096 * that are no longer in use by any other user. 20097 * @param userHandle the user being removed 20098 */ 20099 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20100 final boolean DEBUG_CLEAN_APKS = false; 20101 int [] users = userManager.getUserIds(); 20102 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20103 while (psit.hasNext()) { 20104 PackageSetting ps = psit.next(); 20105 if (ps.pkg == null) { 20106 continue; 20107 } 20108 final String packageName = ps.pkg.packageName; 20109 // Skip over if system app 20110 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20111 continue; 20112 } 20113 if (DEBUG_CLEAN_APKS) { 20114 Slog.i(TAG, "Checking package " + packageName); 20115 } 20116 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20117 if (keep) { 20118 if (DEBUG_CLEAN_APKS) { 20119 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20120 } 20121 } else { 20122 for (int i = 0; i < users.length; i++) { 20123 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20124 keep = true; 20125 if (DEBUG_CLEAN_APKS) { 20126 Slog.i(TAG, " Keeping package " + packageName + " for user " 20127 + users[i]); 20128 } 20129 break; 20130 } 20131 } 20132 } 20133 if (!keep) { 20134 if (DEBUG_CLEAN_APKS) { 20135 Slog.i(TAG, " Removing package " + packageName); 20136 } 20137 mHandler.post(new Runnable() { 20138 public void run() { 20139 deletePackageX(packageName, userHandle, 0); 20140 } //end run 20141 }); 20142 } 20143 } 20144 } 20145 20146 /** Called by UserManagerService */ 20147 void createNewUser(int userId) { 20148 synchronized (mInstallLock) { 20149 mSettings.createNewUserLI(this, mInstaller, userId); 20150 } 20151 synchronized (mPackages) { 20152 scheduleWritePackageRestrictionsLocked(userId); 20153 scheduleWritePackageListLocked(userId); 20154 applyFactoryDefaultBrowserLPw(userId); 20155 primeDomainVerificationsLPw(userId); 20156 } 20157 } 20158 20159 void onBeforeUserStartUninitialized(final int userId) { 20160 synchronized (mPackages) { 20161 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20162 return; 20163 } 20164 } 20165 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20166 // If permission review for legacy apps is required, we represent 20167 // dagerous permissions for such apps as always granted runtime 20168 // permissions to keep per user flag state whether review is needed. 20169 // Hence, if a new user is added we have to propagate dangerous 20170 // permission grants for these legacy apps. 20171 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20172 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20173 | UPDATE_PERMISSIONS_REPLACE_ALL); 20174 } 20175 } 20176 20177 @Override 20178 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20179 mContext.enforceCallingOrSelfPermission( 20180 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20181 "Only package verification agents can read the verifier device identity"); 20182 20183 synchronized (mPackages) { 20184 return mSettings.getVerifierDeviceIdentityLPw(); 20185 } 20186 } 20187 20188 @Override 20189 public void setPermissionEnforced(String permission, boolean enforced) { 20190 // TODO: Now that we no longer change GID for storage, this should to away. 20191 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20192 "setPermissionEnforced"); 20193 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20194 synchronized (mPackages) { 20195 if (mSettings.mReadExternalStorageEnforced == null 20196 || mSettings.mReadExternalStorageEnforced != enforced) { 20197 mSettings.mReadExternalStorageEnforced = enforced; 20198 mSettings.writeLPr(); 20199 } 20200 } 20201 // kill any non-foreground processes so we restart them and 20202 // grant/revoke the GID. 20203 final IActivityManager am = ActivityManagerNative.getDefault(); 20204 if (am != null) { 20205 final long token = Binder.clearCallingIdentity(); 20206 try { 20207 am.killProcessesBelowForeground("setPermissionEnforcement"); 20208 } catch (RemoteException e) { 20209 } finally { 20210 Binder.restoreCallingIdentity(token); 20211 } 20212 } 20213 } else { 20214 throw new IllegalArgumentException("No selective enforcement for " + permission); 20215 } 20216 } 20217 20218 @Override 20219 @Deprecated 20220 public boolean isPermissionEnforced(String permission) { 20221 return true; 20222 } 20223 20224 @Override 20225 public boolean isStorageLow() { 20226 final long token = Binder.clearCallingIdentity(); 20227 try { 20228 final DeviceStorageMonitorInternal 20229 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20230 if (dsm != null) { 20231 return dsm.isMemoryLow(); 20232 } else { 20233 return false; 20234 } 20235 } finally { 20236 Binder.restoreCallingIdentity(token); 20237 } 20238 } 20239 20240 @Override 20241 public IPackageInstaller getPackageInstaller() { 20242 return mInstallerService; 20243 } 20244 20245 private boolean userNeedsBadging(int userId) { 20246 int index = mUserNeedsBadging.indexOfKey(userId); 20247 if (index < 0) { 20248 final UserInfo userInfo; 20249 final long token = Binder.clearCallingIdentity(); 20250 try { 20251 userInfo = sUserManager.getUserInfo(userId); 20252 } finally { 20253 Binder.restoreCallingIdentity(token); 20254 } 20255 final boolean b; 20256 if (userInfo != null && userInfo.isManagedProfile()) { 20257 b = true; 20258 } else { 20259 b = false; 20260 } 20261 mUserNeedsBadging.put(userId, b); 20262 return b; 20263 } 20264 return mUserNeedsBadging.valueAt(index); 20265 } 20266 20267 @Override 20268 public KeySet getKeySetByAlias(String packageName, String alias) { 20269 if (packageName == null || alias == null) { 20270 return null; 20271 } 20272 synchronized(mPackages) { 20273 final PackageParser.Package pkg = mPackages.get(packageName); 20274 if (pkg == null) { 20275 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20276 throw new IllegalArgumentException("Unknown package: " + packageName); 20277 } 20278 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20279 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20280 } 20281 } 20282 20283 @Override 20284 public KeySet getSigningKeySet(String packageName) { 20285 if (packageName == null) { 20286 return null; 20287 } 20288 synchronized(mPackages) { 20289 final PackageParser.Package pkg = mPackages.get(packageName); 20290 if (pkg == null) { 20291 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20292 throw new IllegalArgumentException("Unknown package: " + packageName); 20293 } 20294 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20295 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20296 throw new SecurityException("May not access signing KeySet of other apps."); 20297 } 20298 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20299 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20300 } 20301 } 20302 20303 @Override 20304 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20305 if (packageName == null || ks == null) { 20306 return false; 20307 } 20308 synchronized(mPackages) { 20309 final PackageParser.Package pkg = mPackages.get(packageName); 20310 if (pkg == null) { 20311 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20312 throw new IllegalArgumentException("Unknown package: " + packageName); 20313 } 20314 IBinder ksh = ks.getToken(); 20315 if (ksh instanceof KeySetHandle) { 20316 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20317 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20318 } 20319 return false; 20320 } 20321 } 20322 20323 @Override 20324 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20325 if (packageName == null || ks == null) { 20326 return false; 20327 } 20328 synchronized(mPackages) { 20329 final PackageParser.Package pkg = mPackages.get(packageName); 20330 if (pkg == null) { 20331 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20332 throw new IllegalArgumentException("Unknown package: " + packageName); 20333 } 20334 IBinder ksh = ks.getToken(); 20335 if (ksh instanceof KeySetHandle) { 20336 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20337 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20338 } 20339 return false; 20340 } 20341 } 20342 20343 private void deletePackageIfUnusedLPr(final String packageName) { 20344 PackageSetting ps = mSettings.mPackages.get(packageName); 20345 if (ps == null) { 20346 return; 20347 } 20348 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20349 // TODO Implement atomic delete if package is unused 20350 // It is currently possible that the package will be deleted even if it is installed 20351 // after this method returns. 20352 mHandler.post(new Runnable() { 20353 public void run() { 20354 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20355 } 20356 }); 20357 } 20358 } 20359 20360 /** 20361 * Check and throw if the given before/after packages would be considered a 20362 * downgrade. 20363 */ 20364 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20365 throws PackageManagerException { 20366 if (after.versionCode < before.mVersionCode) { 20367 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20368 "Update version code " + after.versionCode + " is older than current " 20369 + before.mVersionCode); 20370 } else if (after.versionCode == before.mVersionCode) { 20371 if (after.baseRevisionCode < before.baseRevisionCode) { 20372 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20373 "Update base revision code " + after.baseRevisionCode 20374 + " is older than current " + before.baseRevisionCode); 20375 } 20376 20377 if (!ArrayUtils.isEmpty(after.splitNames)) { 20378 for (int i = 0; i < after.splitNames.length; i++) { 20379 final String splitName = after.splitNames[i]; 20380 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20381 if (j != -1) { 20382 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20383 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20384 "Update split " + splitName + " revision code " 20385 + after.splitRevisionCodes[i] + " is older than current " 20386 + before.splitRevisionCodes[j]); 20387 } 20388 } 20389 } 20390 } 20391 } 20392 } 20393 20394 private static class MoveCallbacks extends Handler { 20395 private static final int MSG_CREATED = 1; 20396 private static final int MSG_STATUS_CHANGED = 2; 20397 20398 private final RemoteCallbackList<IPackageMoveObserver> 20399 mCallbacks = new RemoteCallbackList<>(); 20400 20401 private final SparseIntArray mLastStatus = new SparseIntArray(); 20402 20403 public MoveCallbacks(Looper looper) { 20404 super(looper); 20405 } 20406 20407 public void register(IPackageMoveObserver callback) { 20408 mCallbacks.register(callback); 20409 } 20410 20411 public void unregister(IPackageMoveObserver callback) { 20412 mCallbacks.unregister(callback); 20413 } 20414 20415 @Override 20416 public void handleMessage(Message msg) { 20417 final SomeArgs args = (SomeArgs) msg.obj; 20418 final int n = mCallbacks.beginBroadcast(); 20419 for (int i = 0; i < n; i++) { 20420 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20421 try { 20422 invokeCallback(callback, msg.what, args); 20423 } catch (RemoteException ignored) { 20424 } 20425 } 20426 mCallbacks.finishBroadcast(); 20427 args.recycle(); 20428 } 20429 20430 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20431 throws RemoteException { 20432 switch (what) { 20433 case MSG_CREATED: { 20434 callback.onCreated(args.argi1, (Bundle) args.arg2); 20435 break; 20436 } 20437 case MSG_STATUS_CHANGED: { 20438 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20439 break; 20440 } 20441 } 20442 } 20443 20444 private void notifyCreated(int moveId, Bundle extras) { 20445 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20446 20447 final SomeArgs args = SomeArgs.obtain(); 20448 args.argi1 = moveId; 20449 args.arg2 = extras; 20450 obtainMessage(MSG_CREATED, args).sendToTarget(); 20451 } 20452 20453 private void notifyStatusChanged(int moveId, int status) { 20454 notifyStatusChanged(moveId, status, -1); 20455 } 20456 20457 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20458 Slog.v(TAG, "Move " + moveId + " status " + status); 20459 20460 final SomeArgs args = SomeArgs.obtain(); 20461 args.argi1 = moveId; 20462 args.argi2 = status; 20463 args.arg3 = estMillis; 20464 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20465 20466 synchronized (mLastStatus) { 20467 mLastStatus.put(moveId, status); 20468 } 20469 } 20470 } 20471 20472 private final static class OnPermissionChangeListeners extends Handler { 20473 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20474 20475 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20476 new RemoteCallbackList<>(); 20477 20478 public OnPermissionChangeListeners(Looper looper) { 20479 super(looper); 20480 } 20481 20482 @Override 20483 public void handleMessage(Message msg) { 20484 switch (msg.what) { 20485 case MSG_ON_PERMISSIONS_CHANGED: { 20486 final int uid = msg.arg1; 20487 handleOnPermissionsChanged(uid); 20488 } break; 20489 } 20490 } 20491 20492 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20493 mPermissionListeners.register(listener); 20494 20495 } 20496 20497 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20498 mPermissionListeners.unregister(listener); 20499 } 20500 20501 public void onPermissionsChanged(int uid) { 20502 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20503 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20504 } 20505 } 20506 20507 private void handleOnPermissionsChanged(int uid) { 20508 final int count = mPermissionListeners.beginBroadcast(); 20509 try { 20510 for (int i = 0; i < count; i++) { 20511 IOnPermissionsChangeListener callback = mPermissionListeners 20512 .getBroadcastItem(i); 20513 try { 20514 callback.onPermissionsChanged(uid); 20515 } catch (RemoteException e) { 20516 Log.e(TAG, "Permission listener is dead", e); 20517 } 20518 } 20519 } finally { 20520 mPermissionListeners.finishBroadcast(); 20521 } 20522 } 20523 } 20524 20525 private class PackageManagerInternalImpl extends PackageManagerInternal { 20526 @Override 20527 public void setLocationPackagesProvider(PackagesProvider provider) { 20528 synchronized (mPackages) { 20529 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20530 } 20531 } 20532 20533 @Override 20534 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20535 synchronized (mPackages) { 20536 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20537 } 20538 } 20539 20540 @Override 20541 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20542 synchronized (mPackages) { 20543 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20544 } 20545 } 20546 20547 @Override 20548 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20549 synchronized (mPackages) { 20550 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20551 } 20552 } 20553 20554 @Override 20555 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20556 synchronized (mPackages) { 20557 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20558 } 20559 } 20560 20561 @Override 20562 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20563 synchronized (mPackages) { 20564 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20565 } 20566 } 20567 20568 @Override 20569 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20570 synchronized (mPackages) { 20571 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20572 packageName, userId); 20573 } 20574 } 20575 20576 @Override 20577 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20578 synchronized (mPackages) { 20579 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20580 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20581 packageName, userId); 20582 } 20583 } 20584 20585 @Override 20586 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20587 synchronized (mPackages) { 20588 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20589 packageName, userId); 20590 } 20591 } 20592 20593 @Override 20594 public void setKeepUninstalledPackages(final List<String> packageList) { 20595 Preconditions.checkNotNull(packageList); 20596 List<String> removedFromList = null; 20597 synchronized (mPackages) { 20598 if (mKeepUninstalledPackages != null) { 20599 final int packagesCount = mKeepUninstalledPackages.size(); 20600 for (int i = 0; i < packagesCount; i++) { 20601 String oldPackage = mKeepUninstalledPackages.get(i); 20602 if (packageList != null && packageList.contains(oldPackage)) { 20603 continue; 20604 } 20605 if (removedFromList == null) { 20606 removedFromList = new ArrayList<>(); 20607 } 20608 removedFromList.add(oldPackage); 20609 } 20610 } 20611 mKeepUninstalledPackages = new ArrayList<>(packageList); 20612 if (removedFromList != null) { 20613 final int removedCount = removedFromList.size(); 20614 for (int i = 0; i < removedCount; i++) { 20615 deletePackageIfUnusedLPr(removedFromList.get(i)); 20616 } 20617 } 20618 } 20619 } 20620 20621 @Override 20622 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20623 synchronized (mPackages) { 20624 // If we do not support permission review, done. 20625 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20626 return false; 20627 } 20628 20629 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20630 if (packageSetting == null) { 20631 return false; 20632 } 20633 20634 // Permission review applies only to apps not supporting the new permission model. 20635 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20636 return false; 20637 } 20638 20639 // Legacy apps have the permission and get user consent on launch. 20640 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20641 return permissionsState.isPermissionReviewRequired(userId); 20642 } 20643 } 20644 20645 @Override 20646 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20647 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20648 } 20649 20650 @Override 20651 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20652 int userId) { 20653 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20654 } 20655 } 20656 20657 @Override 20658 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20659 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20660 synchronized (mPackages) { 20661 final long identity = Binder.clearCallingIdentity(); 20662 try { 20663 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20664 packageNames, userId); 20665 } finally { 20666 Binder.restoreCallingIdentity(identity); 20667 } 20668 } 20669 } 20670 20671 private static void enforceSystemOrPhoneCaller(String tag) { 20672 int callingUid = Binder.getCallingUid(); 20673 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20674 throw new SecurityException( 20675 "Cannot call " + tag + " from UID " + callingUid); 20676 } 20677 } 20678 20679 boolean isHistoricalPackageUsageAvailable() { 20680 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20681 } 20682 20683 /** 20684 * Return a <b>copy</b> of the collection of packages known to the package manager. 20685 * @return A copy of the values of mPackages. 20686 */ 20687 Collection<PackageParser.Package> getPackages() { 20688 synchronized (mPackages) { 20689 return new ArrayList<>(mPackages.values()); 20690 } 20691 } 20692 20693 /** 20694 * Logs process start information (including base APK hash) to the security log. 20695 * @hide 20696 */ 20697 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20698 String apkFile, int pid) { 20699 if (!SecurityLog.isLoggingEnabled()) { 20700 return; 20701 } 20702 Bundle data = new Bundle(); 20703 data.putLong("startTimestamp", System.currentTimeMillis()); 20704 data.putString("processName", processName); 20705 data.putInt("uid", uid); 20706 data.putString("seinfo", seinfo); 20707 data.putString("apkFile", apkFile); 20708 data.putInt("pid", pid); 20709 Message msg = mProcessLoggingHandler.obtainMessage( 20710 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20711 msg.setData(data); 20712 mProcessLoggingHandler.sendMessage(msg); 20713 } 20714} 20715