PackageManagerService.java revision 98bf12f99989ba2550fac83ee48ecbb6f1582f07
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 // save off the names of pre-existing system packages prior to scanning; we don't 2401 // want to automatically grant runtime permissions for new system apps 2402 if (mPromoteSystemApps) { 2403 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2404 while (pkgSettingIter.hasNext()) { 2405 PackageSetting ps = pkgSettingIter.next(); 2406 if (isSystemApp(ps)) { 2407 mExistingSystemPackages.add(ps.name); 2408 } 2409 } 2410 } 2411 2412 // When upgrading from pre-N, we need to handle package extraction like first boot, 2413 // as there is no profiling data available. 2414 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2415 mSettings.setNWorkDone(); 2416 2417 // Collect vendor overlay packages. 2418 // (Do this before scanning any apps.) 2419 // For security and version matching reason, only consider 2420 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2421 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2422 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR 2425 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2426 2427 // Find base frameworks (resource packages without code). 2428 scanDirTracedLI(frameworkDir, mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_IS_PRIVILEGED, 2432 scanFlags | SCAN_NO_DEX, 0); 2433 2434 // Collected privileged system packages. 2435 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2436 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2440 2441 // Collect ordinary system packages. 2442 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2443 scanDirTracedLI(systemAppDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2446 2447 // Collect all vendor packages. 2448 File vendorAppDir = new File("/vendor/app"); 2449 try { 2450 vendorAppDir = vendorAppDir.getCanonicalFile(); 2451 } catch (IOException e) { 2452 // failed to look up canonical path, continue with original one 2453 } 2454 scanDirTracedLI(vendorAppDir, mDefParseFlags 2455 | PackageParser.PARSE_IS_SYSTEM 2456 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2457 2458 // Collect all OEM packages. 2459 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2460 scanDirTracedLI(oemAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Prune any system packages that no longer exist. 2465 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2466 if (!mOnlyCore) { 2467 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2468 while (psit.hasNext()) { 2469 PackageSetting ps = psit.next(); 2470 2471 /* 2472 * If this is not a system app, it can't be a 2473 * disable system app. 2474 */ 2475 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2476 continue; 2477 } 2478 2479 /* 2480 * If the package is scanned, it's not erased. 2481 */ 2482 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2483 if (scannedPkg != null) { 2484 /* 2485 * If the system app is both scanned and in the 2486 * disabled packages list, then it must have been 2487 * added via OTA. Remove it from the currently 2488 * scanned package so the previously user-installed 2489 * application can be scanned. 2490 */ 2491 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2492 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2493 + ps.name + "; removing system app. Last known codePath=" 2494 + ps.codePathString + ", installStatus=" + ps.installStatus 2495 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2496 + scannedPkg.mVersionCode); 2497 removePackageLI(scannedPkg, true); 2498 mExpectingBetter.put(ps.name, ps.codePath); 2499 } 2500 2501 continue; 2502 } 2503 2504 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2505 psit.remove(); 2506 logCriticalInfo(Log.WARN, "System package " + ps.name 2507 + " no longer exists; it's data will be wiped"); 2508 // Actual deletion of code and data will be handled by later 2509 // reconciliation step 2510 } else { 2511 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2512 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2513 possiblyDeletedUpdatedSystemApps.add(ps.name); 2514 } 2515 } 2516 } 2517 } 2518 2519 //look for any incomplete package installations 2520 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2521 for (int i = 0; i < deletePkgsList.size(); i++) { 2522 // Actual deletion of code and data will be handled by later 2523 // reconciliation step 2524 final String packageName = deletePkgsList.get(i).name; 2525 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2526 synchronized (mPackages) { 2527 mSettings.removePackageLPw(packageName); 2528 } 2529 } 2530 2531 //delete tmp files 2532 deleteTempPackageFiles(); 2533 2534 // Remove any shared userIDs that have no associated packages 2535 mSettings.pruneSharedUsersLPw(); 2536 2537 if (!mOnlyCore) { 2538 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2539 SystemClock.uptimeMillis()); 2540 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2541 2542 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2543 | PackageParser.PARSE_FORWARD_LOCK, 2544 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2545 2546 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2547 | PackageParser.PARSE_IS_EPHEMERAL, 2548 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2549 2550 /** 2551 * Remove disable package settings for any updated system 2552 * apps that were removed via an OTA. If they're not a 2553 * previously-updated app, remove them completely. 2554 * Otherwise, just revoke their system-level permissions. 2555 */ 2556 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2557 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2558 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2559 2560 String msg; 2561 if (deletedPkg == null) { 2562 msg = "Updated system package " + deletedAppName 2563 + " no longer exists; it's data will be wiped"; 2564 // Actual deletion of code and data will be handled by later 2565 // reconciliation step 2566 } else { 2567 msg = "Updated system app + " + deletedAppName 2568 + " no longer present; removing system privileges for " 2569 + deletedAppName; 2570 2571 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2572 2573 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2574 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2575 } 2576 logCriticalInfo(Log.WARN, msg); 2577 } 2578 2579 /** 2580 * Make sure all system apps that we expected to appear on 2581 * the userdata partition actually showed up. If they never 2582 * appeared, crawl back and revive the system version. 2583 */ 2584 for (int i = 0; i < mExpectingBetter.size(); i++) { 2585 final String packageName = mExpectingBetter.keyAt(i); 2586 if (!mPackages.containsKey(packageName)) { 2587 final File scanFile = mExpectingBetter.valueAt(i); 2588 2589 logCriticalInfo(Log.WARN, "Expected better " + packageName 2590 + " but never showed up; reverting to system"); 2591 2592 int reparseFlags = mDefParseFlags; 2593 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2594 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2595 | PackageParser.PARSE_IS_SYSTEM_DIR 2596 | PackageParser.PARSE_IS_PRIVILEGED; 2597 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2598 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2599 | PackageParser.PARSE_IS_SYSTEM_DIR; 2600 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2601 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2602 | PackageParser.PARSE_IS_SYSTEM_DIR; 2603 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR; 2606 } else { 2607 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2608 continue; 2609 } 2610 2611 mSettings.enableSystemPackageLPw(packageName); 2612 2613 try { 2614 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2615 } catch (PackageManagerException e) { 2616 Slog.e(TAG, "Failed to parse original system package: " 2617 + e.getMessage()); 2618 } 2619 } 2620 } 2621 } 2622 mExpectingBetter.clear(); 2623 2624 // Resolve protected action filters. Only the setup wizard is allowed to 2625 // have a high priority filter for these actions. 2626 mSetupWizardPackage = getSetupWizardPackageName(); 2627 if (mProtectedFilters.size() > 0) { 2628 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2629 Slog.i(TAG, "No setup wizard;" 2630 + " All protected intents capped to priority 0"); 2631 } 2632 for (ActivityIntentInfo filter : mProtectedFilters) { 2633 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2634 if (DEBUG_FILTERS) { 2635 Slog.i(TAG, "Found setup wizard;" 2636 + " allow priority " + filter.getPriority() + ";" 2637 + " package: " + filter.activity.info.packageName 2638 + " activity: " + filter.activity.className 2639 + " priority: " + filter.getPriority()); 2640 } 2641 // skip setup wizard; allow it to keep the high priority filter 2642 continue; 2643 } 2644 Slog.w(TAG, "Protected action; cap priority to 0;" 2645 + " package: " + filter.activity.info.packageName 2646 + " activity: " + filter.activity.className 2647 + " origPrio: " + filter.getPriority()); 2648 filter.setPriority(0); 2649 } 2650 } 2651 mDeferProtectedFilters = false; 2652 mProtectedFilters.clear(); 2653 2654 // Now that we know all of the shared libraries, update all clients to have 2655 // the correct library paths. 2656 updateAllSharedLibrariesLPw(); 2657 2658 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2659 // NOTE: We ignore potential failures here during a system scan (like 2660 // the rest of the commands above) because there's precious little we 2661 // can do about it. A settings error is reported, though. 2662 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2663 false /* boot complete */); 2664 } 2665 2666 // Now that we know all the packages we are keeping, 2667 // read and update their last usage times. 2668 mPackageUsage.readLP(); 2669 2670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2671 SystemClock.uptimeMillis()); 2672 Slog.i(TAG, "Time to scan packages: " 2673 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2674 + " seconds"); 2675 2676 // If the platform SDK has changed since the last time we booted, 2677 // we need to re-grant app permission to catch any new ones that 2678 // appear. This is really a hack, and means that apps can in some 2679 // cases get permissions that the user didn't initially explicitly 2680 // allow... it would be nice to have some better way to handle 2681 // this situation. 2682 int updateFlags = UPDATE_PERMISSIONS_ALL; 2683 if (ver.sdkVersion != mSdkVersion) { 2684 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2685 + mSdkVersion + "; regranting permissions for internal storage"); 2686 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2687 } 2688 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2689 ver.sdkVersion = mSdkVersion; 2690 2691 // If this is the first boot or an update from pre-M, and it is a normal 2692 // boot, then we need to initialize the default preferred apps across 2693 // all defined users. 2694 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2695 for (UserInfo user : sUserManager.getUsers(true)) { 2696 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2697 applyFactoryDefaultBrowserLPw(user.id); 2698 primeDomainVerificationsLPw(user.id); 2699 } 2700 } 2701 2702 // Prepare storage for system user really early during boot, 2703 // since core system apps like SettingsProvider and SystemUI 2704 // can't wait for user to start 2705 final int storageFlags; 2706 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE; 2708 } else { 2709 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2710 } 2711 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2712 storageFlags); 2713 2714 // If this is first boot after an OTA, and a normal boot, then 2715 // we need to clear code cache directories. 2716 // Note that we do *not* clear the application profiles. These remain valid 2717 // across OTAs and are used to drive profile verification (post OTA) and 2718 // profile compilation (without waiting to collect a fresh set of profiles). 2719 if (mIsUpgrade && !onlyCore) { 2720 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2721 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2722 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2723 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2724 // No apps are running this early, so no need to freeze 2725 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2726 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2727 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2728 } 2729 clearAppProfilesLIF(ps.pkg, UserHandle.USER_ALL); 2730 } 2731 ver.fingerprint = Build.FINGERPRINT; 2732 } 2733 2734 checkDefaultBrowser(); 2735 2736 // clear only after permissions and other defaults have been updated 2737 mExistingSystemPackages.clear(); 2738 mPromoteSystemApps = false; 2739 2740 // All the changes are done during package scanning. 2741 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2742 2743 // can downgrade to reader 2744 mSettings.writeLPr(); 2745 2746 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2747 SystemClock.uptimeMillis()); 2748 2749 if (!mOnlyCore) { 2750 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2751 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2752 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2753 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2754 mIntentFilterVerifierComponent); 2755 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2756 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2757 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2758 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2759 } else { 2760 mRequiredVerifierPackage = null; 2761 mRequiredInstallerPackage = null; 2762 mIntentFilterVerifierComponent = null; 2763 mIntentFilterVerifier = null; 2764 mServicesSystemSharedLibraryPackageName = null; 2765 mSharedSystemSharedLibraryPackageName = null; 2766 } 2767 2768 mInstallerService = new PackageInstallerService(context, this); 2769 2770 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2771 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2772 // both the installer and resolver must be present to enable ephemeral 2773 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2774 if (DEBUG_EPHEMERAL) { 2775 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2776 + " installer:" + ephemeralInstallerComponent); 2777 } 2778 mEphemeralResolverComponent = ephemeralResolverComponent; 2779 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2780 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2781 mEphemeralResolverConnection = 2782 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2783 } else { 2784 if (DEBUG_EPHEMERAL) { 2785 final String missingComponent = 2786 (ephemeralResolverComponent == null) 2787 ? (ephemeralInstallerComponent == null) 2788 ? "resolver and installer" 2789 : "resolver" 2790 : "installer"; 2791 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2792 } 2793 mEphemeralResolverComponent = null; 2794 mEphemeralInstallerComponent = null; 2795 mEphemeralResolverConnection = null; 2796 } 2797 2798 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2799 } // synchronized (mPackages) 2800 } // synchronized (mInstallLock) 2801 2802 // Now after opening every single application zip, make sure they 2803 // are all flushed. Not really needed, but keeps things nice and 2804 // tidy. 2805 Runtime.getRuntime().gc(); 2806 2807 // The initial scanning above does many calls into installd while 2808 // holding the mPackages lock, but we're mostly interested in yelling 2809 // once we have a booted system. 2810 mInstaller.setWarnIfHeld(mPackages); 2811 2812 // Expose private service for system components to use. 2813 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2814 } 2815 2816 @Override 2817 public boolean isFirstBoot() { 2818 return !mRestoredSettings; 2819 } 2820 2821 @Override 2822 public boolean isOnlyCoreApps() { 2823 return mOnlyCore; 2824 } 2825 2826 @Override 2827 public boolean isUpgrade() { 2828 return mIsUpgrade; 2829 } 2830 2831 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2832 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2833 2834 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2835 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2836 UserHandle.USER_SYSTEM); 2837 if (matches.size() == 1) { 2838 return matches.get(0).getComponentInfo().packageName; 2839 } else { 2840 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2841 return null; 2842 } 2843 } 2844 2845 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2846 synchronized (mPackages) { 2847 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2848 if (libraryEntry == null) { 2849 throw new IllegalStateException("Missing required shared library:" + libraryName); 2850 } 2851 return libraryEntry.apk; 2852 } 2853 } 2854 2855 private @NonNull String getRequiredInstallerLPr() { 2856 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2857 intent.addCategory(Intent.CATEGORY_DEFAULT); 2858 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2859 2860 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2861 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2862 UserHandle.USER_SYSTEM); 2863 if (matches.size() == 1) { 2864 ResolveInfo resolveInfo = matches.get(0); 2865 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2866 throw new RuntimeException("The installer must be a privileged app"); 2867 } 2868 return matches.get(0).getComponentInfo().packageName; 2869 } else { 2870 throw new RuntimeException("There must be exactly one installer; found " + matches); 2871 } 2872 } 2873 2874 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2875 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2876 2877 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2878 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2879 UserHandle.USER_SYSTEM); 2880 ResolveInfo best = null; 2881 final int N = matches.size(); 2882 for (int i = 0; i < N; i++) { 2883 final ResolveInfo cur = matches.get(i); 2884 final String packageName = cur.getComponentInfo().packageName; 2885 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2886 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2887 continue; 2888 } 2889 2890 if (best == null || cur.priority > best.priority) { 2891 best = cur; 2892 } 2893 } 2894 2895 if (best != null) { 2896 return best.getComponentInfo().getComponentName(); 2897 } else { 2898 throw new RuntimeException("There must be at least one intent filter verifier"); 2899 } 2900 } 2901 2902 private @Nullable ComponentName getEphemeralResolverLPr() { 2903 final String[] packageArray = 2904 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2905 if (packageArray.length == 0) { 2906 if (DEBUG_EPHEMERAL) { 2907 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2908 } 2909 return null; 2910 } 2911 2912 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2913 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2914 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2915 UserHandle.USER_SYSTEM); 2916 2917 final int N = resolvers.size(); 2918 if (N == 0) { 2919 if (DEBUG_EPHEMERAL) { 2920 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2921 } 2922 return null; 2923 } 2924 2925 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2926 for (int i = 0; i < N; i++) { 2927 final ResolveInfo info = resolvers.get(i); 2928 2929 if (info.serviceInfo == null) { 2930 continue; 2931 } 2932 2933 final String packageName = info.serviceInfo.packageName; 2934 if (!possiblePackages.contains(packageName)) { 2935 if (DEBUG_EPHEMERAL) { 2936 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2937 + " pkg: " + packageName + ", info:" + info); 2938 } 2939 continue; 2940 } 2941 2942 if (DEBUG_EPHEMERAL) { 2943 Slog.v(TAG, "Ephemeral resolver found;" 2944 + " pkg: " + packageName + ", info:" + info); 2945 } 2946 return new ComponentName(packageName, info.serviceInfo.name); 2947 } 2948 if (DEBUG_EPHEMERAL) { 2949 Slog.v(TAG, "Ephemeral resolver NOT found"); 2950 } 2951 return null; 2952 } 2953 2954 private @Nullable ComponentName getEphemeralInstallerLPr() { 2955 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2956 intent.addCategory(Intent.CATEGORY_DEFAULT); 2957 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2958 2959 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2960 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2961 UserHandle.USER_SYSTEM); 2962 if (matches.size() == 0) { 2963 return null; 2964 } else if (matches.size() == 1) { 2965 return matches.get(0).getComponentInfo().getComponentName(); 2966 } else { 2967 throw new RuntimeException( 2968 "There must be at most one ephemeral installer; found " + matches); 2969 } 2970 } 2971 2972 private void primeDomainVerificationsLPw(int userId) { 2973 if (DEBUG_DOMAIN_VERIFICATION) { 2974 Slog.d(TAG, "Priming domain verifications in user " + userId); 2975 } 2976 2977 SystemConfig systemConfig = SystemConfig.getInstance(); 2978 ArraySet<String> packages = systemConfig.getLinkedApps(); 2979 ArraySet<String> domains = new ArraySet<String>(); 2980 2981 for (String packageName : packages) { 2982 PackageParser.Package pkg = mPackages.get(packageName); 2983 if (pkg != null) { 2984 if (!pkg.isSystemApp()) { 2985 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2986 continue; 2987 } 2988 2989 domains.clear(); 2990 for (PackageParser.Activity a : pkg.activities) { 2991 for (ActivityIntentInfo filter : a.intents) { 2992 if (hasValidDomains(filter)) { 2993 domains.addAll(filter.getHostsList()); 2994 } 2995 } 2996 } 2997 2998 if (domains.size() > 0) { 2999 if (DEBUG_DOMAIN_VERIFICATION) { 3000 Slog.v(TAG, " + " + packageName); 3001 } 3002 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3003 // state w.r.t. the formal app-linkage "no verification attempted" state; 3004 // and then 'always' in the per-user state actually used for intent resolution. 3005 final IntentFilterVerificationInfo ivi; 3006 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3007 new ArrayList<String>(domains)); 3008 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3009 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3010 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3011 } else { 3012 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3013 + "' does not handle web links"); 3014 } 3015 } else { 3016 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3017 } 3018 } 3019 3020 scheduleWritePackageRestrictionsLocked(userId); 3021 scheduleWriteSettingsLocked(); 3022 } 3023 3024 private void applyFactoryDefaultBrowserLPw(int userId) { 3025 // The default browser app's package name is stored in a string resource, 3026 // with a product-specific overlay used for vendor customization. 3027 String browserPkg = mContext.getResources().getString( 3028 com.android.internal.R.string.default_browser); 3029 if (!TextUtils.isEmpty(browserPkg)) { 3030 // non-empty string => required to be a known package 3031 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3032 if (ps == null) { 3033 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3034 browserPkg = null; 3035 } else { 3036 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3037 } 3038 } 3039 3040 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3041 // default. If there's more than one, just leave everything alone. 3042 if (browserPkg == null) { 3043 calculateDefaultBrowserLPw(userId); 3044 } 3045 } 3046 3047 private void calculateDefaultBrowserLPw(int userId) { 3048 List<String> allBrowsers = resolveAllBrowserApps(userId); 3049 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3050 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3051 } 3052 3053 private List<String> resolveAllBrowserApps(int userId) { 3054 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3055 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3056 PackageManager.MATCH_ALL, userId); 3057 3058 final int count = list.size(); 3059 List<String> result = new ArrayList<String>(count); 3060 for (int i=0; i<count; i++) { 3061 ResolveInfo info = list.get(i); 3062 if (info.activityInfo == null 3063 || !info.handleAllWebDataURI 3064 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3065 || result.contains(info.activityInfo.packageName)) { 3066 continue; 3067 } 3068 result.add(info.activityInfo.packageName); 3069 } 3070 3071 return result; 3072 } 3073 3074 private boolean packageIsBrowser(String packageName, int userId) { 3075 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3076 PackageManager.MATCH_ALL, userId); 3077 final int N = list.size(); 3078 for (int i = 0; i < N; i++) { 3079 ResolveInfo info = list.get(i); 3080 if (packageName.equals(info.activityInfo.packageName)) { 3081 return true; 3082 } 3083 } 3084 return false; 3085 } 3086 3087 private void checkDefaultBrowser() { 3088 final int myUserId = UserHandle.myUserId(); 3089 final String packageName = getDefaultBrowserPackageName(myUserId); 3090 if (packageName != null) { 3091 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3092 if (info == null) { 3093 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3094 synchronized (mPackages) { 3095 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3096 } 3097 } 3098 } 3099 } 3100 3101 @Override 3102 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3103 throws RemoteException { 3104 try { 3105 return super.onTransact(code, data, reply, flags); 3106 } catch (RuntimeException e) { 3107 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3108 Slog.wtf(TAG, "Package Manager Crash", e); 3109 } 3110 throw e; 3111 } 3112 } 3113 3114 static int[] appendInts(int[] cur, int[] add) { 3115 if (add == null) return cur; 3116 if (cur == null) return add; 3117 final int N = add.length; 3118 for (int i=0; i<N; i++) { 3119 cur = appendInt(cur, add[i]); 3120 } 3121 return cur; 3122 } 3123 3124 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3125 if (!sUserManager.exists(userId)) return null; 3126 if (ps == null) { 3127 return null; 3128 } 3129 final PackageParser.Package p = ps.pkg; 3130 if (p == null) { 3131 return null; 3132 } 3133 3134 final PermissionsState permissionsState = ps.getPermissionsState(); 3135 3136 final int[] gids = permissionsState.computeGids(userId); 3137 final Set<String> permissions = permissionsState.getPermissions(userId); 3138 final PackageUserState state = ps.readUserState(userId); 3139 3140 return PackageParser.generatePackageInfo(p, gids, flags, 3141 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3142 } 3143 3144 @Override 3145 public void checkPackageStartable(String packageName, int userId) { 3146 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3147 3148 synchronized (mPackages) { 3149 final PackageSetting ps = mSettings.mPackages.get(packageName); 3150 if (ps == null) { 3151 throw new SecurityException("Package " + packageName + " was not found!"); 3152 } 3153 3154 if (!ps.getInstalled(userId)) { 3155 throw new SecurityException( 3156 "Package " + packageName + " was not installed for user " + userId + "!"); 3157 } 3158 3159 if (mSafeMode && !ps.isSystem()) { 3160 throw new SecurityException("Package " + packageName + " not a system app!"); 3161 } 3162 3163 if (mFrozenPackages.contains(packageName)) { 3164 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3165 } 3166 3167 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3168 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3169 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3170 } 3171 } 3172 } 3173 3174 @Override 3175 public boolean isPackageAvailable(String packageName, int userId) { 3176 if (!sUserManager.exists(userId)) return false; 3177 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3178 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3179 synchronized (mPackages) { 3180 PackageParser.Package p = mPackages.get(packageName); 3181 if (p != null) { 3182 final PackageSetting ps = (PackageSetting) p.mExtras; 3183 if (ps != null) { 3184 final PackageUserState state = ps.readUserState(userId); 3185 if (state != null) { 3186 return PackageParser.isAvailable(state); 3187 } 3188 } 3189 } 3190 } 3191 return false; 3192 } 3193 3194 @Override 3195 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3196 if (!sUserManager.exists(userId)) return null; 3197 flags = updateFlagsForPackage(flags, userId, packageName); 3198 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3199 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3200 // reader 3201 synchronized (mPackages) { 3202 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3203 PackageParser.Package p = null; 3204 if (matchFactoryOnly) { 3205 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3206 if (ps != null) { 3207 return generatePackageInfo(ps, flags, userId); 3208 } 3209 } 3210 if (p == null) { 3211 p = mPackages.get(packageName); 3212 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3213 return null; 3214 } 3215 } 3216 if (DEBUG_PACKAGE_INFO) 3217 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3218 if (p != null) { 3219 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3220 } 3221 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3222 final PackageSetting ps = mSettings.mPackages.get(packageName); 3223 return generatePackageInfo(ps, flags, userId); 3224 } 3225 } 3226 return null; 3227 } 3228 3229 @Override 3230 public String[] currentToCanonicalPackageNames(String[] names) { 3231 String[] out = new String[names.length]; 3232 // reader 3233 synchronized (mPackages) { 3234 for (int i=names.length-1; i>=0; i--) { 3235 PackageSetting ps = mSettings.mPackages.get(names[i]); 3236 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3237 } 3238 } 3239 return out; 3240 } 3241 3242 @Override 3243 public String[] canonicalToCurrentPackageNames(String[] names) { 3244 String[] out = new String[names.length]; 3245 // reader 3246 synchronized (mPackages) { 3247 for (int i=names.length-1; i>=0; i--) { 3248 String cur = mSettings.mRenamedPackages.get(names[i]); 3249 out[i] = cur != null ? cur : names[i]; 3250 } 3251 } 3252 return out; 3253 } 3254 3255 @Override 3256 public int getPackageUid(String packageName, int flags, int userId) { 3257 if (!sUserManager.exists(userId)) return -1; 3258 flags = updateFlagsForPackage(flags, userId, packageName); 3259 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3260 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3261 3262 // reader 3263 synchronized (mPackages) { 3264 final PackageParser.Package p = mPackages.get(packageName); 3265 if (p != null && p.isMatch(flags)) { 3266 return UserHandle.getUid(userId, p.applicationInfo.uid); 3267 } 3268 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3269 final PackageSetting ps = mSettings.mPackages.get(packageName); 3270 if (ps != null && ps.isMatch(flags)) { 3271 return UserHandle.getUid(userId, ps.appId); 3272 } 3273 } 3274 } 3275 3276 return -1; 3277 } 3278 3279 @Override 3280 public int[] getPackageGids(String packageName, int flags, int userId) { 3281 if (!sUserManager.exists(userId)) return null; 3282 flags = updateFlagsForPackage(flags, userId, packageName); 3283 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3284 false /* requireFullPermission */, false /* checkShell */, 3285 "getPackageGids"); 3286 3287 // reader 3288 synchronized (mPackages) { 3289 final PackageParser.Package p = mPackages.get(packageName); 3290 if (p != null && p.isMatch(flags)) { 3291 PackageSetting ps = (PackageSetting) p.mExtras; 3292 return ps.getPermissionsState().computeGids(userId); 3293 } 3294 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3295 final PackageSetting ps = mSettings.mPackages.get(packageName); 3296 if (ps != null && ps.isMatch(flags)) { 3297 return ps.getPermissionsState().computeGids(userId); 3298 } 3299 } 3300 } 3301 3302 return null; 3303 } 3304 3305 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3306 if (bp.perm != null) { 3307 return PackageParser.generatePermissionInfo(bp.perm, flags); 3308 } 3309 PermissionInfo pi = new PermissionInfo(); 3310 pi.name = bp.name; 3311 pi.packageName = bp.sourcePackage; 3312 pi.nonLocalizedLabel = bp.name; 3313 pi.protectionLevel = bp.protectionLevel; 3314 return pi; 3315 } 3316 3317 @Override 3318 public PermissionInfo getPermissionInfo(String name, int flags) { 3319 // reader 3320 synchronized (mPackages) { 3321 final BasePermission p = mSettings.mPermissions.get(name); 3322 if (p != null) { 3323 return generatePermissionInfo(p, flags); 3324 } 3325 return null; 3326 } 3327 } 3328 3329 @Override 3330 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3331 int flags) { 3332 // reader 3333 synchronized (mPackages) { 3334 if (group != null && !mPermissionGroups.containsKey(group)) { 3335 // This is thrown as NameNotFoundException 3336 return null; 3337 } 3338 3339 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3340 for (BasePermission p : mSettings.mPermissions.values()) { 3341 if (group == null) { 3342 if (p.perm == null || p.perm.info.group == null) { 3343 out.add(generatePermissionInfo(p, flags)); 3344 } 3345 } else { 3346 if (p.perm != null && group.equals(p.perm.info.group)) { 3347 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3348 } 3349 } 3350 } 3351 return new ParceledListSlice<>(out); 3352 } 3353 } 3354 3355 @Override 3356 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3357 // reader 3358 synchronized (mPackages) { 3359 return PackageParser.generatePermissionGroupInfo( 3360 mPermissionGroups.get(name), flags); 3361 } 3362 } 3363 3364 @Override 3365 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3366 // reader 3367 synchronized (mPackages) { 3368 final int N = mPermissionGroups.size(); 3369 ArrayList<PermissionGroupInfo> out 3370 = new ArrayList<PermissionGroupInfo>(N); 3371 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3372 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3373 } 3374 return new ParceledListSlice<>(out); 3375 } 3376 } 3377 3378 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3379 int userId) { 3380 if (!sUserManager.exists(userId)) return null; 3381 PackageSetting ps = mSettings.mPackages.get(packageName); 3382 if (ps != null) { 3383 if (ps.pkg == null) { 3384 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3385 if (pInfo != null) { 3386 return pInfo.applicationInfo; 3387 } 3388 return null; 3389 } 3390 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3391 ps.readUserState(userId), userId); 3392 } 3393 return null; 3394 } 3395 3396 @Override 3397 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3398 if (!sUserManager.exists(userId)) return null; 3399 flags = updateFlagsForApplication(flags, userId, packageName); 3400 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3401 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3402 // writer 3403 synchronized (mPackages) { 3404 PackageParser.Package p = mPackages.get(packageName); 3405 if (DEBUG_PACKAGE_INFO) Log.v( 3406 TAG, "getApplicationInfo " + packageName 3407 + ": " + p); 3408 if (p != null) { 3409 PackageSetting ps = mSettings.mPackages.get(packageName); 3410 if (ps == null) return null; 3411 // Note: isEnabledLP() does not apply here - always return info 3412 return PackageParser.generateApplicationInfo( 3413 p, flags, ps.readUserState(userId), userId); 3414 } 3415 if ("android".equals(packageName)||"system".equals(packageName)) { 3416 return mAndroidApplication; 3417 } 3418 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3419 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3420 } 3421 } 3422 return null; 3423 } 3424 3425 @Override 3426 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3427 final IPackageDataObserver observer) { 3428 mContext.enforceCallingOrSelfPermission( 3429 android.Manifest.permission.CLEAR_APP_CACHE, null); 3430 // Queue up an async operation since clearing cache may take a little while. 3431 mHandler.post(new Runnable() { 3432 public void run() { 3433 mHandler.removeCallbacks(this); 3434 boolean success = true; 3435 synchronized (mInstallLock) { 3436 try { 3437 mInstaller.freeCache(volumeUuid, freeStorageSize); 3438 } catch (InstallerException e) { 3439 Slog.w(TAG, "Couldn't clear application caches: " + e); 3440 success = false; 3441 } 3442 } 3443 if (observer != null) { 3444 try { 3445 observer.onRemoveCompleted(null, success); 3446 } catch (RemoteException e) { 3447 Slog.w(TAG, "RemoveException when invoking call back"); 3448 } 3449 } 3450 } 3451 }); 3452 } 3453 3454 @Override 3455 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3456 final IntentSender pi) { 3457 mContext.enforceCallingOrSelfPermission( 3458 android.Manifest.permission.CLEAR_APP_CACHE, null); 3459 // Queue up an async operation since clearing cache may take a little while. 3460 mHandler.post(new Runnable() { 3461 public void run() { 3462 mHandler.removeCallbacks(this); 3463 boolean success = true; 3464 synchronized (mInstallLock) { 3465 try { 3466 mInstaller.freeCache(volumeUuid, freeStorageSize); 3467 } catch (InstallerException e) { 3468 Slog.w(TAG, "Couldn't clear application caches: " + e); 3469 success = false; 3470 } 3471 } 3472 if(pi != null) { 3473 try { 3474 // Callback via pending intent 3475 int code = success ? 1 : 0; 3476 pi.sendIntent(null, code, null, 3477 null, null); 3478 } catch (SendIntentException e1) { 3479 Slog.i(TAG, "Failed to send pending intent"); 3480 } 3481 } 3482 } 3483 }); 3484 } 3485 3486 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3487 synchronized (mInstallLock) { 3488 try { 3489 mInstaller.freeCache(volumeUuid, freeStorageSize); 3490 } catch (InstallerException e) { 3491 throw new IOException("Failed to free enough space", e); 3492 } 3493 } 3494 } 3495 3496 /** 3497 * Update given flags based on encryption status of current user. 3498 */ 3499 private int updateFlags(int flags, int userId) { 3500 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3501 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3502 // Caller expressed an explicit opinion about what encryption 3503 // aware/unaware components they want to see, so fall through and 3504 // give them what they want 3505 } else { 3506 // Caller expressed no opinion, so match based on user state 3507 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3508 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3509 } else { 3510 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3511 } 3512 } 3513 return flags; 3514 } 3515 3516 private UserManagerInternal getUserManagerInternal() { 3517 if (mUserManagerInternal == null) { 3518 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3519 } 3520 return mUserManagerInternal; 3521 } 3522 3523 /** 3524 * Update given flags when being used to request {@link PackageInfo}. 3525 */ 3526 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3527 boolean triaged = true; 3528 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3529 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3530 // Caller is asking for component details, so they'd better be 3531 // asking for specific encryption matching behavior, or be triaged 3532 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3533 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3534 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3535 triaged = false; 3536 } 3537 } 3538 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3539 | PackageManager.MATCH_SYSTEM_ONLY 3540 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3541 triaged = false; 3542 } 3543 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3544 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3545 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3546 } 3547 return updateFlags(flags, userId); 3548 } 3549 3550 /** 3551 * Update given flags when being used to request {@link ApplicationInfo}. 3552 */ 3553 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3554 return updateFlagsForPackage(flags, userId, cookie); 3555 } 3556 3557 /** 3558 * Update given flags when being used to request {@link ComponentInfo}. 3559 */ 3560 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3561 if (cookie instanceof Intent) { 3562 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3563 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3564 } 3565 } 3566 3567 boolean triaged = true; 3568 // Caller is asking for component details, so they'd better be 3569 // asking for specific encryption matching behavior, or be triaged 3570 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3571 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3572 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3573 triaged = false; 3574 } 3575 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3576 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3577 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3578 } 3579 3580 return updateFlags(flags, userId); 3581 } 3582 3583 /** 3584 * Update given flags when being used to request {@link ResolveInfo}. 3585 */ 3586 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3587 // Safe mode means we shouldn't match any third-party components 3588 if (mSafeMode) { 3589 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3590 } 3591 3592 return updateFlagsForComponent(flags, userId, cookie); 3593 } 3594 3595 @Override 3596 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3597 if (!sUserManager.exists(userId)) return null; 3598 flags = updateFlagsForComponent(flags, userId, component); 3599 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3600 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3601 synchronized (mPackages) { 3602 PackageParser.Activity a = mActivities.mActivities.get(component); 3603 3604 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3605 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3606 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3607 if (ps == null) return null; 3608 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3609 userId); 3610 } 3611 if (mResolveComponentName.equals(component)) { 3612 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3613 new PackageUserState(), userId); 3614 } 3615 } 3616 return null; 3617 } 3618 3619 @Override 3620 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3621 String resolvedType) { 3622 synchronized (mPackages) { 3623 if (component.equals(mResolveComponentName)) { 3624 // The resolver supports EVERYTHING! 3625 return true; 3626 } 3627 PackageParser.Activity a = mActivities.mActivities.get(component); 3628 if (a == null) { 3629 return false; 3630 } 3631 for (int i=0; i<a.intents.size(); i++) { 3632 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3633 intent.getData(), intent.getCategories(), TAG) >= 0) { 3634 return true; 3635 } 3636 } 3637 return false; 3638 } 3639 } 3640 3641 @Override 3642 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3643 if (!sUserManager.exists(userId)) return null; 3644 flags = updateFlagsForComponent(flags, userId, component); 3645 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3646 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3647 synchronized (mPackages) { 3648 PackageParser.Activity a = mReceivers.mActivities.get(component); 3649 if (DEBUG_PACKAGE_INFO) Log.v( 3650 TAG, "getReceiverInfo " + component + ": " + a); 3651 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3652 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3653 if (ps == null) return null; 3654 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3655 userId); 3656 } 3657 } 3658 return null; 3659 } 3660 3661 @Override 3662 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3663 if (!sUserManager.exists(userId)) return null; 3664 flags = updateFlagsForComponent(flags, userId, component); 3665 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3666 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3667 synchronized (mPackages) { 3668 PackageParser.Service s = mServices.mServices.get(component); 3669 if (DEBUG_PACKAGE_INFO) Log.v( 3670 TAG, "getServiceInfo " + component + ": " + s); 3671 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3672 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3673 if (ps == null) return null; 3674 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3675 userId); 3676 } 3677 } 3678 return null; 3679 } 3680 3681 @Override 3682 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3683 if (!sUserManager.exists(userId)) return null; 3684 flags = updateFlagsForComponent(flags, userId, component); 3685 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3686 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3687 synchronized (mPackages) { 3688 PackageParser.Provider p = mProviders.mProviders.get(component); 3689 if (DEBUG_PACKAGE_INFO) Log.v( 3690 TAG, "getProviderInfo " + component + ": " + p); 3691 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3692 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3693 if (ps == null) return null; 3694 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3695 userId); 3696 } 3697 } 3698 return null; 3699 } 3700 3701 @Override 3702 public String[] getSystemSharedLibraryNames() { 3703 Set<String> libSet; 3704 synchronized (mPackages) { 3705 libSet = mSharedLibraries.keySet(); 3706 int size = libSet.size(); 3707 if (size > 0) { 3708 String[] libs = new String[size]; 3709 libSet.toArray(libs); 3710 return libs; 3711 } 3712 } 3713 return null; 3714 } 3715 3716 @Override 3717 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3718 synchronized (mPackages) { 3719 return mServicesSystemSharedLibraryPackageName; 3720 } 3721 } 3722 3723 @Override 3724 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3725 synchronized (mPackages) { 3726 return mSharedSystemSharedLibraryPackageName; 3727 } 3728 } 3729 3730 @Override 3731 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3732 synchronized (mPackages) { 3733 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3734 3735 final FeatureInfo fi = new FeatureInfo(); 3736 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3737 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3738 res.add(fi); 3739 3740 return new ParceledListSlice<>(res); 3741 } 3742 } 3743 3744 @Override 3745 public boolean hasSystemFeature(String name, int version) { 3746 synchronized (mPackages) { 3747 final FeatureInfo feat = mAvailableFeatures.get(name); 3748 if (feat == null) { 3749 return false; 3750 } else { 3751 return feat.version >= version; 3752 } 3753 } 3754 } 3755 3756 @Override 3757 public int checkPermission(String permName, String pkgName, int userId) { 3758 if (!sUserManager.exists(userId)) { 3759 return PackageManager.PERMISSION_DENIED; 3760 } 3761 3762 synchronized (mPackages) { 3763 final PackageParser.Package p = mPackages.get(pkgName); 3764 if (p != null && p.mExtras != null) { 3765 final PackageSetting ps = (PackageSetting) p.mExtras; 3766 final PermissionsState permissionsState = ps.getPermissionsState(); 3767 if (permissionsState.hasPermission(permName, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3771 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3772 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3773 return PackageManager.PERMISSION_GRANTED; 3774 } 3775 } 3776 } 3777 3778 return PackageManager.PERMISSION_DENIED; 3779 } 3780 3781 @Override 3782 public int checkUidPermission(String permName, int uid) { 3783 final int userId = UserHandle.getUserId(uid); 3784 3785 if (!sUserManager.exists(userId)) { 3786 return PackageManager.PERMISSION_DENIED; 3787 } 3788 3789 synchronized (mPackages) { 3790 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3791 if (obj != null) { 3792 final SettingBase ps = (SettingBase) obj; 3793 final PermissionsState permissionsState = ps.getPermissionsState(); 3794 if (permissionsState.hasPermission(permName, userId)) { 3795 return PackageManager.PERMISSION_GRANTED; 3796 } 3797 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3798 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3799 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3800 return PackageManager.PERMISSION_GRANTED; 3801 } 3802 } else { 3803 ArraySet<String> perms = mSystemPermissions.get(uid); 3804 if (perms != null) { 3805 if (perms.contains(permName)) { 3806 return PackageManager.PERMISSION_GRANTED; 3807 } 3808 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3809 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3810 return PackageManager.PERMISSION_GRANTED; 3811 } 3812 } 3813 } 3814 } 3815 3816 return PackageManager.PERMISSION_DENIED; 3817 } 3818 3819 @Override 3820 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3821 if (UserHandle.getCallingUserId() != userId) { 3822 mContext.enforceCallingPermission( 3823 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3824 "isPermissionRevokedByPolicy for user " + userId); 3825 } 3826 3827 if (checkPermission(permission, packageName, userId) 3828 == PackageManager.PERMISSION_GRANTED) { 3829 return false; 3830 } 3831 3832 final long identity = Binder.clearCallingIdentity(); 3833 try { 3834 final int flags = getPermissionFlags(permission, packageName, userId); 3835 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3836 } finally { 3837 Binder.restoreCallingIdentity(identity); 3838 } 3839 } 3840 3841 @Override 3842 public String getPermissionControllerPackageName() { 3843 synchronized (mPackages) { 3844 return mRequiredInstallerPackage; 3845 } 3846 } 3847 3848 /** 3849 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3850 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3851 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3852 * @param message the message to log on security exception 3853 */ 3854 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3855 boolean checkShell, String message) { 3856 if (userId < 0) { 3857 throw new IllegalArgumentException("Invalid userId " + userId); 3858 } 3859 if (checkShell) { 3860 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3861 } 3862 if (userId == UserHandle.getUserId(callingUid)) return; 3863 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3864 if (requireFullPermission) { 3865 mContext.enforceCallingOrSelfPermission( 3866 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3867 } else { 3868 try { 3869 mContext.enforceCallingOrSelfPermission( 3870 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3871 } catch (SecurityException se) { 3872 mContext.enforceCallingOrSelfPermission( 3873 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3874 } 3875 } 3876 } 3877 } 3878 3879 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3880 if (callingUid == Process.SHELL_UID) { 3881 if (userHandle >= 0 3882 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3883 throw new SecurityException("Shell does not have permission to access user " 3884 + userHandle); 3885 } else if (userHandle < 0) { 3886 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3887 + Debug.getCallers(3)); 3888 } 3889 } 3890 } 3891 3892 private BasePermission findPermissionTreeLP(String permName) { 3893 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3894 if (permName.startsWith(bp.name) && 3895 permName.length() > bp.name.length() && 3896 permName.charAt(bp.name.length()) == '.') { 3897 return bp; 3898 } 3899 } 3900 return null; 3901 } 3902 3903 private BasePermission checkPermissionTreeLP(String permName) { 3904 if (permName != null) { 3905 BasePermission bp = findPermissionTreeLP(permName); 3906 if (bp != null) { 3907 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3908 return bp; 3909 } 3910 throw new SecurityException("Calling uid " 3911 + Binder.getCallingUid() 3912 + " is not allowed to add to permission tree " 3913 + bp.name + " owned by uid " + bp.uid); 3914 } 3915 } 3916 throw new SecurityException("No permission tree found for " + permName); 3917 } 3918 3919 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3920 if (s1 == null) { 3921 return s2 == null; 3922 } 3923 if (s2 == null) { 3924 return false; 3925 } 3926 if (s1.getClass() != s2.getClass()) { 3927 return false; 3928 } 3929 return s1.equals(s2); 3930 } 3931 3932 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3933 if (pi1.icon != pi2.icon) return false; 3934 if (pi1.logo != pi2.logo) return false; 3935 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3936 if (!compareStrings(pi1.name, pi2.name)) return false; 3937 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3938 // We'll take care of setting this one. 3939 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3940 // These are not currently stored in settings. 3941 //if (!compareStrings(pi1.group, pi2.group)) return false; 3942 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3943 //if (pi1.labelRes != pi2.labelRes) return false; 3944 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3945 return true; 3946 } 3947 3948 int permissionInfoFootprint(PermissionInfo info) { 3949 int size = info.name.length(); 3950 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3951 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3952 return size; 3953 } 3954 3955 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3956 int size = 0; 3957 for (BasePermission perm : mSettings.mPermissions.values()) { 3958 if (perm.uid == tree.uid) { 3959 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3960 } 3961 } 3962 return size; 3963 } 3964 3965 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3966 // We calculate the max size of permissions defined by this uid and throw 3967 // if that plus the size of 'info' would exceed our stated maximum. 3968 if (tree.uid != Process.SYSTEM_UID) { 3969 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3970 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3971 throw new SecurityException("Permission tree size cap exceeded"); 3972 } 3973 } 3974 } 3975 3976 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3977 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3978 throw new SecurityException("Label must be specified in permission"); 3979 } 3980 BasePermission tree = checkPermissionTreeLP(info.name); 3981 BasePermission bp = mSettings.mPermissions.get(info.name); 3982 boolean added = bp == null; 3983 boolean changed = true; 3984 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3985 if (added) { 3986 enforcePermissionCapLocked(info, tree); 3987 bp = new BasePermission(info.name, tree.sourcePackage, 3988 BasePermission.TYPE_DYNAMIC); 3989 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3990 throw new SecurityException( 3991 "Not allowed to modify non-dynamic permission " 3992 + info.name); 3993 } else { 3994 if (bp.protectionLevel == fixedLevel 3995 && bp.perm.owner.equals(tree.perm.owner) 3996 && bp.uid == tree.uid 3997 && comparePermissionInfos(bp.perm.info, info)) { 3998 changed = false; 3999 } 4000 } 4001 bp.protectionLevel = fixedLevel; 4002 info = new PermissionInfo(info); 4003 info.protectionLevel = fixedLevel; 4004 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4005 bp.perm.info.packageName = tree.perm.info.packageName; 4006 bp.uid = tree.uid; 4007 if (added) { 4008 mSettings.mPermissions.put(info.name, bp); 4009 } 4010 if (changed) { 4011 if (!async) { 4012 mSettings.writeLPr(); 4013 } else { 4014 scheduleWriteSettingsLocked(); 4015 } 4016 } 4017 return added; 4018 } 4019 4020 @Override 4021 public boolean addPermission(PermissionInfo info) { 4022 synchronized (mPackages) { 4023 return addPermissionLocked(info, false); 4024 } 4025 } 4026 4027 @Override 4028 public boolean addPermissionAsync(PermissionInfo info) { 4029 synchronized (mPackages) { 4030 return addPermissionLocked(info, true); 4031 } 4032 } 4033 4034 @Override 4035 public void removePermission(String name) { 4036 synchronized (mPackages) { 4037 checkPermissionTreeLP(name); 4038 BasePermission bp = mSettings.mPermissions.get(name); 4039 if (bp != null) { 4040 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4041 throw new SecurityException( 4042 "Not allowed to modify non-dynamic permission " 4043 + name); 4044 } 4045 mSettings.mPermissions.remove(name); 4046 mSettings.writeLPr(); 4047 } 4048 } 4049 } 4050 4051 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4052 BasePermission bp) { 4053 int index = pkg.requestedPermissions.indexOf(bp.name); 4054 if (index == -1) { 4055 throw new SecurityException("Package " + pkg.packageName 4056 + " has not requested permission " + bp.name); 4057 } 4058 if (!bp.isRuntime() && !bp.isDevelopment()) { 4059 throw new SecurityException("Permission " + bp.name 4060 + " is not a changeable permission type"); 4061 } 4062 } 4063 4064 @Override 4065 public void grantRuntimePermission(String packageName, String name, final int userId) { 4066 if (!sUserManager.exists(userId)) { 4067 Log.e(TAG, "No such user:" + userId); 4068 return; 4069 } 4070 4071 mContext.enforceCallingOrSelfPermission( 4072 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4073 "grantRuntimePermission"); 4074 4075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4076 true /* requireFullPermission */, true /* checkShell */, 4077 "grantRuntimePermission"); 4078 4079 final int uid; 4080 final SettingBase sb; 4081 4082 synchronized (mPackages) { 4083 final PackageParser.Package pkg = mPackages.get(packageName); 4084 if (pkg == null) { 4085 throw new IllegalArgumentException("Unknown package: " + packageName); 4086 } 4087 4088 final BasePermission bp = mSettings.mPermissions.get(name); 4089 if (bp == null) { 4090 throw new IllegalArgumentException("Unknown permission: " + name); 4091 } 4092 4093 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4094 4095 // If a permission review is required for legacy apps we represent 4096 // their permissions as always granted runtime ones since we need 4097 // to keep the review required permission flag per user while an 4098 // install permission's state is shared across all users. 4099 if (Build.PERMISSIONS_REVIEW_REQUIRED 4100 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4101 && bp.isRuntime()) { 4102 return; 4103 } 4104 4105 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4106 sb = (SettingBase) pkg.mExtras; 4107 if (sb == null) { 4108 throw new IllegalArgumentException("Unknown package: " + packageName); 4109 } 4110 4111 final PermissionsState permissionsState = sb.getPermissionsState(); 4112 4113 final int flags = permissionsState.getPermissionFlags(name, userId); 4114 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4115 throw new SecurityException("Cannot grant system fixed permission " 4116 + name + " for package " + packageName); 4117 } 4118 4119 if (bp.isDevelopment()) { 4120 // Development permissions must be handled specially, since they are not 4121 // normal runtime permissions. For now they apply to all users. 4122 if (permissionsState.grantInstallPermission(bp) != 4123 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4124 scheduleWriteSettingsLocked(); 4125 } 4126 return; 4127 } 4128 4129 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4130 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4131 return; 4132 } 4133 4134 final int result = permissionsState.grantRuntimePermission(bp, userId); 4135 switch (result) { 4136 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4137 return; 4138 } 4139 4140 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4141 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4142 mHandler.post(new Runnable() { 4143 @Override 4144 public void run() { 4145 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4146 } 4147 }); 4148 } 4149 break; 4150 } 4151 4152 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4153 4154 // Not critical if that is lost - app has to request again. 4155 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4156 } 4157 4158 // Only need to do this if user is initialized. Otherwise it's a new user 4159 // and there are no processes running as the user yet and there's no need 4160 // to make an expensive call to remount processes for the changed permissions. 4161 if (READ_EXTERNAL_STORAGE.equals(name) 4162 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4163 final long token = Binder.clearCallingIdentity(); 4164 try { 4165 if (sUserManager.isInitialized(userId)) { 4166 MountServiceInternal mountServiceInternal = LocalServices.getService( 4167 MountServiceInternal.class); 4168 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4169 } 4170 } finally { 4171 Binder.restoreCallingIdentity(token); 4172 } 4173 } 4174 } 4175 4176 @Override 4177 public void revokeRuntimePermission(String packageName, String name, int userId) { 4178 if (!sUserManager.exists(userId)) { 4179 Log.e(TAG, "No such user:" + userId); 4180 return; 4181 } 4182 4183 mContext.enforceCallingOrSelfPermission( 4184 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4185 "revokeRuntimePermission"); 4186 4187 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4188 true /* requireFullPermission */, true /* checkShell */, 4189 "revokeRuntimePermission"); 4190 4191 final int appId; 4192 4193 synchronized (mPackages) { 4194 final PackageParser.Package pkg = mPackages.get(packageName); 4195 if (pkg == null) { 4196 throw new IllegalArgumentException("Unknown package: " + packageName); 4197 } 4198 4199 final BasePermission bp = mSettings.mPermissions.get(name); 4200 if (bp == null) { 4201 throw new IllegalArgumentException("Unknown permission: " + name); 4202 } 4203 4204 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4205 4206 // If a permission review is required for legacy apps we represent 4207 // their permissions as always granted runtime ones since we need 4208 // to keep the review required permission flag per user while an 4209 // install permission's state is shared across all users. 4210 if (Build.PERMISSIONS_REVIEW_REQUIRED 4211 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4212 && bp.isRuntime()) { 4213 return; 4214 } 4215 4216 SettingBase sb = (SettingBase) pkg.mExtras; 4217 if (sb == null) { 4218 throw new IllegalArgumentException("Unknown package: " + packageName); 4219 } 4220 4221 final PermissionsState permissionsState = sb.getPermissionsState(); 4222 4223 final int flags = permissionsState.getPermissionFlags(name, userId); 4224 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4225 throw new SecurityException("Cannot revoke system fixed permission " 4226 + name + " for package " + packageName); 4227 } 4228 4229 if (bp.isDevelopment()) { 4230 // Development permissions must be handled specially, since they are not 4231 // normal runtime permissions. For now they apply to all users. 4232 if (permissionsState.revokeInstallPermission(bp) != 4233 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4234 scheduleWriteSettingsLocked(); 4235 } 4236 return; 4237 } 4238 4239 if (permissionsState.revokeRuntimePermission(bp, userId) == 4240 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4241 return; 4242 } 4243 4244 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4245 4246 // Critical, after this call app should never have the permission. 4247 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4248 4249 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4250 } 4251 4252 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4253 } 4254 4255 @Override 4256 public void resetRuntimePermissions() { 4257 mContext.enforceCallingOrSelfPermission( 4258 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4259 "revokeRuntimePermission"); 4260 4261 int callingUid = Binder.getCallingUid(); 4262 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4263 mContext.enforceCallingOrSelfPermission( 4264 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4265 "resetRuntimePermissions"); 4266 } 4267 4268 synchronized (mPackages) { 4269 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4270 for (int userId : UserManagerService.getInstance().getUserIds()) { 4271 final int packageCount = mPackages.size(); 4272 for (int i = 0; i < packageCount; i++) { 4273 PackageParser.Package pkg = mPackages.valueAt(i); 4274 if (!(pkg.mExtras instanceof PackageSetting)) { 4275 continue; 4276 } 4277 PackageSetting ps = (PackageSetting) pkg.mExtras; 4278 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4279 } 4280 } 4281 } 4282 } 4283 4284 @Override 4285 public int getPermissionFlags(String name, String packageName, int userId) { 4286 if (!sUserManager.exists(userId)) { 4287 return 0; 4288 } 4289 4290 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4291 4292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4293 true /* requireFullPermission */, false /* checkShell */, 4294 "getPermissionFlags"); 4295 4296 synchronized (mPackages) { 4297 final PackageParser.Package pkg = mPackages.get(packageName); 4298 if (pkg == null) { 4299 return 0; 4300 } 4301 4302 final BasePermission bp = mSettings.mPermissions.get(name); 4303 if (bp == null) { 4304 return 0; 4305 } 4306 4307 SettingBase sb = (SettingBase) pkg.mExtras; 4308 if (sb == null) { 4309 return 0; 4310 } 4311 4312 PermissionsState permissionsState = sb.getPermissionsState(); 4313 return permissionsState.getPermissionFlags(name, userId); 4314 } 4315 } 4316 4317 @Override 4318 public void updatePermissionFlags(String name, String packageName, int flagMask, 4319 int flagValues, int userId) { 4320 if (!sUserManager.exists(userId)) { 4321 return; 4322 } 4323 4324 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4325 4326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4327 true /* requireFullPermission */, true /* checkShell */, 4328 "updatePermissionFlags"); 4329 4330 // Only the system can change these flags and nothing else. 4331 if (getCallingUid() != Process.SYSTEM_UID) { 4332 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4333 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4334 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4335 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4336 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4337 } 4338 4339 synchronized (mPackages) { 4340 final PackageParser.Package pkg = mPackages.get(packageName); 4341 if (pkg == null) { 4342 throw new IllegalArgumentException("Unknown package: " + packageName); 4343 } 4344 4345 final BasePermission bp = mSettings.mPermissions.get(name); 4346 if (bp == null) { 4347 throw new IllegalArgumentException("Unknown permission: " + name); 4348 } 4349 4350 SettingBase sb = (SettingBase) pkg.mExtras; 4351 if (sb == null) { 4352 throw new IllegalArgumentException("Unknown package: " + packageName); 4353 } 4354 4355 PermissionsState permissionsState = sb.getPermissionsState(); 4356 4357 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4358 4359 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4360 // Install and runtime permissions are stored in different places, 4361 // so figure out what permission changed and persist the change. 4362 if (permissionsState.getInstallPermissionState(name) != null) { 4363 scheduleWriteSettingsLocked(); 4364 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4365 || hadState) { 4366 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4367 } 4368 } 4369 } 4370 } 4371 4372 /** 4373 * Update the permission flags for all packages and runtime permissions of a user in order 4374 * to allow device or profile owner to remove POLICY_FIXED. 4375 */ 4376 @Override 4377 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4378 if (!sUserManager.exists(userId)) { 4379 return; 4380 } 4381 4382 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4383 4384 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4385 true /* requireFullPermission */, true /* checkShell */, 4386 "updatePermissionFlagsForAllApps"); 4387 4388 // Only the system can change system fixed flags. 4389 if (getCallingUid() != Process.SYSTEM_UID) { 4390 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4391 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4392 } 4393 4394 synchronized (mPackages) { 4395 boolean changed = false; 4396 final int packageCount = mPackages.size(); 4397 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4398 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4399 SettingBase sb = (SettingBase) pkg.mExtras; 4400 if (sb == null) { 4401 continue; 4402 } 4403 PermissionsState permissionsState = sb.getPermissionsState(); 4404 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4405 userId, flagMask, flagValues); 4406 } 4407 if (changed) { 4408 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4409 } 4410 } 4411 } 4412 4413 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4414 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4415 != PackageManager.PERMISSION_GRANTED 4416 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4417 != PackageManager.PERMISSION_GRANTED) { 4418 throw new SecurityException(message + " requires " 4419 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4420 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4421 } 4422 } 4423 4424 @Override 4425 public boolean shouldShowRequestPermissionRationale(String permissionName, 4426 String packageName, int userId) { 4427 if (UserHandle.getCallingUserId() != userId) { 4428 mContext.enforceCallingPermission( 4429 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4430 "canShowRequestPermissionRationale for user " + userId); 4431 } 4432 4433 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4434 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4435 return false; 4436 } 4437 4438 if (checkPermission(permissionName, packageName, userId) 4439 == PackageManager.PERMISSION_GRANTED) { 4440 return false; 4441 } 4442 4443 final int flags; 4444 4445 final long identity = Binder.clearCallingIdentity(); 4446 try { 4447 flags = getPermissionFlags(permissionName, 4448 packageName, userId); 4449 } finally { 4450 Binder.restoreCallingIdentity(identity); 4451 } 4452 4453 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4454 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4455 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4456 4457 if ((flags & fixedFlags) != 0) { 4458 return false; 4459 } 4460 4461 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4462 } 4463 4464 @Override 4465 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4466 mContext.enforceCallingOrSelfPermission( 4467 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4468 "addOnPermissionsChangeListener"); 4469 4470 synchronized (mPackages) { 4471 mOnPermissionChangeListeners.addListenerLocked(listener); 4472 } 4473 } 4474 4475 @Override 4476 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4477 synchronized (mPackages) { 4478 mOnPermissionChangeListeners.removeListenerLocked(listener); 4479 } 4480 } 4481 4482 @Override 4483 public boolean isProtectedBroadcast(String actionName) { 4484 synchronized (mPackages) { 4485 if (mProtectedBroadcasts.contains(actionName)) { 4486 return true; 4487 } else if (actionName != null) { 4488 // TODO: remove these terrible hacks 4489 if (actionName.startsWith("android.net.netmon.lingerExpired") 4490 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4491 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4492 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4493 return true; 4494 } 4495 } 4496 } 4497 return false; 4498 } 4499 4500 @Override 4501 public int checkSignatures(String pkg1, String pkg2) { 4502 synchronized (mPackages) { 4503 final PackageParser.Package p1 = mPackages.get(pkg1); 4504 final PackageParser.Package p2 = mPackages.get(pkg2); 4505 if (p1 == null || p1.mExtras == null 4506 || p2 == null || p2.mExtras == null) { 4507 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4508 } 4509 return compareSignatures(p1.mSignatures, p2.mSignatures); 4510 } 4511 } 4512 4513 @Override 4514 public int checkUidSignatures(int uid1, int uid2) { 4515 // Map to base uids. 4516 uid1 = UserHandle.getAppId(uid1); 4517 uid2 = UserHandle.getAppId(uid2); 4518 // reader 4519 synchronized (mPackages) { 4520 Signature[] s1; 4521 Signature[] s2; 4522 Object obj = mSettings.getUserIdLPr(uid1); 4523 if (obj != null) { 4524 if (obj instanceof SharedUserSetting) { 4525 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4526 } else if (obj instanceof PackageSetting) { 4527 s1 = ((PackageSetting)obj).signatures.mSignatures; 4528 } else { 4529 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4530 } 4531 } else { 4532 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4533 } 4534 obj = mSettings.getUserIdLPr(uid2); 4535 if (obj != null) { 4536 if (obj instanceof SharedUserSetting) { 4537 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4538 } else if (obj instanceof PackageSetting) { 4539 s2 = ((PackageSetting)obj).signatures.mSignatures; 4540 } else { 4541 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4542 } 4543 } else { 4544 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4545 } 4546 return compareSignatures(s1, s2); 4547 } 4548 } 4549 4550 /** 4551 * This method should typically only be used when granting or revoking 4552 * permissions, since the app may immediately restart after this call. 4553 * <p> 4554 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4555 * guard your work against the app being relaunched. 4556 */ 4557 private void killUid(int appId, int userId, String reason) { 4558 final long identity = Binder.clearCallingIdentity(); 4559 try { 4560 IActivityManager am = ActivityManagerNative.getDefault(); 4561 if (am != null) { 4562 try { 4563 am.killUid(appId, userId, reason); 4564 } catch (RemoteException e) { 4565 /* ignore - same process */ 4566 } 4567 } 4568 } finally { 4569 Binder.restoreCallingIdentity(identity); 4570 } 4571 } 4572 4573 /** 4574 * Compares two sets of signatures. Returns: 4575 * <br /> 4576 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4577 * <br /> 4578 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4579 * <br /> 4580 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4581 * <br /> 4582 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4583 * <br /> 4584 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4585 */ 4586 static int compareSignatures(Signature[] s1, Signature[] s2) { 4587 if (s1 == null) { 4588 return s2 == null 4589 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4590 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4591 } 4592 4593 if (s2 == null) { 4594 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4595 } 4596 4597 if (s1.length != s2.length) { 4598 return PackageManager.SIGNATURE_NO_MATCH; 4599 } 4600 4601 // Since both signature sets are of size 1, we can compare without HashSets. 4602 if (s1.length == 1) { 4603 return s1[0].equals(s2[0]) ? 4604 PackageManager.SIGNATURE_MATCH : 4605 PackageManager.SIGNATURE_NO_MATCH; 4606 } 4607 4608 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4609 for (Signature sig : s1) { 4610 set1.add(sig); 4611 } 4612 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4613 for (Signature sig : s2) { 4614 set2.add(sig); 4615 } 4616 // Make sure s2 contains all signatures in s1. 4617 if (set1.equals(set2)) { 4618 return PackageManager.SIGNATURE_MATCH; 4619 } 4620 return PackageManager.SIGNATURE_NO_MATCH; 4621 } 4622 4623 /** 4624 * If the database version for this type of package (internal storage or 4625 * external storage) is less than the version where package signatures 4626 * were updated, return true. 4627 */ 4628 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4629 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4630 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4631 } 4632 4633 /** 4634 * Used for backward compatibility to make sure any packages with 4635 * certificate chains get upgraded to the new style. {@code existingSigs} 4636 * will be in the old format (since they were stored on disk from before the 4637 * system upgrade) and {@code scannedSigs} will be in the newer format. 4638 */ 4639 private int compareSignaturesCompat(PackageSignatures existingSigs, 4640 PackageParser.Package scannedPkg) { 4641 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4642 return PackageManager.SIGNATURE_NO_MATCH; 4643 } 4644 4645 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4646 for (Signature sig : existingSigs.mSignatures) { 4647 existingSet.add(sig); 4648 } 4649 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4650 for (Signature sig : scannedPkg.mSignatures) { 4651 try { 4652 Signature[] chainSignatures = sig.getChainSignatures(); 4653 for (Signature chainSig : chainSignatures) { 4654 scannedCompatSet.add(chainSig); 4655 } 4656 } catch (CertificateEncodingException e) { 4657 scannedCompatSet.add(sig); 4658 } 4659 } 4660 /* 4661 * Make sure the expanded scanned set contains all signatures in the 4662 * existing one. 4663 */ 4664 if (scannedCompatSet.equals(existingSet)) { 4665 // Migrate the old signatures to the new scheme. 4666 existingSigs.assignSignatures(scannedPkg.mSignatures); 4667 // The new KeySets will be re-added later in the scanning process. 4668 synchronized (mPackages) { 4669 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4670 } 4671 return PackageManager.SIGNATURE_MATCH; 4672 } 4673 return PackageManager.SIGNATURE_NO_MATCH; 4674 } 4675 4676 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4677 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4678 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4679 } 4680 4681 private int compareSignaturesRecover(PackageSignatures existingSigs, 4682 PackageParser.Package scannedPkg) { 4683 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4684 return PackageManager.SIGNATURE_NO_MATCH; 4685 } 4686 4687 String msg = null; 4688 try { 4689 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4690 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4691 + scannedPkg.packageName); 4692 return PackageManager.SIGNATURE_MATCH; 4693 } 4694 } catch (CertificateException e) { 4695 msg = e.getMessage(); 4696 } 4697 4698 logCriticalInfo(Log.INFO, 4699 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4700 return PackageManager.SIGNATURE_NO_MATCH; 4701 } 4702 4703 @Override 4704 public List<String> getAllPackages() { 4705 synchronized (mPackages) { 4706 return new ArrayList<String>(mPackages.keySet()); 4707 } 4708 } 4709 4710 @Override 4711 public String[] getPackagesForUid(int uid) { 4712 uid = UserHandle.getAppId(uid); 4713 // reader 4714 synchronized (mPackages) { 4715 Object obj = mSettings.getUserIdLPr(uid); 4716 if (obj instanceof SharedUserSetting) { 4717 final SharedUserSetting sus = (SharedUserSetting) obj; 4718 final int N = sus.packages.size(); 4719 final String[] res = new String[N]; 4720 final Iterator<PackageSetting> it = sus.packages.iterator(); 4721 int i = 0; 4722 while (it.hasNext()) { 4723 res[i++] = it.next().name; 4724 } 4725 return res; 4726 } else if (obj instanceof PackageSetting) { 4727 final PackageSetting ps = (PackageSetting) obj; 4728 return new String[] { ps.name }; 4729 } 4730 } 4731 return null; 4732 } 4733 4734 @Override 4735 public String getNameForUid(int uid) { 4736 // reader 4737 synchronized (mPackages) { 4738 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4739 if (obj instanceof SharedUserSetting) { 4740 final SharedUserSetting sus = (SharedUserSetting) obj; 4741 return sus.name + ":" + sus.userId; 4742 } else if (obj instanceof PackageSetting) { 4743 final PackageSetting ps = (PackageSetting) obj; 4744 return ps.name; 4745 } 4746 } 4747 return null; 4748 } 4749 4750 @Override 4751 public int getUidForSharedUser(String sharedUserName) { 4752 if(sharedUserName == null) { 4753 return -1; 4754 } 4755 // reader 4756 synchronized (mPackages) { 4757 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4758 if (suid == null) { 4759 return -1; 4760 } 4761 return suid.userId; 4762 } 4763 } 4764 4765 @Override 4766 public int getFlagsForUid(int uid) { 4767 synchronized (mPackages) { 4768 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4769 if (obj instanceof SharedUserSetting) { 4770 final SharedUserSetting sus = (SharedUserSetting) obj; 4771 return sus.pkgFlags; 4772 } else if (obj instanceof PackageSetting) { 4773 final PackageSetting ps = (PackageSetting) obj; 4774 return ps.pkgFlags; 4775 } 4776 } 4777 return 0; 4778 } 4779 4780 @Override 4781 public int getPrivateFlagsForUid(int uid) { 4782 synchronized (mPackages) { 4783 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4784 if (obj instanceof SharedUserSetting) { 4785 final SharedUserSetting sus = (SharedUserSetting) obj; 4786 return sus.pkgPrivateFlags; 4787 } else if (obj instanceof PackageSetting) { 4788 final PackageSetting ps = (PackageSetting) obj; 4789 return ps.pkgPrivateFlags; 4790 } 4791 } 4792 return 0; 4793 } 4794 4795 @Override 4796 public boolean isUidPrivileged(int uid) { 4797 uid = UserHandle.getAppId(uid); 4798 // reader 4799 synchronized (mPackages) { 4800 Object obj = mSettings.getUserIdLPr(uid); 4801 if (obj instanceof SharedUserSetting) { 4802 final SharedUserSetting sus = (SharedUserSetting) obj; 4803 final Iterator<PackageSetting> it = sus.packages.iterator(); 4804 while (it.hasNext()) { 4805 if (it.next().isPrivileged()) { 4806 return true; 4807 } 4808 } 4809 } else if (obj instanceof PackageSetting) { 4810 final PackageSetting ps = (PackageSetting) obj; 4811 return ps.isPrivileged(); 4812 } 4813 } 4814 return false; 4815 } 4816 4817 @Override 4818 public String[] getAppOpPermissionPackages(String permissionName) { 4819 synchronized (mPackages) { 4820 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4821 if (pkgs == null) { 4822 return null; 4823 } 4824 return pkgs.toArray(new String[pkgs.size()]); 4825 } 4826 } 4827 4828 @Override 4829 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4830 int flags, int userId) { 4831 try { 4832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4833 4834 if (!sUserManager.exists(userId)) return null; 4835 flags = updateFlagsForResolve(flags, userId, intent); 4836 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4837 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4838 4839 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4840 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4841 flags, userId); 4842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4843 4844 final ResolveInfo bestChoice = 4845 chooseBestActivity(intent, resolvedType, flags, query, userId); 4846 4847 if (isEphemeralAllowed(intent, query, userId)) { 4848 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4849 final EphemeralResolveInfo ai = 4850 getEphemeralResolveInfo(intent, resolvedType, userId); 4851 if (ai != null) { 4852 if (DEBUG_EPHEMERAL) { 4853 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4854 } 4855 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4856 bestChoice.ephemeralResolveInfo = ai; 4857 } 4858 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4859 } 4860 return bestChoice; 4861 } finally { 4862 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4863 } 4864 } 4865 4866 @Override 4867 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4868 IntentFilter filter, int match, ComponentName activity) { 4869 final int userId = UserHandle.getCallingUserId(); 4870 if (DEBUG_PREFERRED) { 4871 Log.v(TAG, "setLastChosenActivity intent=" + intent 4872 + " resolvedType=" + resolvedType 4873 + " flags=" + flags 4874 + " filter=" + filter 4875 + " match=" + match 4876 + " activity=" + activity); 4877 filter.dump(new PrintStreamPrinter(System.out), " "); 4878 } 4879 intent.setComponent(null); 4880 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4881 userId); 4882 // Find any earlier preferred or last chosen entries and nuke them 4883 findPreferredActivity(intent, resolvedType, 4884 flags, query, 0, false, true, false, userId); 4885 // Add the new activity as the last chosen for this filter 4886 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4887 "Setting last chosen"); 4888 } 4889 4890 @Override 4891 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4892 final int userId = UserHandle.getCallingUserId(); 4893 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4894 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4895 userId); 4896 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4897 false, false, false, userId); 4898 } 4899 4900 4901 private boolean isEphemeralAllowed( 4902 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4903 // Short circuit and return early if possible. 4904 if (DISABLE_EPHEMERAL_APPS) { 4905 return false; 4906 } 4907 final int callingUser = UserHandle.getCallingUserId(); 4908 if (callingUser != UserHandle.USER_SYSTEM) { 4909 return false; 4910 } 4911 if (mEphemeralResolverConnection == null) { 4912 return false; 4913 } 4914 if (intent.getComponent() != null) { 4915 return false; 4916 } 4917 if (intent.getPackage() != null) { 4918 return false; 4919 } 4920 final boolean isWebUri = hasWebURI(intent); 4921 if (!isWebUri) { 4922 return false; 4923 } 4924 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4925 synchronized (mPackages) { 4926 final int count = resolvedActivites.size(); 4927 for (int n = 0; n < count; n++) { 4928 ResolveInfo info = resolvedActivites.get(n); 4929 String packageName = info.activityInfo.packageName; 4930 PackageSetting ps = mSettings.mPackages.get(packageName); 4931 if (ps != null) { 4932 // Try to get the status from User settings first 4933 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4934 int status = (int) (packedStatus >> 32); 4935 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4936 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4937 if (DEBUG_EPHEMERAL) { 4938 Slog.v(TAG, "DENY ephemeral apps;" 4939 + " pkg: " + packageName + ", status: " + status); 4940 } 4941 return false; 4942 } 4943 } 4944 } 4945 } 4946 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4947 return true; 4948 } 4949 4950 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4951 int userId) { 4952 MessageDigest digest = null; 4953 try { 4954 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4955 } catch (NoSuchAlgorithmException e) { 4956 // If we can't create a digest, ignore ephemeral apps. 4957 return null; 4958 } 4959 4960 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4961 final byte[] digestBytes = digest.digest(hostBytes); 4962 int shaPrefix = 4963 digestBytes[0] << 24 4964 | digestBytes[1] << 16 4965 | digestBytes[2] << 8 4966 | digestBytes[3] << 0; 4967 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4968 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4969 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4970 // No hash prefix match; there are no ephemeral apps for this domain. 4971 return null; 4972 } 4973 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4974 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4975 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4976 continue; 4977 } 4978 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4979 // No filters; this should never happen. 4980 if (filters.isEmpty()) { 4981 continue; 4982 } 4983 // We have a domain match; resolve the filters to see if anything matches. 4984 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4985 for (int j = filters.size() - 1; j >= 0; --j) { 4986 final EphemeralResolveIntentInfo intentInfo = 4987 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4988 ephemeralResolver.addFilter(intentInfo); 4989 } 4990 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4991 intent, resolvedType, false /*defaultOnly*/, userId); 4992 if (!matchedResolveInfoList.isEmpty()) { 4993 return matchedResolveInfoList.get(0); 4994 } 4995 } 4996 // Hash or filter mis-match; no ephemeral apps for this domain. 4997 return null; 4998 } 4999 5000 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5001 int flags, List<ResolveInfo> query, int userId) { 5002 if (query != null) { 5003 final int N = query.size(); 5004 if (N == 1) { 5005 return query.get(0); 5006 } else if (N > 1) { 5007 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5008 // If there is more than one activity with the same priority, 5009 // then let the user decide between them. 5010 ResolveInfo r0 = query.get(0); 5011 ResolveInfo r1 = query.get(1); 5012 if (DEBUG_INTENT_MATCHING || debug) { 5013 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5014 + r1.activityInfo.name + "=" + r1.priority); 5015 } 5016 // If the first activity has a higher priority, or a different 5017 // default, then it is always desirable to pick it. 5018 if (r0.priority != r1.priority 5019 || r0.preferredOrder != r1.preferredOrder 5020 || r0.isDefault != r1.isDefault) { 5021 return query.get(0); 5022 } 5023 // If we have saved a preference for a preferred activity for 5024 // this Intent, use that. 5025 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5026 flags, query, r0.priority, true, false, debug, userId); 5027 if (ri != null) { 5028 return ri; 5029 } 5030 ri = new ResolveInfo(mResolveInfo); 5031 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5032 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5033 // If all of the options come from the same package, show the application's 5034 // label and icon instead of the generic resolver's. 5035 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5036 // and then throw away the ResolveInfo itself, meaning that the caller loses 5037 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5038 // a fallback for this case; we only set the target package's resources on 5039 // the ResolveInfo, not the ActivityInfo. 5040 final String intentPackage = intent.getPackage(); 5041 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5042 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5043 ri.resolvePackageName = intentPackage; 5044 if (userNeedsBadging(userId)) { 5045 ri.noResourceId = true; 5046 } else { 5047 ri.icon = appi.icon; 5048 } 5049 ri.iconResourceId = appi.icon; 5050 ri.labelRes = appi.labelRes; 5051 } 5052 ri.activityInfo.applicationInfo = new ApplicationInfo( 5053 ri.activityInfo.applicationInfo); 5054 if (userId != 0) { 5055 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5056 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5057 } 5058 // Make sure that the resolver is displayable in car mode 5059 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5060 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5061 return ri; 5062 } 5063 } 5064 return null; 5065 } 5066 5067 /** 5068 * Return true if the given list is not empty and all of its contents have 5069 * an activityInfo with the given package name. 5070 */ 5071 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5072 if (ArrayUtils.isEmpty(list)) { 5073 return false; 5074 } 5075 for (int i = 0, N = list.size(); i < N; i++) { 5076 final ResolveInfo ri = list.get(i); 5077 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5078 if (ai == null || !packageName.equals(ai.packageName)) { 5079 return false; 5080 } 5081 } 5082 return true; 5083 } 5084 5085 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5086 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5087 final int N = query.size(); 5088 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5089 .get(userId); 5090 // Get the list of persistent preferred activities that handle the intent 5091 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5092 List<PersistentPreferredActivity> pprefs = ppir != null 5093 ? ppir.queryIntent(intent, resolvedType, 5094 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5095 : null; 5096 if (pprefs != null && pprefs.size() > 0) { 5097 final int M = pprefs.size(); 5098 for (int i=0; i<M; i++) { 5099 final PersistentPreferredActivity ppa = pprefs.get(i); 5100 if (DEBUG_PREFERRED || debug) { 5101 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5102 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5103 + "\n component=" + ppa.mComponent); 5104 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5105 } 5106 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5107 flags | MATCH_DISABLED_COMPONENTS, userId); 5108 if (DEBUG_PREFERRED || debug) { 5109 Slog.v(TAG, "Found persistent preferred activity:"); 5110 if (ai != null) { 5111 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5112 } else { 5113 Slog.v(TAG, " null"); 5114 } 5115 } 5116 if (ai == null) { 5117 // This previously registered persistent preferred activity 5118 // component is no longer known. Ignore it and do NOT remove it. 5119 continue; 5120 } 5121 for (int j=0; j<N; j++) { 5122 final ResolveInfo ri = query.get(j); 5123 if (!ri.activityInfo.applicationInfo.packageName 5124 .equals(ai.applicationInfo.packageName)) { 5125 continue; 5126 } 5127 if (!ri.activityInfo.name.equals(ai.name)) { 5128 continue; 5129 } 5130 // Found a persistent preference that can handle the intent. 5131 if (DEBUG_PREFERRED || debug) { 5132 Slog.v(TAG, "Returning persistent preferred activity: " + 5133 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5134 } 5135 return ri; 5136 } 5137 } 5138 } 5139 return null; 5140 } 5141 5142 // TODO: handle preferred activities missing while user has amnesia 5143 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5144 List<ResolveInfo> query, int priority, boolean always, 5145 boolean removeMatches, boolean debug, int userId) { 5146 if (!sUserManager.exists(userId)) return null; 5147 flags = updateFlagsForResolve(flags, userId, intent); 5148 // writer 5149 synchronized (mPackages) { 5150 if (intent.getSelector() != null) { 5151 intent = intent.getSelector(); 5152 } 5153 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5154 5155 // Try to find a matching persistent preferred activity. 5156 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5157 debug, userId); 5158 5159 // If a persistent preferred activity matched, use it. 5160 if (pri != null) { 5161 return pri; 5162 } 5163 5164 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5165 // Get the list of preferred activities that handle the intent 5166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5167 List<PreferredActivity> prefs = pir != null 5168 ? pir.queryIntent(intent, resolvedType, 5169 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5170 : null; 5171 if (prefs != null && prefs.size() > 0) { 5172 boolean changed = false; 5173 try { 5174 // First figure out how good the original match set is. 5175 // We will only allow preferred activities that came 5176 // from the same match quality. 5177 int match = 0; 5178 5179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5180 5181 final int N = query.size(); 5182 for (int j=0; j<N; j++) { 5183 final ResolveInfo ri = query.get(j); 5184 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5185 + ": 0x" + Integer.toHexString(match)); 5186 if (ri.match > match) { 5187 match = ri.match; 5188 } 5189 } 5190 5191 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5192 + Integer.toHexString(match)); 5193 5194 match &= IntentFilter.MATCH_CATEGORY_MASK; 5195 final int M = prefs.size(); 5196 for (int i=0; i<M; i++) { 5197 final PreferredActivity pa = prefs.get(i); 5198 if (DEBUG_PREFERRED || debug) { 5199 Slog.v(TAG, "Checking PreferredActivity ds=" 5200 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5201 + "\n component=" + pa.mPref.mComponent); 5202 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5203 } 5204 if (pa.mPref.mMatch != match) { 5205 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5206 + Integer.toHexString(pa.mPref.mMatch)); 5207 continue; 5208 } 5209 // If it's not an "always" type preferred activity and that's what we're 5210 // looking for, skip it. 5211 if (always && !pa.mPref.mAlways) { 5212 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5213 continue; 5214 } 5215 final ActivityInfo ai = getActivityInfo( 5216 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5217 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5218 userId); 5219 if (DEBUG_PREFERRED || debug) { 5220 Slog.v(TAG, "Found preferred activity:"); 5221 if (ai != null) { 5222 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5223 } else { 5224 Slog.v(TAG, " null"); 5225 } 5226 } 5227 if (ai == null) { 5228 // This previously registered preferred activity 5229 // component is no longer known. Most likely an update 5230 // to the app was installed and in the new version this 5231 // component no longer exists. Clean it up by removing 5232 // it from the preferred activities list, and skip it. 5233 Slog.w(TAG, "Removing dangling preferred activity: " 5234 + pa.mPref.mComponent); 5235 pir.removeFilter(pa); 5236 changed = true; 5237 continue; 5238 } 5239 for (int j=0; j<N; j++) { 5240 final ResolveInfo ri = query.get(j); 5241 if (!ri.activityInfo.applicationInfo.packageName 5242 .equals(ai.applicationInfo.packageName)) { 5243 continue; 5244 } 5245 if (!ri.activityInfo.name.equals(ai.name)) { 5246 continue; 5247 } 5248 5249 if (removeMatches) { 5250 pir.removeFilter(pa); 5251 changed = true; 5252 if (DEBUG_PREFERRED) { 5253 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5254 } 5255 break; 5256 } 5257 5258 // Okay we found a previously set preferred or last chosen app. 5259 // If the result set is different from when this 5260 // was created, we need to clear it and re-ask the 5261 // user their preference, if we're looking for an "always" type entry. 5262 if (always && !pa.mPref.sameSet(query)) { 5263 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5264 + intent + " type " + resolvedType); 5265 if (DEBUG_PREFERRED) { 5266 Slog.v(TAG, "Removing preferred activity since set changed " 5267 + pa.mPref.mComponent); 5268 } 5269 pir.removeFilter(pa); 5270 // Re-add the filter as a "last chosen" entry (!always) 5271 PreferredActivity lastChosen = new PreferredActivity( 5272 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5273 pir.addFilter(lastChosen); 5274 changed = true; 5275 return null; 5276 } 5277 5278 // Yay! Either the set matched or we're looking for the last chosen 5279 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5280 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5281 return ri; 5282 } 5283 } 5284 } finally { 5285 if (changed) { 5286 if (DEBUG_PREFERRED) { 5287 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5288 } 5289 scheduleWritePackageRestrictionsLocked(userId); 5290 } 5291 } 5292 } 5293 } 5294 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5295 return null; 5296 } 5297 5298 /* 5299 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5300 */ 5301 @Override 5302 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5303 int targetUserId) { 5304 mContext.enforceCallingOrSelfPermission( 5305 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5306 List<CrossProfileIntentFilter> matches = 5307 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5308 if (matches != null) { 5309 int size = matches.size(); 5310 for (int i = 0; i < size; i++) { 5311 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5312 } 5313 } 5314 if (hasWebURI(intent)) { 5315 // cross-profile app linking works only towards the parent. 5316 final UserInfo parent = getProfileParent(sourceUserId); 5317 synchronized(mPackages) { 5318 int flags = updateFlagsForResolve(0, parent.id, intent); 5319 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5320 intent, resolvedType, flags, sourceUserId, parent.id); 5321 return xpDomainInfo != null; 5322 } 5323 } 5324 return false; 5325 } 5326 5327 private UserInfo getProfileParent(int userId) { 5328 final long identity = Binder.clearCallingIdentity(); 5329 try { 5330 return sUserManager.getProfileParent(userId); 5331 } finally { 5332 Binder.restoreCallingIdentity(identity); 5333 } 5334 } 5335 5336 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5337 String resolvedType, int userId) { 5338 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5339 if (resolver != null) { 5340 return resolver.queryIntent(intent, resolvedType, false, userId); 5341 } 5342 return null; 5343 } 5344 5345 @Override 5346 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5347 String resolvedType, int flags, int userId) { 5348 try { 5349 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5350 5351 return new ParceledListSlice<>( 5352 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5353 } finally { 5354 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5355 } 5356 } 5357 5358 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5359 String resolvedType, int flags, int userId) { 5360 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5361 flags = updateFlagsForResolve(flags, userId, intent); 5362 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5363 false /* requireFullPermission */, false /* checkShell */, 5364 "query intent activities"); 5365 ComponentName comp = intent.getComponent(); 5366 if (comp == null) { 5367 if (intent.getSelector() != null) { 5368 intent = intent.getSelector(); 5369 comp = intent.getComponent(); 5370 } 5371 } 5372 5373 if (comp != null) { 5374 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5375 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5376 if (ai != null) { 5377 final ResolveInfo ri = new ResolveInfo(); 5378 ri.activityInfo = ai; 5379 list.add(ri); 5380 } 5381 return list; 5382 } 5383 5384 // reader 5385 synchronized (mPackages) { 5386 final String pkgName = intent.getPackage(); 5387 if (pkgName == null) { 5388 List<CrossProfileIntentFilter> matchingFilters = 5389 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5390 // Check for results that need to skip the current profile. 5391 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5392 resolvedType, flags, userId); 5393 if (xpResolveInfo != null) { 5394 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5395 result.add(xpResolveInfo); 5396 return filterIfNotSystemUser(result, userId); 5397 } 5398 5399 // Check for results in the current profile. 5400 List<ResolveInfo> result = mActivities.queryIntent( 5401 intent, resolvedType, flags, userId); 5402 result = filterIfNotSystemUser(result, userId); 5403 5404 // Check for cross profile results. 5405 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5406 xpResolveInfo = queryCrossProfileIntents( 5407 matchingFilters, intent, resolvedType, flags, userId, 5408 hasNonNegativePriorityResult); 5409 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5410 boolean isVisibleToUser = filterIfNotSystemUser( 5411 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5412 if (isVisibleToUser) { 5413 result.add(xpResolveInfo); 5414 Collections.sort(result, mResolvePrioritySorter); 5415 } 5416 } 5417 if (hasWebURI(intent)) { 5418 CrossProfileDomainInfo xpDomainInfo = null; 5419 final UserInfo parent = getProfileParent(userId); 5420 if (parent != null) { 5421 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5422 flags, userId, parent.id); 5423 } 5424 if (xpDomainInfo != null) { 5425 if (xpResolveInfo != null) { 5426 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5427 // in the result. 5428 result.remove(xpResolveInfo); 5429 } 5430 if (result.size() == 0) { 5431 result.add(xpDomainInfo.resolveInfo); 5432 return result; 5433 } 5434 } else if (result.size() <= 1) { 5435 return result; 5436 } 5437 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5438 xpDomainInfo, userId); 5439 Collections.sort(result, mResolvePrioritySorter); 5440 } 5441 return result; 5442 } 5443 final PackageParser.Package pkg = mPackages.get(pkgName); 5444 if (pkg != null) { 5445 return filterIfNotSystemUser( 5446 mActivities.queryIntentForPackage( 5447 intent, resolvedType, flags, pkg.activities, userId), 5448 userId); 5449 } 5450 return new ArrayList<ResolveInfo>(); 5451 } 5452 } 5453 5454 private static class CrossProfileDomainInfo { 5455 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5456 ResolveInfo resolveInfo; 5457 /* Best domain verification status of the activities found in the other profile */ 5458 int bestDomainVerificationStatus; 5459 } 5460 5461 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5462 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5463 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5464 sourceUserId)) { 5465 return null; 5466 } 5467 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5468 resolvedType, flags, parentUserId); 5469 5470 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5471 return null; 5472 } 5473 CrossProfileDomainInfo result = null; 5474 int size = resultTargetUser.size(); 5475 for (int i = 0; i < size; i++) { 5476 ResolveInfo riTargetUser = resultTargetUser.get(i); 5477 // Intent filter verification is only for filters that specify a host. So don't return 5478 // those that handle all web uris. 5479 if (riTargetUser.handleAllWebDataURI) { 5480 continue; 5481 } 5482 String packageName = riTargetUser.activityInfo.packageName; 5483 PackageSetting ps = mSettings.mPackages.get(packageName); 5484 if (ps == null) { 5485 continue; 5486 } 5487 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5488 int status = (int)(verificationState >> 32); 5489 if (result == null) { 5490 result = new CrossProfileDomainInfo(); 5491 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5492 sourceUserId, parentUserId); 5493 result.bestDomainVerificationStatus = status; 5494 } else { 5495 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5496 result.bestDomainVerificationStatus); 5497 } 5498 } 5499 // Don't consider matches with status NEVER across profiles. 5500 if (result != null && result.bestDomainVerificationStatus 5501 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5502 return null; 5503 } 5504 return result; 5505 } 5506 5507 /** 5508 * Verification statuses are ordered from the worse to the best, except for 5509 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5510 */ 5511 private int bestDomainVerificationStatus(int status1, int status2) { 5512 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5513 return status2; 5514 } 5515 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5516 return status1; 5517 } 5518 return (int) MathUtils.max(status1, status2); 5519 } 5520 5521 private boolean isUserEnabled(int userId) { 5522 long callingId = Binder.clearCallingIdentity(); 5523 try { 5524 UserInfo userInfo = sUserManager.getUserInfo(userId); 5525 return userInfo != null && userInfo.isEnabled(); 5526 } finally { 5527 Binder.restoreCallingIdentity(callingId); 5528 } 5529 } 5530 5531 /** 5532 * Filter out activities with systemUserOnly flag set, when current user is not System. 5533 * 5534 * @return filtered list 5535 */ 5536 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5537 if (userId == UserHandle.USER_SYSTEM) { 5538 return resolveInfos; 5539 } 5540 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5541 ResolveInfo info = resolveInfos.get(i); 5542 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5543 resolveInfos.remove(i); 5544 } 5545 } 5546 return resolveInfos; 5547 } 5548 5549 /** 5550 * @param resolveInfos list of resolve infos in descending priority order 5551 * @return if the list contains a resolve info with non-negative priority 5552 */ 5553 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5554 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5555 } 5556 5557 private static boolean hasWebURI(Intent intent) { 5558 if (intent.getData() == null) { 5559 return false; 5560 } 5561 final String scheme = intent.getScheme(); 5562 if (TextUtils.isEmpty(scheme)) { 5563 return false; 5564 } 5565 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5566 } 5567 5568 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5569 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5570 int userId) { 5571 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5572 5573 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5574 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5575 candidates.size()); 5576 } 5577 5578 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5579 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5580 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5581 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5582 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5583 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5584 5585 synchronized (mPackages) { 5586 final int count = candidates.size(); 5587 // First, try to use linked apps. Partition the candidates into four lists: 5588 // one for the final results, one for the "do not use ever", one for "undefined status" 5589 // and finally one for "browser app type". 5590 for (int n=0; n<count; n++) { 5591 ResolveInfo info = candidates.get(n); 5592 String packageName = info.activityInfo.packageName; 5593 PackageSetting ps = mSettings.mPackages.get(packageName); 5594 if (ps != null) { 5595 // Add to the special match all list (Browser use case) 5596 if (info.handleAllWebDataURI) { 5597 matchAllList.add(info); 5598 continue; 5599 } 5600 // Try to get the status from User settings first 5601 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5602 int status = (int)(packedStatus >> 32); 5603 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5604 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5605 if (DEBUG_DOMAIN_VERIFICATION) { 5606 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5607 + " : linkgen=" + linkGeneration); 5608 } 5609 // Use link-enabled generation as preferredOrder, i.e. 5610 // prefer newly-enabled over earlier-enabled. 5611 info.preferredOrder = linkGeneration; 5612 alwaysList.add(info); 5613 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5614 if (DEBUG_DOMAIN_VERIFICATION) { 5615 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5616 } 5617 neverList.add(info); 5618 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5619 if (DEBUG_DOMAIN_VERIFICATION) { 5620 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5621 } 5622 alwaysAskList.add(info); 5623 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5624 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5625 if (DEBUG_DOMAIN_VERIFICATION) { 5626 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5627 } 5628 undefinedList.add(info); 5629 } 5630 } 5631 } 5632 5633 // We'll want to include browser possibilities in a few cases 5634 boolean includeBrowser = false; 5635 5636 // First try to add the "always" resolution(s) for the current user, if any 5637 if (alwaysList.size() > 0) { 5638 result.addAll(alwaysList); 5639 } else { 5640 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5641 result.addAll(undefinedList); 5642 // Maybe add one for the other profile. 5643 if (xpDomainInfo != null && ( 5644 xpDomainInfo.bestDomainVerificationStatus 5645 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5646 result.add(xpDomainInfo.resolveInfo); 5647 } 5648 includeBrowser = true; 5649 } 5650 5651 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5652 // If there were 'always' entries their preferred order has been set, so we also 5653 // back that off to make the alternatives equivalent 5654 if (alwaysAskList.size() > 0) { 5655 for (ResolveInfo i : result) { 5656 i.preferredOrder = 0; 5657 } 5658 result.addAll(alwaysAskList); 5659 includeBrowser = true; 5660 } 5661 5662 if (includeBrowser) { 5663 // Also add browsers (all of them or only the default one) 5664 if (DEBUG_DOMAIN_VERIFICATION) { 5665 Slog.v(TAG, " ...including browsers in candidate set"); 5666 } 5667 if ((matchFlags & MATCH_ALL) != 0) { 5668 result.addAll(matchAllList); 5669 } else { 5670 // Browser/generic handling case. If there's a default browser, go straight 5671 // to that (but only if there is no other higher-priority match). 5672 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5673 int maxMatchPrio = 0; 5674 ResolveInfo defaultBrowserMatch = null; 5675 final int numCandidates = matchAllList.size(); 5676 for (int n = 0; n < numCandidates; n++) { 5677 ResolveInfo info = matchAllList.get(n); 5678 // track the highest overall match priority... 5679 if (info.priority > maxMatchPrio) { 5680 maxMatchPrio = info.priority; 5681 } 5682 // ...and the highest-priority default browser match 5683 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5684 if (defaultBrowserMatch == null 5685 || (defaultBrowserMatch.priority < info.priority)) { 5686 if (debug) { 5687 Slog.v(TAG, "Considering default browser match " + info); 5688 } 5689 defaultBrowserMatch = info; 5690 } 5691 } 5692 } 5693 if (defaultBrowserMatch != null 5694 && defaultBrowserMatch.priority >= maxMatchPrio 5695 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5696 { 5697 if (debug) { 5698 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5699 } 5700 result.add(defaultBrowserMatch); 5701 } else { 5702 result.addAll(matchAllList); 5703 } 5704 } 5705 5706 // If there is nothing selected, add all candidates and remove the ones that the user 5707 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5708 if (result.size() == 0) { 5709 result.addAll(candidates); 5710 result.removeAll(neverList); 5711 } 5712 } 5713 } 5714 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5715 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5716 result.size()); 5717 for (ResolveInfo info : result) { 5718 Slog.v(TAG, " + " + info.activityInfo); 5719 } 5720 } 5721 return result; 5722 } 5723 5724 // Returns a packed value as a long: 5725 // 5726 // high 'int'-sized word: link status: undefined/ask/never/always. 5727 // low 'int'-sized word: relative priority among 'always' results. 5728 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5729 long result = ps.getDomainVerificationStatusForUser(userId); 5730 // if none available, get the master status 5731 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5732 if (ps.getIntentFilterVerificationInfo() != null) { 5733 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5734 } 5735 } 5736 return result; 5737 } 5738 5739 private ResolveInfo querySkipCurrentProfileIntents( 5740 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5741 int flags, int sourceUserId) { 5742 if (matchingFilters != null) { 5743 int size = matchingFilters.size(); 5744 for (int i = 0; i < size; i ++) { 5745 CrossProfileIntentFilter filter = matchingFilters.get(i); 5746 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5747 // Checking if there are activities in the target user that can handle the 5748 // intent. 5749 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5750 resolvedType, flags, sourceUserId); 5751 if (resolveInfo != null) { 5752 return resolveInfo; 5753 } 5754 } 5755 } 5756 } 5757 return null; 5758 } 5759 5760 // Return matching ResolveInfo in target user if any. 5761 private ResolveInfo queryCrossProfileIntents( 5762 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5763 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5764 if (matchingFilters != null) { 5765 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5766 // match the same intent. For performance reasons, it is better not to 5767 // run queryIntent twice for the same userId 5768 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5769 int size = matchingFilters.size(); 5770 for (int i = 0; i < size; i++) { 5771 CrossProfileIntentFilter filter = matchingFilters.get(i); 5772 int targetUserId = filter.getTargetUserId(); 5773 boolean skipCurrentProfile = 5774 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5775 boolean skipCurrentProfileIfNoMatchFound = 5776 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5777 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5778 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5779 // Checking if there are activities in the target user that can handle the 5780 // intent. 5781 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5782 resolvedType, flags, sourceUserId); 5783 if (resolveInfo != null) return resolveInfo; 5784 alreadyTriedUserIds.put(targetUserId, true); 5785 } 5786 } 5787 } 5788 return null; 5789 } 5790 5791 /** 5792 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5793 * will forward the intent to the filter's target user. 5794 * Otherwise, returns null. 5795 */ 5796 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5797 String resolvedType, int flags, int sourceUserId) { 5798 int targetUserId = filter.getTargetUserId(); 5799 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5800 resolvedType, flags, targetUserId); 5801 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5802 // If all the matches in the target profile are suspended, return null. 5803 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5804 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5805 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5806 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5807 targetUserId); 5808 } 5809 } 5810 } 5811 return null; 5812 } 5813 5814 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5815 int sourceUserId, int targetUserId) { 5816 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5817 long ident = Binder.clearCallingIdentity(); 5818 boolean targetIsProfile; 5819 try { 5820 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5821 } finally { 5822 Binder.restoreCallingIdentity(ident); 5823 } 5824 String className; 5825 if (targetIsProfile) { 5826 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5827 } else { 5828 className = FORWARD_INTENT_TO_PARENT; 5829 } 5830 ComponentName forwardingActivityComponentName = new ComponentName( 5831 mAndroidApplication.packageName, className); 5832 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5833 sourceUserId); 5834 if (!targetIsProfile) { 5835 forwardingActivityInfo.showUserIcon = targetUserId; 5836 forwardingResolveInfo.noResourceId = true; 5837 } 5838 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5839 forwardingResolveInfo.priority = 0; 5840 forwardingResolveInfo.preferredOrder = 0; 5841 forwardingResolveInfo.match = 0; 5842 forwardingResolveInfo.isDefault = true; 5843 forwardingResolveInfo.filter = filter; 5844 forwardingResolveInfo.targetUserId = targetUserId; 5845 return forwardingResolveInfo; 5846 } 5847 5848 @Override 5849 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5850 Intent[] specifics, String[] specificTypes, Intent intent, 5851 String resolvedType, int flags, int userId) { 5852 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5853 specificTypes, intent, resolvedType, flags, userId)); 5854 } 5855 5856 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5857 Intent[] specifics, String[] specificTypes, Intent intent, 5858 String resolvedType, int flags, int userId) { 5859 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5860 flags = updateFlagsForResolve(flags, userId, intent); 5861 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5862 false /* requireFullPermission */, false /* checkShell */, 5863 "query intent activity options"); 5864 final String resultsAction = intent.getAction(); 5865 5866 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5867 | PackageManager.GET_RESOLVED_FILTER, userId); 5868 5869 if (DEBUG_INTENT_MATCHING) { 5870 Log.v(TAG, "Query " + intent + ": " + results); 5871 } 5872 5873 int specificsPos = 0; 5874 int N; 5875 5876 // todo: note that the algorithm used here is O(N^2). This 5877 // isn't a problem in our current environment, but if we start running 5878 // into situations where we have more than 5 or 10 matches then this 5879 // should probably be changed to something smarter... 5880 5881 // First we go through and resolve each of the specific items 5882 // that were supplied, taking care of removing any corresponding 5883 // duplicate items in the generic resolve list. 5884 if (specifics != null) { 5885 for (int i=0; i<specifics.length; i++) { 5886 final Intent sintent = specifics[i]; 5887 if (sintent == null) { 5888 continue; 5889 } 5890 5891 if (DEBUG_INTENT_MATCHING) { 5892 Log.v(TAG, "Specific #" + i + ": " + sintent); 5893 } 5894 5895 String action = sintent.getAction(); 5896 if (resultsAction != null && resultsAction.equals(action)) { 5897 // If this action was explicitly requested, then don't 5898 // remove things that have it. 5899 action = null; 5900 } 5901 5902 ResolveInfo ri = null; 5903 ActivityInfo ai = null; 5904 5905 ComponentName comp = sintent.getComponent(); 5906 if (comp == null) { 5907 ri = resolveIntent( 5908 sintent, 5909 specificTypes != null ? specificTypes[i] : null, 5910 flags, userId); 5911 if (ri == null) { 5912 continue; 5913 } 5914 if (ri == mResolveInfo) { 5915 // ACK! Must do something better with this. 5916 } 5917 ai = ri.activityInfo; 5918 comp = new ComponentName(ai.applicationInfo.packageName, 5919 ai.name); 5920 } else { 5921 ai = getActivityInfo(comp, flags, userId); 5922 if (ai == null) { 5923 continue; 5924 } 5925 } 5926 5927 // Look for any generic query activities that are duplicates 5928 // of this specific one, and remove them from the results. 5929 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5930 N = results.size(); 5931 int j; 5932 for (j=specificsPos; j<N; j++) { 5933 ResolveInfo sri = results.get(j); 5934 if ((sri.activityInfo.name.equals(comp.getClassName()) 5935 && sri.activityInfo.applicationInfo.packageName.equals( 5936 comp.getPackageName())) 5937 || (action != null && sri.filter.matchAction(action))) { 5938 results.remove(j); 5939 if (DEBUG_INTENT_MATCHING) Log.v( 5940 TAG, "Removing duplicate item from " + j 5941 + " due to specific " + specificsPos); 5942 if (ri == null) { 5943 ri = sri; 5944 } 5945 j--; 5946 N--; 5947 } 5948 } 5949 5950 // Add this specific item to its proper place. 5951 if (ri == null) { 5952 ri = new ResolveInfo(); 5953 ri.activityInfo = ai; 5954 } 5955 results.add(specificsPos, ri); 5956 ri.specificIndex = i; 5957 specificsPos++; 5958 } 5959 } 5960 5961 // Now we go through the remaining generic results and remove any 5962 // duplicate actions that are found here. 5963 N = results.size(); 5964 for (int i=specificsPos; i<N-1; i++) { 5965 final ResolveInfo rii = results.get(i); 5966 if (rii.filter == null) { 5967 continue; 5968 } 5969 5970 // Iterate over all of the actions of this result's intent 5971 // filter... typically this should be just one. 5972 final Iterator<String> it = rii.filter.actionsIterator(); 5973 if (it == null) { 5974 continue; 5975 } 5976 while (it.hasNext()) { 5977 final String action = it.next(); 5978 if (resultsAction != null && resultsAction.equals(action)) { 5979 // If this action was explicitly requested, then don't 5980 // remove things that have it. 5981 continue; 5982 } 5983 for (int j=i+1; j<N; j++) { 5984 final ResolveInfo rij = results.get(j); 5985 if (rij.filter != null && rij.filter.hasAction(action)) { 5986 results.remove(j); 5987 if (DEBUG_INTENT_MATCHING) Log.v( 5988 TAG, "Removing duplicate item from " + j 5989 + " due to action " + action + " at " + i); 5990 j--; 5991 N--; 5992 } 5993 } 5994 } 5995 5996 // If the caller didn't request filter information, drop it now 5997 // so we don't have to marshall/unmarshall it. 5998 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5999 rii.filter = null; 6000 } 6001 } 6002 6003 // Filter out the caller activity if so requested. 6004 if (caller != null) { 6005 N = results.size(); 6006 for (int i=0; i<N; i++) { 6007 ActivityInfo ainfo = results.get(i).activityInfo; 6008 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6009 && caller.getClassName().equals(ainfo.name)) { 6010 results.remove(i); 6011 break; 6012 } 6013 } 6014 } 6015 6016 // If the caller didn't request filter information, 6017 // drop them now so we don't have to 6018 // marshall/unmarshall it. 6019 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6020 N = results.size(); 6021 for (int i=0; i<N; i++) { 6022 results.get(i).filter = null; 6023 } 6024 } 6025 6026 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6027 return results; 6028 } 6029 6030 @Override 6031 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6032 String resolvedType, int flags, int userId) { 6033 return new ParceledListSlice<>( 6034 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6035 } 6036 6037 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6038 String resolvedType, int flags, int userId) { 6039 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6040 flags = updateFlagsForResolve(flags, userId, intent); 6041 ComponentName comp = intent.getComponent(); 6042 if (comp == null) { 6043 if (intent.getSelector() != null) { 6044 intent = intent.getSelector(); 6045 comp = intent.getComponent(); 6046 } 6047 } 6048 if (comp != null) { 6049 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6050 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6051 if (ai != null) { 6052 ResolveInfo ri = new ResolveInfo(); 6053 ri.activityInfo = ai; 6054 list.add(ri); 6055 } 6056 return list; 6057 } 6058 6059 // reader 6060 synchronized (mPackages) { 6061 String pkgName = intent.getPackage(); 6062 if (pkgName == null) { 6063 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6064 } 6065 final PackageParser.Package pkg = mPackages.get(pkgName); 6066 if (pkg != null) { 6067 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6068 userId); 6069 } 6070 return Collections.emptyList(); 6071 } 6072 } 6073 6074 @Override 6075 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6076 if (!sUserManager.exists(userId)) return null; 6077 flags = updateFlagsForResolve(flags, userId, intent); 6078 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6079 if (query != null) { 6080 if (query.size() >= 1) { 6081 // If there is more than one service with the same priority, 6082 // just arbitrarily pick the first one. 6083 return query.get(0); 6084 } 6085 } 6086 return null; 6087 } 6088 6089 @Override 6090 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6091 String resolvedType, int flags, int userId) { 6092 return new ParceledListSlice<>( 6093 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6094 } 6095 6096 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6097 String resolvedType, int flags, int userId) { 6098 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6099 flags = updateFlagsForResolve(flags, userId, intent); 6100 ComponentName comp = intent.getComponent(); 6101 if (comp == null) { 6102 if (intent.getSelector() != null) { 6103 intent = intent.getSelector(); 6104 comp = intent.getComponent(); 6105 } 6106 } 6107 if (comp != null) { 6108 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6109 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6110 if (si != null) { 6111 final ResolveInfo ri = new ResolveInfo(); 6112 ri.serviceInfo = si; 6113 list.add(ri); 6114 } 6115 return list; 6116 } 6117 6118 // reader 6119 synchronized (mPackages) { 6120 String pkgName = intent.getPackage(); 6121 if (pkgName == null) { 6122 return mServices.queryIntent(intent, resolvedType, flags, userId); 6123 } 6124 final PackageParser.Package pkg = mPackages.get(pkgName); 6125 if (pkg != null) { 6126 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6127 userId); 6128 } 6129 return Collections.emptyList(); 6130 } 6131 } 6132 6133 @Override 6134 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6135 String resolvedType, int flags, int userId) { 6136 return new ParceledListSlice<>( 6137 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6138 } 6139 6140 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6141 Intent intent, String resolvedType, int flags, int userId) { 6142 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6143 flags = updateFlagsForResolve(flags, userId, intent); 6144 ComponentName comp = intent.getComponent(); 6145 if (comp == null) { 6146 if (intent.getSelector() != null) { 6147 intent = intent.getSelector(); 6148 comp = intent.getComponent(); 6149 } 6150 } 6151 if (comp != null) { 6152 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6153 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6154 if (pi != null) { 6155 final ResolveInfo ri = new ResolveInfo(); 6156 ri.providerInfo = pi; 6157 list.add(ri); 6158 } 6159 return list; 6160 } 6161 6162 // reader 6163 synchronized (mPackages) { 6164 String pkgName = intent.getPackage(); 6165 if (pkgName == null) { 6166 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6167 } 6168 final PackageParser.Package pkg = mPackages.get(pkgName); 6169 if (pkg != null) { 6170 return mProviders.queryIntentForPackage( 6171 intent, resolvedType, flags, pkg.providers, userId); 6172 } 6173 return Collections.emptyList(); 6174 } 6175 } 6176 6177 @Override 6178 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6179 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6180 flags = updateFlagsForPackage(flags, userId, null); 6181 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6182 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6183 true /* requireFullPermission */, false /* checkShell */, 6184 "get installed packages"); 6185 6186 // writer 6187 synchronized (mPackages) { 6188 ArrayList<PackageInfo> list; 6189 if (listUninstalled) { 6190 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6191 for (PackageSetting ps : mSettings.mPackages.values()) { 6192 final PackageInfo pi; 6193 if (ps.pkg != null) { 6194 pi = generatePackageInfo(ps, flags, userId); 6195 } else { 6196 pi = generatePackageInfo(ps, flags, userId); 6197 } 6198 if (pi != null) { 6199 list.add(pi); 6200 } 6201 } 6202 } else { 6203 list = new ArrayList<PackageInfo>(mPackages.size()); 6204 for (PackageParser.Package p : mPackages.values()) { 6205 final PackageInfo pi = 6206 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6207 if (pi != null) { 6208 list.add(pi); 6209 } 6210 } 6211 } 6212 6213 return new ParceledListSlice<PackageInfo>(list); 6214 } 6215 } 6216 6217 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6218 String[] permissions, boolean[] tmp, int flags, int userId) { 6219 int numMatch = 0; 6220 final PermissionsState permissionsState = ps.getPermissionsState(); 6221 for (int i=0; i<permissions.length; i++) { 6222 final String permission = permissions[i]; 6223 if (permissionsState.hasPermission(permission, userId)) { 6224 tmp[i] = true; 6225 numMatch++; 6226 } else { 6227 tmp[i] = false; 6228 } 6229 } 6230 if (numMatch == 0) { 6231 return; 6232 } 6233 final PackageInfo pi; 6234 if (ps.pkg != null) { 6235 pi = generatePackageInfo(ps, flags, userId); 6236 } else { 6237 pi = generatePackageInfo(ps, flags, userId); 6238 } 6239 // The above might return null in cases of uninstalled apps or install-state 6240 // skew across users/profiles. 6241 if (pi != null) { 6242 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6243 if (numMatch == permissions.length) { 6244 pi.requestedPermissions = permissions; 6245 } else { 6246 pi.requestedPermissions = new String[numMatch]; 6247 numMatch = 0; 6248 for (int i=0; i<permissions.length; i++) { 6249 if (tmp[i]) { 6250 pi.requestedPermissions[numMatch] = permissions[i]; 6251 numMatch++; 6252 } 6253 } 6254 } 6255 } 6256 list.add(pi); 6257 } 6258 } 6259 6260 @Override 6261 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6262 String[] permissions, int flags, int userId) { 6263 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6264 flags = updateFlagsForPackage(flags, userId, permissions); 6265 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6266 6267 // writer 6268 synchronized (mPackages) { 6269 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6270 boolean[] tmpBools = new boolean[permissions.length]; 6271 if (listUninstalled) { 6272 for (PackageSetting ps : mSettings.mPackages.values()) { 6273 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6274 } 6275 } else { 6276 for (PackageParser.Package pkg : mPackages.values()) { 6277 PackageSetting ps = (PackageSetting)pkg.mExtras; 6278 if (ps != null) { 6279 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6280 userId); 6281 } 6282 } 6283 } 6284 6285 return new ParceledListSlice<PackageInfo>(list); 6286 } 6287 } 6288 6289 @Override 6290 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6291 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6292 flags = updateFlagsForApplication(flags, userId, null); 6293 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6294 6295 // writer 6296 synchronized (mPackages) { 6297 ArrayList<ApplicationInfo> list; 6298 if (listUninstalled) { 6299 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6300 for (PackageSetting ps : mSettings.mPackages.values()) { 6301 ApplicationInfo ai; 6302 if (ps.pkg != null) { 6303 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6304 ps.readUserState(userId), userId); 6305 } else { 6306 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6307 } 6308 if (ai != null) { 6309 list.add(ai); 6310 } 6311 } 6312 } else { 6313 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6314 for (PackageParser.Package p : mPackages.values()) { 6315 if (p.mExtras != null) { 6316 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6317 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6318 if (ai != null) { 6319 list.add(ai); 6320 } 6321 } 6322 } 6323 } 6324 6325 return new ParceledListSlice<ApplicationInfo>(list); 6326 } 6327 } 6328 6329 @Override 6330 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6331 if (DISABLE_EPHEMERAL_APPS) { 6332 return null; 6333 } 6334 6335 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6336 "getEphemeralApplications"); 6337 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6338 true /* requireFullPermission */, false /* checkShell */, 6339 "getEphemeralApplications"); 6340 synchronized (mPackages) { 6341 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6342 .getEphemeralApplicationsLPw(userId); 6343 if (ephemeralApps != null) { 6344 return new ParceledListSlice<>(ephemeralApps); 6345 } 6346 } 6347 return null; 6348 } 6349 6350 @Override 6351 public boolean isEphemeralApplication(String packageName, int userId) { 6352 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6353 true /* requireFullPermission */, false /* checkShell */, 6354 "isEphemeral"); 6355 if (DISABLE_EPHEMERAL_APPS) { 6356 return false; 6357 } 6358 6359 if (!isCallerSameApp(packageName)) { 6360 return false; 6361 } 6362 synchronized (mPackages) { 6363 PackageParser.Package pkg = mPackages.get(packageName); 6364 if (pkg != null) { 6365 return pkg.applicationInfo.isEphemeralApp(); 6366 } 6367 } 6368 return false; 6369 } 6370 6371 @Override 6372 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6373 if (DISABLE_EPHEMERAL_APPS) { 6374 return null; 6375 } 6376 6377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6378 true /* requireFullPermission */, false /* checkShell */, 6379 "getCookie"); 6380 if (!isCallerSameApp(packageName)) { 6381 return null; 6382 } 6383 synchronized (mPackages) { 6384 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6385 packageName, userId); 6386 } 6387 } 6388 6389 @Override 6390 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6391 if (DISABLE_EPHEMERAL_APPS) { 6392 return true; 6393 } 6394 6395 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6396 true /* requireFullPermission */, true /* checkShell */, 6397 "setCookie"); 6398 if (!isCallerSameApp(packageName)) { 6399 return false; 6400 } 6401 synchronized (mPackages) { 6402 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6403 packageName, cookie, userId); 6404 } 6405 } 6406 6407 @Override 6408 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6409 if (DISABLE_EPHEMERAL_APPS) { 6410 return null; 6411 } 6412 6413 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6414 "getEphemeralApplicationIcon"); 6415 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6416 true /* requireFullPermission */, false /* checkShell */, 6417 "getEphemeralApplicationIcon"); 6418 synchronized (mPackages) { 6419 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6420 packageName, userId); 6421 } 6422 } 6423 6424 private boolean isCallerSameApp(String packageName) { 6425 PackageParser.Package pkg = mPackages.get(packageName); 6426 return pkg != null 6427 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6428 } 6429 6430 @Override 6431 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6432 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6433 } 6434 6435 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6436 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6437 6438 // reader 6439 synchronized (mPackages) { 6440 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6441 final int userId = UserHandle.getCallingUserId(); 6442 while (i.hasNext()) { 6443 final PackageParser.Package p = i.next(); 6444 if (p.applicationInfo == null) continue; 6445 6446 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6447 && !p.applicationInfo.isDirectBootAware(); 6448 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6449 && p.applicationInfo.isDirectBootAware(); 6450 6451 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6452 && (!mSafeMode || isSystemApp(p)) 6453 && (matchesUnaware || matchesAware)) { 6454 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6455 if (ps != null) { 6456 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6457 ps.readUserState(userId), userId); 6458 if (ai != null) { 6459 finalList.add(ai); 6460 } 6461 } 6462 } 6463 } 6464 } 6465 6466 return finalList; 6467 } 6468 6469 @Override 6470 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6471 if (!sUserManager.exists(userId)) return null; 6472 flags = updateFlagsForComponent(flags, userId, name); 6473 // reader 6474 synchronized (mPackages) { 6475 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6476 PackageSetting ps = provider != null 6477 ? mSettings.mPackages.get(provider.owner.packageName) 6478 : null; 6479 return ps != null 6480 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6481 ? PackageParser.generateProviderInfo(provider, flags, 6482 ps.readUserState(userId), userId) 6483 : null; 6484 } 6485 } 6486 6487 /** 6488 * @deprecated 6489 */ 6490 @Deprecated 6491 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6492 // reader 6493 synchronized (mPackages) { 6494 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6495 .entrySet().iterator(); 6496 final int userId = UserHandle.getCallingUserId(); 6497 while (i.hasNext()) { 6498 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6499 PackageParser.Provider p = entry.getValue(); 6500 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6501 6502 if (ps != null && p.syncable 6503 && (!mSafeMode || (p.info.applicationInfo.flags 6504 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6505 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6506 ps.readUserState(userId), userId); 6507 if (info != null) { 6508 outNames.add(entry.getKey()); 6509 outInfo.add(info); 6510 } 6511 } 6512 } 6513 } 6514 } 6515 6516 @Override 6517 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6518 int uid, int flags) { 6519 final int userId = processName != null ? UserHandle.getUserId(uid) 6520 : UserHandle.getCallingUserId(); 6521 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6522 flags = updateFlagsForComponent(flags, userId, processName); 6523 6524 ArrayList<ProviderInfo> finalList = null; 6525 // reader 6526 synchronized (mPackages) { 6527 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6528 while (i.hasNext()) { 6529 final PackageParser.Provider p = i.next(); 6530 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6531 if (ps != null && p.info.authority != null 6532 && (processName == null 6533 || (p.info.processName.equals(processName) 6534 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6535 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6536 if (finalList == null) { 6537 finalList = new ArrayList<ProviderInfo>(3); 6538 } 6539 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6540 ps.readUserState(userId), userId); 6541 if (info != null) { 6542 finalList.add(info); 6543 } 6544 } 6545 } 6546 } 6547 6548 if (finalList != null) { 6549 Collections.sort(finalList, mProviderInitOrderSorter); 6550 return new ParceledListSlice<ProviderInfo>(finalList); 6551 } 6552 6553 return ParceledListSlice.emptyList(); 6554 } 6555 6556 @Override 6557 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6558 // reader 6559 synchronized (mPackages) { 6560 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6561 return PackageParser.generateInstrumentationInfo(i, flags); 6562 } 6563 } 6564 6565 @Override 6566 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6567 String targetPackage, int flags) { 6568 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6569 } 6570 6571 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6572 int flags) { 6573 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6574 6575 // reader 6576 synchronized (mPackages) { 6577 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6578 while (i.hasNext()) { 6579 final PackageParser.Instrumentation p = i.next(); 6580 if (targetPackage == null 6581 || targetPackage.equals(p.info.targetPackage)) { 6582 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6583 flags); 6584 if (ii != null) { 6585 finalList.add(ii); 6586 } 6587 } 6588 } 6589 } 6590 6591 return finalList; 6592 } 6593 6594 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6595 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6596 if (overlays == null) { 6597 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6598 return; 6599 } 6600 for (PackageParser.Package opkg : overlays.values()) { 6601 // Not much to do if idmap fails: we already logged the error 6602 // and we certainly don't want to abort installation of pkg simply 6603 // because an overlay didn't fit properly. For these reasons, 6604 // ignore the return value of createIdmapForPackagePairLI. 6605 createIdmapForPackagePairLI(pkg, opkg); 6606 } 6607 } 6608 6609 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6610 PackageParser.Package opkg) { 6611 if (!opkg.mTrustedOverlay) { 6612 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6613 opkg.baseCodePath + ": overlay not trusted"); 6614 return false; 6615 } 6616 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6617 if (overlaySet == null) { 6618 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6619 opkg.baseCodePath + " but target package has no known overlays"); 6620 return false; 6621 } 6622 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6623 // TODO: generate idmap for split APKs 6624 try { 6625 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6626 } catch (InstallerException e) { 6627 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6628 + opkg.baseCodePath); 6629 return false; 6630 } 6631 PackageParser.Package[] overlayArray = 6632 overlaySet.values().toArray(new PackageParser.Package[0]); 6633 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6634 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6635 return p1.mOverlayPriority - p2.mOverlayPriority; 6636 } 6637 }; 6638 Arrays.sort(overlayArray, cmp); 6639 6640 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6641 int i = 0; 6642 for (PackageParser.Package p : overlayArray) { 6643 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6644 } 6645 return true; 6646 } 6647 6648 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6650 try { 6651 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6652 } finally { 6653 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6654 } 6655 } 6656 6657 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6658 final File[] files = dir.listFiles(); 6659 if (ArrayUtils.isEmpty(files)) { 6660 Log.d(TAG, "No files in app dir " + dir); 6661 return; 6662 } 6663 6664 if (DEBUG_PACKAGE_SCANNING) { 6665 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6666 + " flags=0x" + Integer.toHexString(parseFlags)); 6667 } 6668 6669 for (File file : files) { 6670 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6671 && !PackageInstallerService.isStageName(file.getName()); 6672 if (!isPackage) { 6673 // Ignore entries which are not packages 6674 continue; 6675 } 6676 try { 6677 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6678 scanFlags, currentTime, null); 6679 } catch (PackageManagerException e) { 6680 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6681 6682 // Delete invalid userdata apps 6683 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6684 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6685 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6686 removeCodePathLI(file); 6687 } 6688 } 6689 } 6690 } 6691 6692 private static File getSettingsProblemFile() { 6693 File dataDir = Environment.getDataDirectory(); 6694 File systemDir = new File(dataDir, "system"); 6695 File fname = new File(systemDir, "uiderrors.txt"); 6696 return fname; 6697 } 6698 6699 static void reportSettingsProblem(int priority, String msg) { 6700 logCriticalInfo(priority, msg); 6701 } 6702 6703 static void logCriticalInfo(int priority, String msg) { 6704 Slog.println(priority, TAG, msg); 6705 EventLogTags.writePmCriticalInfo(msg); 6706 try { 6707 File fname = getSettingsProblemFile(); 6708 FileOutputStream out = new FileOutputStream(fname, true); 6709 PrintWriter pw = new FastPrintWriter(out); 6710 SimpleDateFormat formatter = new SimpleDateFormat(); 6711 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6712 pw.println(dateString + ": " + msg); 6713 pw.close(); 6714 FileUtils.setPermissions( 6715 fname.toString(), 6716 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6717 -1, -1); 6718 } catch (java.io.IOException e) { 6719 } 6720 } 6721 6722 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6723 final int policyFlags) throws PackageManagerException { 6724 if (ps != null 6725 && ps.codePath.equals(srcFile) 6726 && ps.timeStamp == srcFile.lastModified() 6727 && !isCompatSignatureUpdateNeeded(pkg) 6728 && !isRecoverSignatureUpdateNeeded(pkg)) { 6729 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6730 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6731 ArraySet<PublicKey> signingKs; 6732 synchronized (mPackages) { 6733 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6734 } 6735 if (ps.signatures.mSignatures != null 6736 && ps.signatures.mSignatures.length != 0 6737 && signingKs != null) { 6738 // Optimization: reuse the existing cached certificates 6739 // if the package appears to be unchanged. 6740 pkg.mSignatures = ps.signatures.mSignatures; 6741 pkg.mSigningKeys = signingKs; 6742 return; 6743 } 6744 6745 Slog.w(TAG, "PackageSetting for " + ps.name 6746 + " is missing signatures. Collecting certs again to recover them."); 6747 } else { 6748 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6749 } 6750 6751 try { 6752 PackageParser.collectCertificates(pkg, policyFlags); 6753 } catch (PackageParserException e) { 6754 throw PackageManagerException.from(e); 6755 } 6756 } 6757 6758 /** 6759 * Traces a package scan. 6760 * @see #scanPackageLI(File, int, int, long, UserHandle) 6761 */ 6762 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6763 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6765 try { 6766 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6767 } finally { 6768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6769 } 6770 } 6771 6772 /** 6773 * Scans a package and returns the newly parsed package. 6774 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6775 */ 6776 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6777 long currentTime, UserHandle user) throws PackageManagerException { 6778 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6779 PackageParser pp = new PackageParser(); 6780 pp.setSeparateProcesses(mSeparateProcesses); 6781 pp.setOnlyCoreApps(mOnlyCore); 6782 pp.setDisplayMetrics(mMetrics); 6783 6784 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6785 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6786 } 6787 6788 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6789 final PackageParser.Package pkg; 6790 try { 6791 pkg = pp.parsePackage(scanFile, parseFlags); 6792 } catch (PackageParserException e) { 6793 throw PackageManagerException.from(e); 6794 } finally { 6795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6796 } 6797 6798 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6799 } 6800 6801 /** 6802 * Scans a package and returns the newly parsed package. 6803 * @throws PackageManagerException on a parse error. 6804 */ 6805 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6806 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6807 throws PackageManagerException { 6808 // If the package has children and this is the first dive in the function 6809 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6810 // packages (parent and children) would be successfully scanned before the 6811 // actual scan since scanning mutates internal state and we want to atomically 6812 // install the package and its children. 6813 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6814 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6815 scanFlags |= SCAN_CHECK_ONLY; 6816 } 6817 } else { 6818 scanFlags &= ~SCAN_CHECK_ONLY; 6819 } 6820 6821 // Scan the parent 6822 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6823 scanFlags, currentTime, user); 6824 6825 // Scan the children 6826 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6827 for (int i = 0; i < childCount; i++) { 6828 PackageParser.Package childPackage = pkg.childPackages.get(i); 6829 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6830 currentTime, user); 6831 } 6832 6833 6834 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6835 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6836 } 6837 6838 return scannedPkg; 6839 } 6840 6841 /** 6842 * Scans a package and returns the newly parsed package. 6843 * @throws PackageManagerException on a parse error. 6844 */ 6845 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6846 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6847 throws PackageManagerException { 6848 PackageSetting ps = null; 6849 PackageSetting updatedPkg; 6850 // reader 6851 synchronized (mPackages) { 6852 // Look to see if we already know about this package. 6853 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6854 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6855 // This package has been renamed to its original name. Let's 6856 // use that. 6857 ps = mSettings.peekPackageLPr(oldName); 6858 } 6859 // If there was no original package, see one for the real package name. 6860 if (ps == null) { 6861 ps = mSettings.peekPackageLPr(pkg.packageName); 6862 } 6863 // Check to see if this package could be hiding/updating a system 6864 // package. Must look for it either under the original or real 6865 // package name depending on our state. 6866 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6867 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6868 6869 // If this is a package we don't know about on the system partition, we 6870 // may need to remove disabled child packages on the system partition 6871 // or may need to not add child packages if the parent apk is updated 6872 // on the data partition and no longer defines this child package. 6873 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6874 // If this is a parent package for an updated system app and this system 6875 // app got an OTA update which no longer defines some of the child packages 6876 // we have to prune them from the disabled system packages. 6877 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6878 if (disabledPs != null) { 6879 final int scannedChildCount = (pkg.childPackages != null) 6880 ? pkg.childPackages.size() : 0; 6881 final int disabledChildCount = disabledPs.childPackageNames != null 6882 ? disabledPs.childPackageNames.size() : 0; 6883 for (int i = 0; i < disabledChildCount; i++) { 6884 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6885 boolean disabledPackageAvailable = false; 6886 for (int j = 0; j < scannedChildCount; j++) { 6887 PackageParser.Package childPkg = pkg.childPackages.get(j); 6888 if (childPkg.packageName.equals(disabledChildPackageName)) { 6889 disabledPackageAvailable = true; 6890 break; 6891 } 6892 } 6893 if (!disabledPackageAvailable) { 6894 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6895 } 6896 } 6897 } 6898 } 6899 } 6900 6901 boolean updatedPkgBetter = false; 6902 // First check if this is a system package that may involve an update 6903 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6904 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6905 // it needs to drop FLAG_PRIVILEGED. 6906 if (locationIsPrivileged(scanFile)) { 6907 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6908 } else { 6909 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6910 } 6911 6912 if (ps != null && !ps.codePath.equals(scanFile)) { 6913 // The path has changed from what was last scanned... check the 6914 // version of the new path against what we have stored to determine 6915 // what to do. 6916 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6917 if (pkg.mVersionCode <= ps.versionCode) { 6918 // The system package has been updated and the code path does not match 6919 // Ignore entry. Skip it. 6920 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6921 + " ignored: updated version " + ps.versionCode 6922 + " better than this " + pkg.mVersionCode); 6923 if (!updatedPkg.codePath.equals(scanFile)) { 6924 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6925 + ps.name + " changing from " + updatedPkg.codePathString 6926 + " to " + scanFile); 6927 updatedPkg.codePath = scanFile; 6928 updatedPkg.codePathString = scanFile.toString(); 6929 updatedPkg.resourcePath = scanFile; 6930 updatedPkg.resourcePathString = scanFile.toString(); 6931 } 6932 updatedPkg.pkg = pkg; 6933 updatedPkg.versionCode = pkg.mVersionCode; 6934 6935 // Update the disabled system child packages to point to the package too. 6936 final int childCount = updatedPkg.childPackageNames != null 6937 ? updatedPkg.childPackageNames.size() : 0; 6938 for (int i = 0; i < childCount; i++) { 6939 String childPackageName = updatedPkg.childPackageNames.get(i); 6940 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6941 childPackageName); 6942 if (updatedChildPkg != null) { 6943 updatedChildPkg.pkg = pkg; 6944 updatedChildPkg.versionCode = pkg.mVersionCode; 6945 } 6946 } 6947 6948 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6949 + scanFile + " ignored: updated version " + ps.versionCode 6950 + " better than this " + pkg.mVersionCode); 6951 } else { 6952 // The current app on the system partition is better than 6953 // what we have updated to on the data partition; switch 6954 // back to the system partition version. 6955 // At this point, its safely assumed that package installation for 6956 // apps in system partition will go through. If not there won't be a working 6957 // version of the app 6958 // writer 6959 synchronized (mPackages) { 6960 // Just remove the loaded entries from package lists. 6961 mPackages.remove(ps.name); 6962 } 6963 6964 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6965 + " reverting from " + ps.codePathString 6966 + ": new version " + pkg.mVersionCode 6967 + " better than installed " + ps.versionCode); 6968 6969 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6970 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6971 synchronized (mInstallLock) { 6972 args.cleanUpResourcesLI(); 6973 } 6974 synchronized (mPackages) { 6975 mSettings.enableSystemPackageLPw(ps.name); 6976 } 6977 updatedPkgBetter = true; 6978 } 6979 } 6980 } 6981 6982 if (updatedPkg != null) { 6983 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6984 // initially 6985 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6986 6987 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6988 // flag set initially 6989 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6990 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6991 } 6992 } 6993 6994 // Verify certificates against what was last scanned 6995 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6996 6997 /* 6998 * A new system app appeared, but we already had a non-system one of the 6999 * same name installed earlier. 7000 */ 7001 boolean shouldHideSystemApp = false; 7002 if (updatedPkg == null && ps != null 7003 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7004 /* 7005 * Check to make sure the signatures match first. If they don't, 7006 * wipe the installed application and its data. 7007 */ 7008 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7009 != PackageManager.SIGNATURE_MATCH) { 7010 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7011 + " signatures don't match existing userdata copy; removing"); 7012 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7013 "scanPackageInternalLI")) { 7014 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7015 } 7016 ps = null; 7017 } else { 7018 /* 7019 * If the newly-added system app is an older version than the 7020 * already installed version, hide it. It will be scanned later 7021 * and re-added like an update. 7022 */ 7023 if (pkg.mVersionCode <= ps.versionCode) { 7024 shouldHideSystemApp = true; 7025 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7026 + " but new version " + pkg.mVersionCode + " better than installed " 7027 + ps.versionCode + "; hiding system"); 7028 } else { 7029 /* 7030 * The newly found system app is a newer version that the 7031 * one previously installed. Simply remove the 7032 * already-installed application and replace it with our own 7033 * while keeping the application data. 7034 */ 7035 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7036 + " reverting from " + ps.codePathString + ": new version " 7037 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7038 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7039 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7040 synchronized (mInstallLock) { 7041 args.cleanUpResourcesLI(); 7042 } 7043 } 7044 } 7045 } 7046 7047 // The apk is forward locked (not public) if its code and resources 7048 // are kept in different files. (except for app in either system or 7049 // vendor path). 7050 // TODO grab this value from PackageSettings 7051 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7052 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7053 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7054 } 7055 } 7056 7057 // TODO: extend to support forward-locked splits 7058 String resourcePath = null; 7059 String baseResourcePath = null; 7060 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7061 if (ps != null && ps.resourcePathString != null) { 7062 resourcePath = ps.resourcePathString; 7063 baseResourcePath = ps.resourcePathString; 7064 } else { 7065 // Should not happen at all. Just log an error. 7066 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7067 } 7068 } else { 7069 resourcePath = pkg.codePath; 7070 baseResourcePath = pkg.baseCodePath; 7071 } 7072 7073 // Set application objects path explicitly. 7074 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7075 pkg.setApplicationInfoCodePath(pkg.codePath); 7076 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7077 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7078 pkg.setApplicationInfoResourcePath(resourcePath); 7079 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7080 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7081 7082 // Note that we invoke the following method only if we are about to unpack an application 7083 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7084 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7085 7086 /* 7087 * If the system app should be overridden by a previously installed 7088 * data, hide the system app now and let the /data/app scan pick it up 7089 * again. 7090 */ 7091 if (shouldHideSystemApp) { 7092 synchronized (mPackages) { 7093 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7094 } 7095 } 7096 7097 return scannedPkg; 7098 } 7099 7100 private static String fixProcessName(String defProcessName, 7101 String processName, int uid) { 7102 if (processName == null) { 7103 return defProcessName; 7104 } 7105 return processName; 7106 } 7107 7108 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7109 throws PackageManagerException { 7110 if (pkgSetting.signatures.mSignatures != null) { 7111 // Already existing package. Make sure signatures match 7112 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7113 == PackageManager.SIGNATURE_MATCH; 7114 if (!match) { 7115 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7116 == PackageManager.SIGNATURE_MATCH; 7117 } 7118 if (!match) { 7119 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7120 == PackageManager.SIGNATURE_MATCH; 7121 } 7122 if (!match) { 7123 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7124 + pkg.packageName + " signatures do not match the " 7125 + "previously installed version; ignoring!"); 7126 } 7127 } 7128 7129 // Check for shared user signatures 7130 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7131 // Already existing package. Make sure signatures match 7132 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7133 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7134 if (!match) { 7135 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7136 == PackageManager.SIGNATURE_MATCH; 7137 } 7138 if (!match) { 7139 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7140 == PackageManager.SIGNATURE_MATCH; 7141 } 7142 if (!match) { 7143 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7144 "Package " + pkg.packageName 7145 + " has no signatures that match those in shared user " 7146 + pkgSetting.sharedUser.name + "; ignoring!"); 7147 } 7148 } 7149 } 7150 7151 /** 7152 * Enforces that only the system UID or root's UID can call a method exposed 7153 * via Binder. 7154 * 7155 * @param message used as message if SecurityException is thrown 7156 * @throws SecurityException if the caller is not system or root 7157 */ 7158 private static final void enforceSystemOrRoot(String message) { 7159 final int uid = Binder.getCallingUid(); 7160 if (uid != Process.SYSTEM_UID && uid != 0) { 7161 throw new SecurityException(message); 7162 } 7163 } 7164 7165 @Override 7166 public void performFstrimIfNeeded() { 7167 enforceSystemOrRoot("Only the system can request fstrim"); 7168 7169 // Before everything else, see whether we need to fstrim. 7170 try { 7171 IMountService ms = PackageHelper.getMountService(); 7172 if (ms != null) { 7173 final boolean isUpgrade = isUpgrade(); 7174 boolean doTrim = isUpgrade; 7175 if (doTrim) { 7176 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7177 } else { 7178 final long interval = android.provider.Settings.Global.getLong( 7179 mContext.getContentResolver(), 7180 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7181 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7182 if (interval > 0) { 7183 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7184 if (timeSinceLast > interval) { 7185 doTrim = true; 7186 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7187 + "; running immediately"); 7188 } 7189 } 7190 } 7191 if (doTrim) { 7192 if (!isFirstBoot()) { 7193 try { 7194 ActivityManagerNative.getDefault().showBootMessage( 7195 mContext.getResources().getString( 7196 R.string.android_upgrading_fstrim), true); 7197 } catch (RemoteException e) { 7198 } 7199 } 7200 ms.runMaintenance(); 7201 } 7202 } else { 7203 Slog.e(TAG, "Mount service unavailable!"); 7204 } 7205 } catch (RemoteException e) { 7206 // Can't happen; MountService is local 7207 } 7208 } 7209 7210 @Override 7211 public void updatePackagesIfNeeded() { 7212 enforceSystemOrRoot("Only the system can request package update"); 7213 7214 // We need to re-extract after an OTA. 7215 boolean causeUpgrade = isUpgrade(); 7216 7217 // First boot or factory reset. 7218 // Note: we also handle devices that are upgrading to N right now as if it is their 7219 // first boot, as they do not have profile data. 7220 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7221 7222 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7223 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7224 7225 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7226 return; 7227 } 7228 7229 List<PackageParser.Package> pkgs; 7230 synchronized (mPackages) { 7231 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7232 } 7233 7234 int numberOfPackagesVisited = 0; 7235 int numberOfPackagesOptimized = 0; 7236 int numberOfPackagesSkipped = 0; 7237 int numberOfPackagesFailed = 0; 7238 final int numberOfPackagesToDexopt = pkgs.size(); 7239 final long startTime = System.nanoTime(); 7240 7241 for (PackageParser.Package pkg : pkgs) { 7242 numberOfPackagesVisited++; 7243 7244 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7245 if (DEBUG_DEXOPT) { 7246 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7247 } 7248 numberOfPackagesSkipped++; 7249 continue; 7250 } 7251 7252 if (DEBUG_DEXOPT) { 7253 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7254 numberOfPackagesToDexopt + ": " + pkg.packageName); 7255 } 7256 7257 if (mIsPreNUpgrade) { 7258 try { 7259 ActivityManagerNative.getDefault().showBootMessage( 7260 mContext.getResources().getString(R.string.android_upgrading_apk, 7261 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7262 } catch (RemoteException e) { 7263 } 7264 } 7265 7266 // checkProfiles is false to avoid merging profiles during boot which 7267 // might interfere with background compilation (b/28612421). 7268 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7269 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7270 // trade-off worth doing to save boot time work. 7271 int dexOptStatus = performDexOptTraced(pkg.packageName, 7272 false /* checkProfiles */, 7273 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7274 false /* force */); 7275 switch (dexOptStatus) { 7276 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7277 numberOfPackagesOptimized++; 7278 break; 7279 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7280 numberOfPackagesSkipped++; 7281 break; 7282 case PackageDexOptimizer.DEX_OPT_FAILED: 7283 numberOfPackagesFailed++; 7284 break; 7285 default: 7286 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7287 break; 7288 } 7289 } 7290 7291 final int elapsedTimeSeconds = 7292 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7293 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7294 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7295 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7296 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7297 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7298 } 7299 7300 @Override 7301 public void notifyPackageUse(String packageName, int reason) { 7302 synchronized (mPackages) { 7303 PackageParser.Package p = mPackages.get(packageName); 7304 if (p == null) { 7305 return; 7306 } 7307 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7308 } 7309 } 7310 7311 // TODO: this is not used nor needed. Delete it. 7312 @Override 7313 public boolean performDexOptIfNeeded(String packageName) { 7314 int dexOptStatus = performDexOptTraced(packageName, 7315 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7316 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7317 } 7318 7319 @Override 7320 public boolean performDexOpt(String packageName, 7321 boolean checkProfiles, int compileReason, boolean force) { 7322 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7323 getCompilerFilterForReason(compileReason), force); 7324 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7325 } 7326 7327 @Override 7328 public boolean performDexOptMode(String packageName, 7329 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7330 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7331 targetCompilerFilter, force); 7332 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7333 } 7334 7335 private int performDexOptTraced(String packageName, 7336 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7337 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7338 try { 7339 return performDexOptInternal(packageName, checkProfiles, 7340 targetCompilerFilter, force); 7341 } finally { 7342 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7343 } 7344 } 7345 7346 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7347 // if the package can now be considered up to date for the given filter. 7348 private int performDexOptInternal(String packageName, 7349 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7350 PackageParser.Package p; 7351 synchronized (mPackages) { 7352 p = mPackages.get(packageName); 7353 if (p == null) { 7354 // Package could not be found. Report failure. 7355 return PackageDexOptimizer.DEX_OPT_FAILED; 7356 } 7357 mPackageUsage.write(false); 7358 } 7359 long callingId = Binder.clearCallingIdentity(); 7360 try { 7361 synchronized (mInstallLock) { 7362 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7363 targetCompilerFilter, force); 7364 } 7365 } finally { 7366 Binder.restoreCallingIdentity(callingId); 7367 } 7368 } 7369 7370 public ArraySet<String> getOptimizablePackages() { 7371 ArraySet<String> pkgs = new ArraySet<String>(); 7372 synchronized (mPackages) { 7373 for (PackageParser.Package p : mPackages.values()) { 7374 if (PackageDexOptimizer.canOptimizePackage(p)) { 7375 pkgs.add(p.packageName); 7376 } 7377 } 7378 } 7379 return pkgs; 7380 } 7381 7382 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7383 boolean checkProfiles, String targetCompilerFilter, 7384 boolean force) { 7385 // Select the dex optimizer based on the force parameter. 7386 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7387 // allocate an object here. 7388 PackageDexOptimizer pdo = force 7389 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7390 : mPackageDexOptimizer; 7391 7392 // Optimize all dependencies first. Note: we ignore the return value and march on 7393 // on errors. 7394 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7395 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7396 if (!deps.isEmpty()) { 7397 for (PackageParser.Package depPackage : deps) { 7398 // TODO: Analyze and investigate if we (should) profile libraries. 7399 // Currently this will do a full compilation of the library by default. 7400 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7401 false /* checkProfiles */, 7402 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7403 } 7404 } 7405 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7406 targetCompilerFilter); 7407 } 7408 7409 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7410 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7411 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7412 Set<String> collectedNames = new HashSet<>(); 7413 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7414 7415 retValue.remove(p); 7416 7417 return retValue; 7418 } else { 7419 return Collections.emptyList(); 7420 } 7421 } 7422 7423 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7424 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7425 if (!collectedNames.contains(p.packageName)) { 7426 collectedNames.add(p.packageName); 7427 collected.add(p); 7428 7429 if (p.usesLibraries != null) { 7430 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7431 } 7432 if (p.usesOptionalLibraries != null) { 7433 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7434 collectedNames); 7435 } 7436 } 7437 } 7438 7439 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7440 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7441 for (String libName : libs) { 7442 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7443 if (libPkg != null) { 7444 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7445 } 7446 } 7447 } 7448 7449 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7450 synchronized (mPackages) { 7451 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7452 if (lib != null && lib.apk != null) { 7453 return mPackages.get(lib.apk); 7454 } 7455 } 7456 return null; 7457 } 7458 7459 public void shutdown() { 7460 mPackageUsage.write(true); 7461 } 7462 7463 @Override 7464 public void forceDexOpt(String packageName) { 7465 enforceSystemOrRoot("forceDexOpt"); 7466 7467 PackageParser.Package pkg; 7468 synchronized (mPackages) { 7469 pkg = mPackages.get(packageName); 7470 if (pkg == null) { 7471 throw new IllegalArgumentException("Unknown package: " + packageName); 7472 } 7473 } 7474 7475 synchronized (mInstallLock) { 7476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7477 7478 // Whoever is calling forceDexOpt wants a fully compiled package. 7479 // Don't use profiles since that may cause compilation to be skipped. 7480 final int res = performDexOptInternalWithDependenciesLI(pkg, 7481 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7482 true /* force */); 7483 7484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7485 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7486 throw new IllegalStateException("Failed to dexopt: " + res); 7487 } 7488 } 7489 } 7490 7491 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7492 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7493 Slog.w(TAG, "Unable to update from " + oldPkg.name 7494 + " to " + newPkg.packageName 7495 + ": old package not in system partition"); 7496 return false; 7497 } else if (mPackages.get(oldPkg.name) != null) { 7498 Slog.w(TAG, "Unable to update from " + oldPkg.name 7499 + " to " + newPkg.packageName 7500 + ": old package still exists"); 7501 return false; 7502 } 7503 return true; 7504 } 7505 7506 void removeCodePathLI(File codePath) { 7507 if (codePath.isDirectory()) { 7508 try { 7509 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7510 } catch (InstallerException e) { 7511 Slog.w(TAG, "Failed to remove code path", e); 7512 } 7513 } else { 7514 codePath.delete(); 7515 } 7516 } 7517 7518 private int[] resolveUserIds(int userId) { 7519 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7520 } 7521 7522 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7523 if (pkg == null) { 7524 Slog.wtf(TAG, "Package was null!", new Throwable()); 7525 return; 7526 } 7527 clearAppDataLeafLIF(pkg, userId, flags); 7528 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7529 for (int i = 0; i < childCount; i++) { 7530 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7531 } 7532 } 7533 7534 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7535 final PackageSetting ps; 7536 synchronized (mPackages) { 7537 ps = mSettings.mPackages.get(pkg.packageName); 7538 } 7539 for (int realUserId : resolveUserIds(userId)) { 7540 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7541 try { 7542 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7543 ceDataInode); 7544 } catch (InstallerException e) { 7545 Slog.w(TAG, String.valueOf(e)); 7546 } 7547 } 7548 } 7549 7550 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7551 if (pkg == null) { 7552 Slog.wtf(TAG, "Package was null!", new Throwable()); 7553 return; 7554 } 7555 destroyAppDataLeafLIF(pkg, userId, flags); 7556 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7557 for (int i = 0; i < childCount; i++) { 7558 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7559 } 7560 } 7561 7562 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7563 final PackageSetting ps; 7564 synchronized (mPackages) { 7565 ps = mSettings.mPackages.get(pkg.packageName); 7566 } 7567 for (int realUserId : resolveUserIds(userId)) { 7568 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7569 try { 7570 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7571 ceDataInode); 7572 } catch (InstallerException e) { 7573 Slog.w(TAG, String.valueOf(e)); 7574 } 7575 } 7576 } 7577 7578 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7579 if (pkg == null) { 7580 Slog.wtf(TAG, "Package was null!", new Throwable()); 7581 return; 7582 } 7583 destroyAppProfilesLeafLIF(pkg); 7584 destroyAppReferenceProfileLeafLIF(pkg, userId); 7585 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7586 for (int i = 0; i < childCount; i++) { 7587 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7588 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId); 7589 } 7590 } 7591 7592 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) { 7593 if (pkg.isForwardLocked()) { 7594 return; 7595 } 7596 7597 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7598 try { 7599 path = PackageManagerServiceUtils.realpath(new File(path)); 7600 } catch (IOException e) { 7601 // TODO: Should we return early here ? 7602 Slog.w(TAG, "Failed to get canonical path", e); 7603 continue; 7604 } 7605 7606 final String useMarker = path.replace('/', '@'); 7607 for (int realUserId : resolveUserIds(userId)) { 7608 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7609 File foreignUseMark = new File(profileDir, useMarker); 7610 if (foreignUseMark.exists()) { 7611 if (!foreignUseMark.delete()) { 7612 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7613 + pkg.packageName); 7614 } 7615 } 7616 7617 File[] markers = profileDir.listFiles(); 7618 if (markers != null) { 7619 final String searchString = "@" + pkg.packageName + "@"; 7620 // We also delete all markers that contain the package name we're 7621 // uninstalling. These are associated with secondary dex-files belonging 7622 // to the package. Reconstructing the path of these dex files is messy 7623 // in general. 7624 for (File marker : markers) { 7625 if (marker.getName().indexOf(searchString) > 0) { 7626 if (!marker.delete()) { 7627 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7628 + pkg.packageName); 7629 } 7630 } 7631 } 7632 } 7633 } 7634 } 7635 } 7636 7637 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7638 try { 7639 mInstaller.destroyAppProfiles(pkg.packageName); 7640 } catch (InstallerException e) { 7641 Slog.w(TAG, String.valueOf(e)); 7642 } 7643 } 7644 7645 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7646 if (pkg == null) { 7647 Slog.wtf(TAG, "Package was null!", new Throwable()); 7648 return; 7649 } 7650 clearAppProfilesLeafLIF(pkg); 7651 destroyAppReferenceProfileLeafLIF(pkg, userId); 7652 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7653 for (int i = 0; i < childCount; i++) { 7654 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7655 } 7656 } 7657 7658 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7659 try { 7660 mInstaller.clearAppProfiles(pkg.packageName); 7661 } catch (InstallerException e) { 7662 Slog.w(TAG, String.valueOf(e)); 7663 } 7664 } 7665 7666 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7667 long lastUpdateTime) { 7668 // Set parent install/update time 7669 PackageSetting ps = (PackageSetting) pkg.mExtras; 7670 if (ps != null) { 7671 ps.firstInstallTime = firstInstallTime; 7672 ps.lastUpdateTime = lastUpdateTime; 7673 } 7674 // Set children install/update time 7675 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7676 for (int i = 0; i < childCount; i++) { 7677 PackageParser.Package childPkg = pkg.childPackages.get(i); 7678 ps = (PackageSetting) childPkg.mExtras; 7679 if (ps != null) { 7680 ps.firstInstallTime = firstInstallTime; 7681 ps.lastUpdateTime = lastUpdateTime; 7682 } 7683 } 7684 } 7685 7686 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7687 PackageParser.Package changingLib) { 7688 if (file.path != null) { 7689 usesLibraryFiles.add(file.path); 7690 return; 7691 } 7692 PackageParser.Package p = mPackages.get(file.apk); 7693 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7694 // If we are doing this while in the middle of updating a library apk, 7695 // then we need to make sure to use that new apk for determining the 7696 // dependencies here. (We haven't yet finished committing the new apk 7697 // to the package manager state.) 7698 if (p == null || p.packageName.equals(changingLib.packageName)) { 7699 p = changingLib; 7700 } 7701 } 7702 if (p != null) { 7703 usesLibraryFiles.addAll(p.getAllCodePaths()); 7704 } 7705 } 7706 7707 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7708 PackageParser.Package changingLib) throws PackageManagerException { 7709 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7710 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7711 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7712 for (int i=0; i<N; i++) { 7713 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7714 if (file == null) { 7715 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7716 "Package " + pkg.packageName + " requires unavailable shared library " 7717 + pkg.usesLibraries.get(i) + "; failing!"); 7718 } 7719 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7720 } 7721 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7722 for (int i=0; i<N; i++) { 7723 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7724 if (file == null) { 7725 Slog.w(TAG, "Package " + pkg.packageName 7726 + " desires unavailable shared library " 7727 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7728 } else { 7729 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7730 } 7731 } 7732 N = usesLibraryFiles.size(); 7733 if (N > 0) { 7734 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7735 } else { 7736 pkg.usesLibraryFiles = null; 7737 } 7738 } 7739 } 7740 7741 private static boolean hasString(List<String> list, List<String> which) { 7742 if (list == null) { 7743 return false; 7744 } 7745 for (int i=list.size()-1; i>=0; i--) { 7746 for (int j=which.size()-1; j>=0; j--) { 7747 if (which.get(j).equals(list.get(i))) { 7748 return true; 7749 } 7750 } 7751 } 7752 return false; 7753 } 7754 7755 private void updateAllSharedLibrariesLPw() { 7756 for (PackageParser.Package pkg : mPackages.values()) { 7757 try { 7758 updateSharedLibrariesLPw(pkg, null); 7759 } catch (PackageManagerException e) { 7760 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7761 } 7762 } 7763 } 7764 7765 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7766 PackageParser.Package changingPkg) { 7767 ArrayList<PackageParser.Package> res = null; 7768 for (PackageParser.Package pkg : mPackages.values()) { 7769 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7770 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7771 if (res == null) { 7772 res = new ArrayList<PackageParser.Package>(); 7773 } 7774 res.add(pkg); 7775 try { 7776 updateSharedLibrariesLPw(pkg, changingPkg); 7777 } catch (PackageManagerException e) { 7778 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7779 } 7780 } 7781 } 7782 return res; 7783 } 7784 7785 /** 7786 * Derive the value of the {@code cpuAbiOverride} based on the provided 7787 * value and an optional stored value from the package settings. 7788 */ 7789 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7790 String cpuAbiOverride = null; 7791 7792 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7793 cpuAbiOverride = null; 7794 } else if (abiOverride != null) { 7795 cpuAbiOverride = abiOverride; 7796 } else if (settings != null) { 7797 cpuAbiOverride = settings.cpuAbiOverrideString; 7798 } 7799 7800 return cpuAbiOverride; 7801 } 7802 7803 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7804 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7805 throws PackageManagerException { 7806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7807 // If the package has children and this is the first dive in the function 7808 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7809 // whether all packages (parent and children) would be successfully scanned 7810 // before the actual scan since scanning mutates internal state and we want 7811 // to atomically install the package and its children. 7812 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7813 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7814 scanFlags |= SCAN_CHECK_ONLY; 7815 } 7816 } else { 7817 scanFlags &= ~SCAN_CHECK_ONLY; 7818 } 7819 7820 final PackageParser.Package scannedPkg; 7821 try { 7822 // Scan the parent 7823 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7824 // Scan the children 7825 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7826 for (int i = 0; i < childCount; i++) { 7827 PackageParser.Package childPkg = pkg.childPackages.get(i); 7828 scanPackageLI(childPkg, policyFlags, 7829 scanFlags, currentTime, user); 7830 } 7831 } finally { 7832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7833 } 7834 7835 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7836 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7837 } 7838 7839 return scannedPkg; 7840 } 7841 7842 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7843 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7844 boolean success = false; 7845 try { 7846 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7847 currentTime, user); 7848 success = true; 7849 return res; 7850 } finally { 7851 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7852 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7853 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7854 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7855 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7856 } 7857 } 7858 } 7859 7860 /** 7861 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7862 */ 7863 private static boolean apkHasCode(String fileName) { 7864 StrictJarFile jarFile = null; 7865 try { 7866 jarFile = new StrictJarFile(fileName, 7867 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7868 return jarFile.findEntry("classes.dex") != null; 7869 } catch (IOException ignore) { 7870 } finally { 7871 try { 7872 jarFile.close(); 7873 } catch (IOException ignore) {} 7874 } 7875 return false; 7876 } 7877 7878 /** 7879 * Enforces code policy for the package. This ensures that if an APK has 7880 * declared hasCode="true" in its manifest that the APK actually contains 7881 * code. 7882 * 7883 * @throws PackageManagerException If bytecode could not be found when it should exist 7884 */ 7885 private static void enforceCodePolicy(PackageParser.Package pkg) 7886 throws PackageManagerException { 7887 final boolean shouldHaveCode = 7888 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7889 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7890 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7891 "Package " + pkg.baseCodePath + " code is missing"); 7892 } 7893 7894 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7895 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7896 final boolean splitShouldHaveCode = 7897 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7898 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7899 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7900 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7901 } 7902 } 7903 } 7904 } 7905 7906 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7907 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7908 throws PackageManagerException { 7909 final File scanFile = new File(pkg.codePath); 7910 if (pkg.applicationInfo.getCodePath() == null || 7911 pkg.applicationInfo.getResourcePath() == null) { 7912 // Bail out. The resource and code paths haven't been set. 7913 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7914 "Code and resource paths haven't been set correctly"); 7915 } 7916 7917 // Apply policy 7918 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7919 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7920 if (pkg.applicationInfo.isDirectBootAware()) { 7921 // we're direct boot aware; set for all components 7922 for (PackageParser.Service s : pkg.services) { 7923 s.info.encryptionAware = s.info.directBootAware = true; 7924 } 7925 for (PackageParser.Provider p : pkg.providers) { 7926 p.info.encryptionAware = p.info.directBootAware = true; 7927 } 7928 for (PackageParser.Activity a : pkg.activities) { 7929 a.info.encryptionAware = a.info.directBootAware = true; 7930 } 7931 for (PackageParser.Activity r : pkg.receivers) { 7932 r.info.encryptionAware = r.info.directBootAware = true; 7933 } 7934 } 7935 } else { 7936 // Only allow system apps to be flagged as core apps. 7937 pkg.coreApp = false; 7938 // clear flags not applicable to regular apps 7939 pkg.applicationInfo.privateFlags &= 7940 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7941 pkg.applicationInfo.privateFlags &= 7942 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7943 } 7944 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7945 7946 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7947 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7948 } 7949 7950 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7951 enforceCodePolicy(pkg); 7952 } 7953 7954 if (mCustomResolverComponentName != null && 7955 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7956 setUpCustomResolverActivity(pkg); 7957 } 7958 7959 if (pkg.packageName.equals("android")) { 7960 synchronized (mPackages) { 7961 if (mAndroidApplication != null) { 7962 Slog.w(TAG, "*************************************************"); 7963 Slog.w(TAG, "Core android package being redefined. Skipping."); 7964 Slog.w(TAG, " file=" + scanFile); 7965 Slog.w(TAG, "*************************************************"); 7966 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7967 "Core android package being redefined. Skipping."); 7968 } 7969 7970 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7971 // Set up information for our fall-back user intent resolution activity. 7972 mPlatformPackage = pkg; 7973 pkg.mVersionCode = mSdkVersion; 7974 mAndroidApplication = pkg.applicationInfo; 7975 7976 if (!mResolverReplaced) { 7977 mResolveActivity.applicationInfo = mAndroidApplication; 7978 mResolveActivity.name = ResolverActivity.class.getName(); 7979 mResolveActivity.packageName = mAndroidApplication.packageName; 7980 mResolveActivity.processName = "system:ui"; 7981 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7982 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7983 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7984 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7985 mResolveActivity.exported = true; 7986 mResolveActivity.enabled = true; 7987 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7988 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7989 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7990 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7991 | ActivityInfo.CONFIG_ORIENTATION 7992 | ActivityInfo.CONFIG_KEYBOARD 7993 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7994 mResolveInfo.activityInfo = mResolveActivity; 7995 mResolveInfo.priority = 0; 7996 mResolveInfo.preferredOrder = 0; 7997 mResolveInfo.match = 0; 7998 mResolveComponentName = new ComponentName( 7999 mAndroidApplication.packageName, mResolveActivity.name); 8000 } 8001 } 8002 } 8003 } 8004 8005 if (DEBUG_PACKAGE_SCANNING) { 8006 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8007 Log.d(TAG, "Scanning package " + pkg.packageName); 8008 } 8009 8010 synchronized (mPackages) { 8011 if (mPackages.containsKey(pkg.packageName) 8012 || mSharedLibraries.containsKey(pkg.packageName)) { 8013 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8014 "Application package " + pkg.packageName 8015 + " already installed. Skipping duplicate."); 8016 } 8017 8018 // If we're only installing presumed-existing packages, require that the 8019 // scanned APK is both already known and at the path previously established 8020 // for it. Previously unknown packages we pick up normally, but if we have an 8021 // a priori expectation about this package's install presence, enforce it. 8022 // With a singular exception for new system packages. When an OTA contains 8023 // a new system package, we allow the codepath to change from a system location 8024 // to the user-installed location. If we don't allow this change, any newer, 8025 // user-installed version of the application will be ignored. 8026 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8027 if (mExpectingBetter.containsKey(pkg.packageName)) { 8028 logCriticalInfo(Log.WARN, 8029 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8030 } else { 8031 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8032 if (known != null) { 8033 if (DEBUG_PACKAGE_SCANNING) { 8034 Log.d(TAG, "Examining " + pkg.codePath 8035 + " and requiring known paths " + known.codePathString 8036 + " & " + known.resourcePathString); 8037 } 8038 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8039 || !pkg.applicationInfo.getResourcePath().equals( 8040 known.resourcePathString)) { 8041 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8042 "Application package " + pkg.packageName 8043 + " found at " + pkg.applicationInfo.getCodePath() 8044 + " but expected at " + known.codePathString 8045 + "; ignoring."); 8046 } 8047 } 8048 } 8049 } 8050 } 8051 8052 // Initialize package source and resource directories 8053 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8054 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8055 8056 SharedUserSetting suid = null; 8057 PackageSetting pkgSetting = null; 8058 8059 if (!isSystemApp(pkg)) { 8060 // Only system apps can use these features. 8061 pkg.mOriginalPackages = null; 8062 pkg.mRealPackage = null; 8063 pkg.mAdoptPermissions = null; 8064 } 8065 8066 // Getting the package setting may have a side-effect, so if we 8067 // are only checking if scan would succeed, stash a copy of the 8068 // old setting to restore at the end. 8069 PackageSetting nonMutatedPs = null; 8070 8071 // writer 8072 synchronized (mPackages) { 8073 if (pkg.mSharedUserId != null) { 8074 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8075 if (suid == null) { 8076 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8077 "Creating application package " + pkg.packageName 8078 + " for shared user failed"); 8079 } 8080 if (DEBUG_PACKAGE_SCANNING) { 8081 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8082 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8083 + "): packages=" + suid.packages); 8084 } 8085 } 8086 8087 // Check if we are renaming from an original package name. 8088 PackageSetting origPackage = null; 8089 String realName = null; 8090 if (pkg.mOriginalPackages != null) { 8091 // This package may need to be renamed to a previously 8092 // installed name. Let's check on that... 8093 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8094 if (pkg.mOriginalPackages.contains(renamed)) { 8095 // This package had originally been installed as the 8096 // original name, and we have already taken care of 8097 // transitioning to the new one. Just update the new 8098 // one to continue using the old name. 8099 realName = pkg.mRealPackage; 8100 if (!pkg.packageName.equals(renamed)) { 8101 // Callers into this function may have already taken 8102 // care of renaming the package; only do it here if 8103 // it is not already done. 8104 pkg.setPackageName(renamed); 8105 } 8106 8107 } else { 8108 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8109 if ((origPackage = mSettings.peekPackageLPr( 8110 pkg.mOriginalPackages.get(i))) != null) { 8111 // We do have the package already installed under its 8112 // original name... should we use it? 8113 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8114 // New package is not compatible with original. 8115 origPackage = null; 8116 continue; 8117 } else if (origPackage.sharedUser != null) { 8118 // Make sure uid is compatible between packages. 8119 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8120 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8121 + " to " + pkg.packageName + ": old uid " 8122 + origPackage.sharedUser.name 8123 + " differs from " + pkg.mSharedUserId); 8124 origPackage = null; 8125 continue; 8126 } 8127 // TODO: Add case when shared user id is added [b/28144775] 8128 } else { 8129 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8130 + pkg.packageName + " to old name " + origPackage.name); 8131 } 8132 break; 8133 } 8134 } 8135 } 8136 } 8137 8138 if (mTransferedPackages.contains(pkg.packageName)) { 8139 Slog.w(TAG, "Package " + pkg.packageName 8140 + " was transferred to another, but its .apk remains"); 8141 } 8142 8143 // See comments in nonMutatedPs declaration 8144 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8145 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8146 if (foundPs != null) { 8147 nonMutatedPs = new PackageSetting(foundPs); 8148 } 8149 } 8150 8151 // Just create the setting, don't add it yet. For already existing packages 8152 // the PkgSetting exists already and doesn't have to be created. 8153 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8154 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8155 pkg.applicationInfo.primaryCpuAbi, 8156 pkg.applicationInfo.secondaryCpuAbi, 8157 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8158 user, false); 8159 if (pkgSetting == null) { 8160 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8161 "Creating application package " + pkg.packageName + " failed"); 8162 } 8163 8164 if (pkgSetting.origPackage != null) { 8165 // If we are first transitioning from an original package, 8166 // fix up the new package's name now. We need to do this after 8167 // looking up the package under its new name, so getPackageLP 8168 // can take care of fiddling things correctly. 8169 pkg.setPackageName(origPackage.name); 8170 8171 // File a report about this. 8172 String msg = "New package " + pkgSetting.realName 8173 + " renamed to replace old package " + pkgSetting.name; 8174 reportSettingsProblem(Log.WARN, msg); 8175 8176 // Make a note of it. 8177 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8178 mTransferedPackages.add(origPackage.name); 8179 } 8180 8181 // No longer need to retain this. 8182 pkgSetting.origPackage = null; 8183 } 8184 8185 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8186 // Make a note of it. 8187 mTransferedPackages.add(pkg.packageName); 8188 } 8189 8190 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8191 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8192 } 8193 8194 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8195 // Check all shared libraries and map to their actual file path. 8196 // We only do this here for apps not on a system dir, because those 8197 // are the only ones that can fail an install due to this. We 8198 // will take care of the system apps by updating all of their 8199 // library paths after the scan is done. 8200 updateSharedLibrariesLPw(pkg, null); 8201 } 8202 8203 if (mFoundPolicyFile) { 8204 SELinuxMMAC.assignSeinfoValue(pkg); 8205 } 8206 8207 pkg.applicationInfo.uid = pkgSetting.appId; 8208 pkg.mExtras = pkgSetting; 8209 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8210 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8211 // We just determined the app is signed correctly, so bring 8212 // over the latest parsed certs. 8213 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8214 } else { 8215 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8216 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8217 "Package " + pkg.packageName + " upgrade keys do not match the " 8218 + "previously installed version"); 8219 } else { 8220 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8221 String msg = "System package " + pkg.packageName 8222 + " signature changed; retaining data."; 8223 reportSettingsProblem(Log.WARN, msg); 8224 } 8225 } 8226 } else { 8227 try { 8228 verifySignaturesLP(pkgSetting, pkg); 8229 // We just determined the app is signed correctly, so bring 8230 // over the latest parsed certs. 8231 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8232 } catch (PackageManagerException e) { 8233 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8234 throw e; 8235 } 8236 // The signature has changed, but this package is in the system 8237 // image... let's recover! 8238 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8239 // However... if this package is part of a shared user, but it 8240 // doesn't match the signature of the shared user, let's fail. 8241 // What this means is that you can't change the signatures 8242 // associated with an overall shared user, which doesn't seem all 8243 // that unreasonable. 8244 if (pkgSetting.sharedUser != null) { 8245 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8246 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8247 throw new PackageManagerException( 8248 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8249 "Signature mismatch for shared user: " 8250 + pkgSetting.sharedUser); 8251 } 8252 } 8253 // File a report about this. 8254 String msg = "System package " + pkg.packageName 8255 + " signature changed; retaining data."; 8256 reportSettingsProblem(Log.WARN, msg); 8257 } 8258 } 8259 // Verify that this new package doesn't have any content providers 8260 // that conflict with existing packages. Only do this if the 8261 // package isn't already installed, since we don't want to break 8262 // things that are installed. 8263 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8264 final int N = pkg.providers.size(); 8265 int i; 8266 for (i=0; i<N; i++) { 8267 PackageParser.Provider p = pkg.providers.get(i); 8268 if (p.info.authority != null) { 8269 String names[] = p.info.authority.split(";"); 8270 for (int j = 0; j < names.length; j++) { 8271 if (mProvidersByAuthority.containsKey(names[j])) { 8272 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8273 final String otherPackageName = 8274 ((other != null && other.getComponentName() != null) ? 8275 other.getComponentName().getPackageName() : "?"); 8276 throw new PackageManagerException( 8277 INSTALL_FAILED_CONFLICTING_PROVIDER, 8278 "Can't install because provider name " + names[j] 8279 + " (in package " + pkg.applicationInfo.packageName 8280 + ") is already used by " + otherPackageName); 8281 } 8282 } 8283 } 8284 } 8285 } 8286 8287 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8288 // This package wants to adopt ownership of permissions from 8289 // another package. 8290 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8291 final String origName = pkg.mAdoptPermissions.get(i); 8292 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8293 if (orig != null) { 8294 if (verifyPackageUpdateLPr(orig, pkg)) { 8295 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8296 + pkg.packageName); 8297 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8298 } 8299 } 8300 } 8301 } 8302 } 8303 8304 final String pkgName = pkg.packageName; 8305 8306 final long scanFileTime = scanFile.lastModified(); 8307 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8308 pkg.applicationInfo.processName = fixProcessName( 8309 pkg.applicationInfo.packageName, 8310 pkg.applicationInfo.processName, 8311 pkg.applicationInfo.uid); 8312 8313 if (pkg != mPlatformPackage) { 8314 // Get all of our default paths setup 8315 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8316 } 8317 8318 final String path = scanFile.getPath(); 8319 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8320 8321 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8322 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8323 8324 // Some system apps still use directory structure for native libraries 8325 // in which case we might end up not detecting abi solely based on apk 8326 // structure. Try to detect abi based on directory structure. 8327 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8328 pkg.applicationInfo.primaryCpuAbi == null) { 8329 setBundledAppAbisAndRoots(pkg, pkgSetting); 8330 setNativeLibraryPaths(pkg); 8331 } 8332 8333 } else { 8334 if ((scanFlags & SCAN_MOVE) != 0) { 8335 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8336 // but we already have this packages package info in the PackageSetting. We just 8337 // use that and derive the native library path based on the new codepath. 8338 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8339 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8340 } 8341 8342 // Set native library paths again. For moves, the path will be updated based on the 8343 // ABIs we've determined above. For non-moves, the path will be updated based on the 8344 // ABIs we determined during compilation, but the path will depend on the final 8345 // package path (after the rename away from the stage path). 8346 setNativeLibraryPaths(pkg); 8347 } 8348 8349 // This is a special case for the "system" package, where the ABI is 8350 // dictated by the zygote configuration (and init.rc). We should keep track 8351 // of this ABI so that we can deal with "normal" applications that run under 8352 // the same UID correctly. 8353 if (mPlatformPackage == pkg) { 8354 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8355 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8356 } 8357 8358 // If there's a mismatch between the abi-override in the package setting 8359 // and the abiOverride specified for the install. Warn about this because we 8360 // would've already compiled the app without taking the package setting into 8361 // account. 8362 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8363 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8364 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8365 " for package " + pkg.packageName); 8366 } 8367 } 8368 8369 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8370 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8371 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8372 8373 // Copy the derived override back to the parsed package, so that we can 8374 // update the package settings accordingly. 8375 pkg.cpuAbiOverride = cpuAbiOverride; 8376 8377 if (DEBUG_ABI_SELECTION) { 8378 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8379 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8380 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8381 } 8382 8383 // Push the derived path down into PackageSettings so we know what to 8384 // clean up at uninstall time. 8385 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8386 8387 if (DEBUG_ABI_SELECTION) { 8388 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8389 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8390 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8391 } 8392 8393 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8394 // We don't do this here during boot because we can do it all 8395 // at once after scanning all existing packages. 8396 // 8397 // We also do this *before* we perform dexopt on this package, so that 8398 // we can avoid redundant dexopts, and also to make sure we've got the 8399 // code and package path correct. 8400 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8401 pkg, true /* boot complete */); 8402 } 8403 8404 if (mFactoryTest && pkg.requestedPermissions.contains( 8405 android.Manifest.permission.FACTORY_TEST)) { 8406 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8407 } 8408 8409 ArrayList<PackageParser.Package> clientLibPkgs = null; 8410 8411 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8412 if (nonMutatedPs != null) { 8413 synchronized (mPackages) { 8414 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8415 } 8416 } 8417 return pkg; 8418 } 8419 8420 // Only privileged apps and updated privileged apps can add child packages. 8421 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8422 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8423 throw new PackageManagerException("Only privileged apps and updated " 8424 + "privileged apps can add child packages. Ignoring package " 8425 + pkg.packageName); 8426 } 8427 final int childCount = pkg.childPackages.size(); 8428 for (int i = 0; i < childCount; i++) { 8429 PackageParser.Package childPkg = pkg.childPackages.get(i); 8430 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8431 childPkg.packageName)) { 8432 throw new PackageManagerException("Cannot override a child package of " 8433 + "another disabled system app. Ignoring package " + pkg.packageName); 8434 } 8435 } 8436 } 8437 8438 // writer 8439 synchronized (mPackages) { 8440 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8441 // Only system apps can add new shared libraries. 8442 if (pkg.libraryNames != null) { 8443 for (int i=0; i<pkg.libraryNames.size(); i++) { 8444 String name = pkg.libraryNames.get(i); 8445 boolean allowed = false; 8446 if (pkg.isUpdatedSystemApp()) { 8447 // New library entries can only be added through the 8448 // system image. This is important to get rid of a lot 8449 // of nasty edge cases: for example if we allowed a non- 8450 // system update of the app to add a library, then uninstalling 8451 // the update would make the library go away, and assumptions 8452 // we made such as through app install filtering would now 8453 // have allowed apps on the device which aren't compatible 8454 // with it. Better to just have the restriction here, be 8455 // conservative, and create many fewer cases that can negatively 8456 // impact the user experience. 8457 final PackageSetting sysPs = mSettings 8458 .getDisabledSystemPkgLPr(pkg.packageName); 8459 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8460 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8461 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8462 allowed = true; 8463 break; 8464 } 8465 } 8466 } 8467 } else { 8468 allowed = true; 8469 } 8470 if (allowed) { 8471 if (!mSharedLibraries.containsKey(name)) { 8472 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8473 } else if (!name.equals(pkg.packageName)) { 8474 Slog.w(TAG, "Package " + pkg.packageName + " library " 8475 + name + " already exists; skipping"); 8476 } 8477 } else { 8478 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8479 + name + " that is not declared on system image; skipping"); 8480 } 8481 } 8482 if ((scanFlags & SCAN_BOOTING) == 0) { 8483 // If we are not booting, we need to update any applications 8484 // that are clients of our shared library. If we are booting, 8485 // this will all be done once the scan is complete. 8486 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8487 } 8488 } 8489 } 8490 } 8491 8492 if ((scanFlags & SCAN_BOOTING) != 0) { 8493 // No apps can run during boot scan, so they don't need to be frozen 8494 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8495 // Caller asked to not kill app, so it's probably not frozen 8496 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8497 // Caller asked us to ignore frozen check for some reason; they 8498 // probably didn't know the package name 8499 } else { 8500 // We're doing major surgery on this package, so it better be frozen 8501 // right now to keep it from launching 8502 checkPackageFrozen(pkgName); 8503 } 8504 8505 // Also need to kill any apps that are dependent on the library. 8506 if (clientLibPkgs != null) { 8507 for (int i=0; i<clientLibPkgs.size(); i++) { 8508 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8509 killApplication(clientPkg.applicationInfo.packageName, 8510 clientPkg.applicationInfo.uid, "update lib"); 8511 } 8512 } 8513 8514 // Make sure we're not adding any bogus keyset info 8515 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8516 ksms.assertScannedPackageValid(pkg); 8517 8518 // writer 8519 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8520 8521 boolean createIdmapFailed = false; 8522 synchronized (mPackages) { 8523 // We don't expect installation to fail beyond this point 8524 8525 // Add the new setting to mSettings 8526 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8527 // Add the new setting to mPackages 8528 mPackages.put(pkg.applicationInfo.packageName, pkg); 8529 // Make sure we don't accidentally delete its data. 8530 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8531 while (iter.hasNext()) { 8532 PackageCleanItem item = iter.next(); 8533 if (pkgName.equals(item.packageName)) { 8534 iter.remove(); 8535 } 8536 } 8537 8538 // Take care of first install / last update times. 8539 if (currentTime != 0) { 8540 if (pkgSetting.firstInstallTime == 0) { 8541 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8542 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8543 pkgSetting.lastUpdateTime = currentTime; 8544 } 8545 } else if (pkgSetting.firstInstallTime == 0) { 8546 // We need *something*. Take time time stamp of the file. 8547 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8548 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8549 if (scanFileTime != pkgSetting.timeStamp) { 8550 // A package on the system image has changed; consider this 8551 // to be an update. 8552 pkgSetting.lastUpdateTime = scanFileTime; 8553 } 8554 } 8555 8556 // Add the package's KeySets to the global KeySetManagerService 8557 ksms.addScannedPackageLPw(pkg); 8558 8559 int N = pkg.providers.size(); 8560 StringBuilder r = null; 8561 int i; 8562 for (i=0; i<N; i++) { 8563 PackageParser.Provider p = pkg.providers.get(i); 8564 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8565 p.info.processName, pkg.applicationInfo.uid); 8566 mProviders.addProvider(p); 8567 p.syncable = p.info.isSyncable; 8568 if (p.info.authority != null) { 8569 String names[] = p.info.authority.split(";"); 8570 p.info.authority = null; 8571 for (int j = 0; j < names.length; j++) { 8572 if (j == 1 && p.syncable) { 8573 // We only want the first authority for a provider to possibly be 8574 // syncable, so if we already added this provider using a different 8575 // authority clear the syncable flag. We copy the provider before 8576 // changing it because the mProviders object contains a reference 8577 // to a provider that we don't want to change. 8578 // Only do this for the second authority since the resulting provider 8579 // object can be the same for all future authorities for this provider. 8580 p = new PackageParser.Provider(p); 8581 p.syncable = false; 8582 } 8583 if (!mProvidersByAuthority.containsKey(names[j])) { 8584 mProvidersByAuthority.put(names[j], p); 8585 if (p.info.authority == null) { 8586 p.info.authority = names[j]; 8587 } else { 8588 p.info.authority = p.info.authority + ";" + names[j]; 8589 } 8590 if (DEBUG_PACKAGE_SCANNING) { 8591 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8592 Log.d(TAG, "Registered content provider: " + names[j] 8593 + ", className = " + p.info.name + ", isSyncable = " 8594 + p.info.isSyncable); 8595 } 8596 } else { 8597 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8598 Slog.w(TAG, "Skipping provider name " + names[j] + 8599 " (in package " + pkg.applicationInfo.packageName + 8600 "): name already used by " 8601 + ((other != null && other.getComponentName() != null) 8602 ? other.getComponentName().getPackageName() : "?")); 8603 } 8604 } 8605 } 8606 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8607 if (r == null) { 8608 r = new StringBuilder(256); 8609 } else { 8610 r.append(' '); 8611 } 8612 r.append(p.info.name); 8613 } 8614 } 8615 if (r != null) { 8616 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8617 } 8618 8619 N = pkg.services.size(); 8620 r = null; 8621 for (i=0; i<N; i++) { 8622 PackageParser.Service s = pkg.services.get(i); 8623 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8624 s.info.processName, pkg.applicationInfo.uid); 8625 mServices.addService(s); 8626 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8627 if (r == null) { 8628 r = new StringBuilder(256); 8629 } else { 8630 r.append(' '); 8631 } 8632 r.append(s.info.name); 8633 } 8634 } 8635 if (r != null) { 8636 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8637 } 8638 8639 N = pkg.receivers.size(); 8640 r = null; 8641 for (i=0; i<N; i++) { 8642 PackageParser.Activity a = pkg.receivers.get(i); 8643 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8644 a.info.processName, pkg.applicationInfo.uid); 8645 mReceivers.addActivity(a, "receiver"); 8646 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8647 if (r == null) { 8648 r = new StringBuilder(256); 8649 } else { 8650 r.append(' '); 8651 } 8652 r.append(a.info.name); 8653 } 8654 } 8655 if (r != null) { 8656 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8657 } 8658 8659 N = pkg.activities.size(); 8660 r = null; 8661 for (i=0; i<N; i++) { 8662 PackageParser.Activity a = pkg.activities.get(i); 8663 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8664 a.info.processName, pkg.applicationInfo.uid); 8665 mActivities.addActivity(a, "activity"); 8666 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8667 if (r == null) { 8668 r = new StringBuilder(256); 8669 } else { 8670 r.append(' '); 8671 } 8672 r.append(a.info.name); 8673 } 8674 } 8675 if (r != null) { 8676 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8677 } 8678 8679 N = pkg.permissionGroups.size(); 8680 r = null; 8681 for (i=0; i<N; i++) { 8682 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8683 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8684 if (cur == null) { 8685 mPermissionGroups.put(pg.info.name, pg); 8686 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8687 if (r == null) { 8688 r = new StringBuilder(256); 8689 } else { 8690 r.append(' '); 8691 } 8692 r.append(pg.info.name); 8693 } 8694 } else { 8695 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8696 + pg.info.packageName + " ignored: original from " 8697 + cur.info.packageName); 8698 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8699 if (r == null) { 8700 r = new StringBuilder(256); 8701 } else { 8702 r.append(' '); 8703 } 8704 r.append("DUP:"); 8705 r.append(pg.info.name); 8706 } 8707 } 8708 } 8709 if (r != null) { 8710 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8711 } 8712 8713 N = pkg.permissions.size(); 8714 r = null; 8715 for (i=0; i<N; i++) { 8716 PackageParser.Permission p = pkg.permissions.get(i); 8717 8718 // Assume by default that we did not install this permission into the system. 8719 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8720 8721 // Now that permission groups have a special meaning, we ignore permission 8722 // groups for legacy apps to prevent unexpected behavior. In particular, 8723 // permissions for one app being granted to someone just becase they happen 8724 // to be in a group defined by another app (before this had no implications). 8725 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8726 p.group = mPermissionGroups.get(p.info.group); 8727 // Warn for a permission in an unknown group. 8728 if (p.info.group != null && p.group == null) { 8729 Slog.w(TAG, "Permission " + p.info.name + " from package " 8730 + p.info.packageName + " in an unknown group " + p.info.group); 8731 } 8732 } 8733 8734 ArrayMap<String, BasePermission> permissionMap = 8735 p.tree ? mSettings.mPermissionTrees 8736 : mSettings.mPermissions; 8737 BasePermission bp = permissionMap.get(p.info.name); 8738 8739 // Allow system apps to redefine non-system permissions 8740 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8741 final boolean currentOwnerIsSystem = (bp.perm != null 8742 && isSystemApp(bp.perm.owner)); 8743 if (isSystemApp(p.owner)) { 8744 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8745 // It's a built-in permission and no owner, take ownership now 8746 bp.packageSetting = pkgSetting; 8747 bp.perm = p; 8748 bp.uid = pkg.applicationInfo.uid; 8749 bp.sourcePackage = p.info.packageName; 8750 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8751 } else if (!currentOwnerIsSystem) { 8752 String msg = "New decl " + p.owner + " of permission " 8753 + p.info.name + " is system; overriding " + bp.sourcePackage; 8754 reportSettingsProblem(Log.WARN, msg); 8755 bp = null; 8756 } 8757 } 8758 } 8759 8760 if (bp == null) { 8761 bp = new BasePermission(p.info.name, p.info.packageName, 8762 BasePermission.TYPE_NORMAL); 8763 permissionMap.put(p.info.name, bp); 8764 } 8765 8766 if (bp.perm == null) { 8767 if (bp.sourcePackage == null 8768 || bp.sourcePackage.equals(p.info.packageName)) { 8769 BasePermission tree = findPermissionTreeLP(p.info.name); 8770 if (tree == null 8771 || tree.sourcePackage.equals(p.info.packageName)) { 8772 bp.packageSetting = pkgSetting; 8773 bp.perm = p; 8774 bp.uid = pkg.applicationInfo.uid; 8775 bp.sourcePackage = p.info.packageName; 8776 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8777 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8778 if (r == null) { 8779 r = new StringBuilder(256); 8780 } else { 8781 r.append(' '); 8782 } 8783 r.append(p.info.name); 8784 } 8785 } else { 8786 Slog.w(TAG, "Permission " + p.info.name + " from package " 8787 + p.info.packageName + " ignored: base tree " 8788 + tree.name + " is from package " 8789 + tree.sourcePackage); 8790 } 8791 } else { 8792 Slog.w(TAG, "Permission " + p.info.name + " from package " 8793 + p.info.packageName + " ignored: original from " 8794 + bp.sourcePackage); 8795 } 8796 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8797 if (r == null) { 8798 r = new StringBuilder(256); 8799 } else { 8800 r.append(' '); 8801 } 8802 r.append("DUP:"); 8803 r.append(p.info.name); 8804 } 8805 if (bp.perm == p) { 8806 bp.protectionLevel = p.info.protectionLevel; 8807 } 8808 } 8809 8810 if (r != null) { 8811 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8812 } 8813 8814 N = pkg.instrumentation.size(); 8815 r = null; 8816 for (i=0; i<N; i++) { 8817 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8818 a.info.packageName = pkg.applicationInfo.packageName; 8819 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8820 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8821 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8822 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8823 a.info.dataDir = pkg.applicationInfo.dataDir; 8824 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8825 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8826 8827 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8828 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8829 mInstrumentation.put(a.getComponentName(), a); 8830 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8831 if (r == null) { 8832 r = new StringBuilder(256); 8833 } else { 8834 r.append(' '); 8835 } 8836 r.append(a.info.name); 8837 } 8838 } 8839 if (r != null) { 8840 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8841 } 8842 8843 if (pkg.protectedBroadcasts != null) { 8844 N = pkg.protectedBroadcasts.size(); 8845 for (i=0; i<N; i++) { 8846 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8847 } 8848 } 8849 8850 pkgSetting.setTimeStamp(scanFileTime); 8851 8852 // Create idmap files for pairs of (packages, overlay packages). 8853 // Note: "android", ie framework-res.apk, is handled by native layers. 8854 if (pkg.mOverlayTarget != null) { 8855 // This is an overlay package. 8856 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8857 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8858 mOverlays.put(pkg.mOverlayTarget, 8859 new ArrayMap<String, PackageParser.Package>()); 8860 } 8861 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8862 map.put(pkg.packageName, pkg); 8863 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8864 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8865 createIdmapFailed = true; 8866 } 8867 } 8868 } else if (mOverlays.containsKey(pkg.packageName) && 8869 !pkg.packageName.equals("android")) { 8870 // This is a regular package, with one or more known overlay packages. 8871 createIdmapsForPackageLI(pkg); 8872 } 8873 } 8874 8875 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8876 8877 if (createIdmapFailed) { 8878 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8879 "scanPackageLI failed to createIdmap"); 8880 } 8881 return pkg; 8882 } 8883 8884 /** 8885 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8886 * is derived purely on the basis of the contents of {@code scanFile} and 8887 * {@code cpuAbiOverride}. 8888 * 8889 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8890 */ 8891 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8892 String cpuAbiOverride, boolean extractLibs) 8893 throws PackageManagerException { 8894 // TODO: We can probably be smarter about this stuff. For installed apps, 8895 // we can calculate this information at install time once and for all. For 8896 // system apps, we can probably assume that this information doesn't change 8897 // after the first boot scan. As things stand, we do lots of unnecessary work. 8898 8899 // Give ourselves some initial paths; we'll come back for another 8900 // pass once we've determined ABI below. 8901 setNativeLibraryPaths(pkg); 8902 8903 // We would never need to extract libs for forward-locked and external packages, 8904 // since the container service will do it for us. We shouldn't attempt to 8905 // extract libs from system app when it was not updated. 8906 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8907 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8908 extractLibs = false; 8909 } 8910 8911 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8912 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8913 8914 NativeLibraryHelper.Handle handle = null; 8915 try { 8916 handle = NativeLibraryHelper.Handle.create(pkg); 8917 // TODO(multiArch): This can be null for apps that didn't go through the 8918 // usual installation process. We can calculate it again, like we 8919 // do during install time. 8920 // 8921 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8922 // unnecessary. 8923 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8924 8925 // Null out the abis so that they can be recalculated. 8926 pkg.applicationInfo.primaryCpuAbi = null; 8927 pkg.applicationInfo.secondaryCpuAbi = null; 8928 if (isMultiArch(pkg.applicationInfo)) { 8929 // Warn if we've set an abiOverride for multi-lib packages.. 8930 // By definition, we need to copy both 32 and 64 bit libraries for 8931 // such packages. 8932 if (pkg.cpuAbiOverride != null 8933 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8934 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8935 } 8936 8937 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8938 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8939 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8940 if (extractLibs) { 8941 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8942 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8943 useIsaSpecificSubdirs); 8944 } else { 8945 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8946 } 8947 } 8948 8949 maybeThrowExceptionForMultiArchCopy( 8950 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8951 8952 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8953 if (extractLibs) { 8954 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8955 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8956 useIsaSpecificSubdirs); 8957 } else { 8958 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8959 } 8960 } 8961 8962 maybeThrowExceptionForMultiArchCopy( 8963 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8964 8965 if (abi64 >= 0) { 8966 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8967 } 8968 8969 if (abi32 >= 0) { 8970 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8971 if (abi64 >= 0) { 8972 if (pkg.use32bitAbi) { 8973 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8974 pkg.applicationInfo.primaryCpuAbi = abi; 8975 } else { 8976 pkg.applicationInfo.secondaryCpuAbi = abi; 8977 } 8978 } else { 8979 pkg.applicationInfo.primaryCpuAbi = abi; 8980 } 8981 } 8982 8983 } else { 8984 String[] abiList = (cpuAbiOverride != null) ? 8985 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8986 8987 // Enable gross and lame hacks for apps that are built with old 8988 // SDK tools. We must scan their APKs for renderscript bitcode and 8989 // not launch them if it's present. Don't bother checking on devices 8990 // that don't have 64 bit support. 8991 boolean needsRenderScriptOverride = false; 8992 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8993 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8994 abiList = Build.SUPPORTED_32_BIT_ABIS; 8995 needsRenderScriptOverride = true; 8996 } 8997 8998 final int copyRet; 8999 if (extractLibs) { 9000 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9001 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9002 } else { 9003 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9004 } 9005 9006 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9007 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9008 "Error unpackaging native libs for app, errorCode=" + copyRet); 9009 } 9010 9011 if (copyRet >= 0) { 9012 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9013 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9014 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9015 } else if (needsRenderScriptOverride) { 9016 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9017 } 9018 } 9019 } catch (IOException ioe) { 9020 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9021 } finally { 9022 IoUtils.closeQuietly(handle); 9023 } 9024 9025 // Now that we've calculated the ABIs and determined if it's an internal app, 9026 // we will go ahead and populate the nativeLibraryPath. 9027 setNativeLibraryPaths(pkg); 9028 } 9029 9030 /** 9031 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9032 * i.e, so that all packages can be run inside a single process if required. 9033 * 9034 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9035 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9036 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9037 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9038 * updating a package that belongs to a shared user. 9039 * 9040 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9041 * adds unnecessary complexity. 9042 */ 9043 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9044 PackageParser.Package scannedPackage, boolean bootComplete) { 9045 String requiredInstructionSet = null; 9046 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9047 requiredInstructionSet = VMRuntime.getInstructionSet( 9048 scannedPackage.applicationInfo.primaryCpuAbi); 9049 } 9050 9051 PackageSetting requirer = null; 9052 for (PackageSetting ps : packagesForUser) { 9053 // If packagesForUser contains scannedPackage, we skip it. This will happen 9054 // when scannedPackage is an update of an existing package. Without this check, 9055 // we will never be able to change the ABI of any package belonging to a shared 9056 // user, even if it's compatible with other packages. 9057 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9058 if (ps.primaryCpuAbiString == null) { 9059 continue; 9060 } 9061 9062 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9063 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9064 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9065 // this but there's not much we can do. 9066 String errorMessage = "Instruction set mismatch, " 9067 + ((requirer == null) ? "[caller]" : requirer) 9068 + " requires " + requiredInstructionSet + " whereas " + ps 9069 + " requires " + instructionSet; 9070 Slog.w(TAG, errorMessage); 9071 } 9072 9073 if (requiredInstructionSet == null) { 9074 requiredInstructionSet = instructionSet; 9075 requirer = ps; 9076 } 9077 } 9078 } 9079 9080 if (requiredInstructionSet != null) { 9081 String adjustedAbi; 9082 if (requirer != null) { 9083 // requirer != null implies that either scannedPackage was null or that scannedPackage 9084 // did not require an ABI, in which case we have to adjust scannedPackage to match 9085 // the ABI of the set (which is the same as requirer's ABI) 9086 adjustedAbi = requirer.primaryCpuAbiString; 9087 if (scannedPackage != null) { 9088 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9089 } 9090 } else { 9091 // requirer == null implies that we're updating all ABIs in the set to 9092 // match scannedPackage. 9093 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9094 } 9095 9096 for (PackageSetting ps : packagesForUser) { 9097 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9098 if (ps.primaryCpuAbiString != null) { 9099 continue; 9100 } 9101 9102 ps.primaryCpuAbiString = adjustedAbi; 9103 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9104 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9105 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9106 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9107 + " (requirer=" 9108 + (requirer == null ? "null" : requirer.pkg.packageName) 9109 + ", scannedPackage=" 9110 + (scannedPackage != null ? scannedPackage.packageName : "null") 9111 + ")"); 9112 try { 9113 mInstaller.rmdex(ps.codePathString, 9114 getDexCodeInstructionSet(getPreferredInstructionSet())); 9115 } catch (InstallerException ignored) { 9116 } 9117 } 9118 } 9119 } 9120 } 9121 } 9122 9123 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9124 synchronized (mPackages) { 9125 mResolverReplaced = true; 9126 // Set up information for custom user intent resolution activity. 9127 mResolveActivity.applicationInfo = pkg.applicationInfo; 9128 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9129 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9130 mResolveActivity.processName = pkg.applicationInfo.packageName; 9131 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9132 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9133 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9134 mResolveActivity.theme = 0; 9135 mResolveActivity.exported = true; 9136 mResolveActivity.enabled = true; 9137 mResolveInfo.activityInfo = mResolveActivity; 9138 mResolveInfo.priority = 0; 9139 mResolveInfo.preferredOrder = 0; 9140 mResolveInfo.match = 0; 9141 mResolveComponentName = mCustomResolverComponentName; 9142 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9143 mResolveComponentName); 9144 } 9145 } 9146 9147 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9148 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9149 9150 // Set up information for ephemeral installer activity 9151 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9152 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9153 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9154 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9155 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9156 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9157 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9158 mEphemeralInstallerActivity.theme = 0; 9159 mEphemeralInstallerActivity.exported = true; 9160 mEphemeralInstallerActivity.enabled = true; 9161 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9162 mEphemeralInstallerInfo.priority = 0; 9163 mEphemeralInstallerInfo.preferredOrder = 0; 9164 mEphemeralInstallerInfo.match = 0; 9165 9166 if (DEBUG_EPHEMERAL) { 9167 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9168 } 9169 } 9170 9171 private static String calculateBundledApkRoot(final String codePathString) { 9172 final File codePath = new File(codePathString); 9173 final File codeRoot; 9174 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9175 codeRoot = Environment.getRootDirectory(); 9176 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9177 codeRoot = Environment.getOemDirectory(); 9178 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9179 codeRoot = Environment.getVendorDirectory(); 9180 } else { 9181 // Unrecognized code path; take its top real segment as the apk root: 9182 // e.g. /something/app/blah.apk => /something 9183 try { 9184 File f = codePath.getCanonicalFile(); 9185 File parent = f.getParentFile(); // non-null because codePath is a file 9186 File tmp; 9187 while ((tmp = parent.getParentFile()) != null) { 9188 f = parent; 9189 parent = tmp; 9190 } 9191 codeRoot = f; 9192 Slog.w(TAG, "Unrecognized code path " 9193 + codePath + " - using " + codeRoot); 9194 } catch (IOException e) { 9195 // Can't canonicalize the code path -- shenanigans? 9196 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9197 return Environment.getRootDirectory().getPath(); 9198 } 9199 } 9200 return codeRoot.getPath(); 9201 } 9202 9203 /** 9204 * Derive and set the location of native libraries for the given package, 9205 * which varies depending on where and how the package was installed. 9206 */ 9207 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9208 final ApplicationInfo info = pkg.applicationInfo; 9209 final String codePath = pkg.codePath; 9210 final File codeFile = new File(codePath); 9211 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9212 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9213 9214 info.nativeLibraryRootDir = null; 9215 info.nativeLibraryRootRequiresIsa = false; 9216 info.nativeLibraryDir = null; 9217 info.secondaryNativeLibraryDir = null; 9218 9219 if (isApkFile(codeFile)) { 9220 // Monolithic install 9221 if (bundledApp) { 9222 // If "/system/lib64/apkname" exists, assume that is the per-package 9223 // native library directory to use; otherwise use "/system/lib/apkname". 9224 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9225 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9226 getPrimaryInstructionSet(info)); 9227 9228 // This is a bundled system app so choose the path based on the ABI. 9229 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9230 // is just the default path. 9231 final String apkName = deriveCodePathName(codePath); 9232 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9233 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9234 apkName).getAbsolutePath(); 9235 9236 if (info.secondaryCpuAbi != null) { 9237 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9238 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9239 secondaryLibDir, apkName).getAbsolutePath(); 9240 } 9241 } else if (asecApp) { 9242 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9243 .getAbsolutePath(); 9244 } else { 9245 final String apkName = deriveCodePathName(codePath); 9246 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9247 .getAbsolutePath(); 9248 } 9249 9250 info.nativeLibraryRootRequiresIsa = false; 9251 info.nativeLibraryDir = info.nativeLibraryRootDir; 9252 } else { 9253 // Cluster install 9254 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9255 info.nativeLibraryRootRequiresIsa = true; 9256 9257 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9258 getPrimaryInstructionSet(info)).getAbsolutePath(); 9259 9260 if (info.secondaryCpuAbi != null) { 9261 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9262 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9263 } 9264 } 9265 } 9266 9267 /** 9268 * Calculate the abis and roots for a bundled app. These can uniquely 9269 * be determined from the contents of the system partition, i.e whether 9270 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9271 * of this information, and instead assume that the system was built 9272 * sensibly. 9273 */ 9274 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9275 PackageSetting pkgSetting) { 9276 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9277 9278 // If "/system/lib64/apkname" exists, assume that is the per-package 9279 // native library directory to use; otherwise use "/system/lib/apkname". 9280 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9281 setBundledAppAbi(pkg, apkRoot, apkName); 9282 // pkgSetting might be null during rescan following uninstall of updates 9283 // to a bundled app, so accommodate that possibility. The settings in 9284 // that case will be established later from the parsed package. 9285 // 9286 // If the settings aren't null, sync them up with what we've just derived. 9287 // note that apkRoot isn't stored in the package settings. 9288 if (pkgSetting != null) { 9289 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9290 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9291 } 9292 } 9293 9294 /** 9295 * Deduces the ABI of a bundled app and sets the relevant fields on the 9296 * parsed pkg object. 9297 * 9298 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9299 * under which system libraries are installed. 9300 * @param apkName the name of the installed package. 9301 */ 9302 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9303 final File codeFile = new File(pkg.codePath); 9304 9305 final boolean has64BitLibs; 9306 final boolean has32BitLibs; 9307 if (isApkFile(codeFile)) { 9308 // Monolithic install 9309 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9310 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9311 } else { 9312 // Cluster install 9313 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9314 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9315 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9316 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9317 has64BitLibs = (new File(rootDir, isa)).exists(); 9318 } else { 9319 has64BitLibs = false; 9320 } 9321 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9322 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9323 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9324 has32BitLibs = (new File(rootDir, isa)).exists(); 9325 } else { 9326 has32BitLibs = false; 9327 } 9328 } 9329 9330 if (has64BitLibs && !has32BitLibs) { 9331 // The package has 64 bit libs, but not 32 bit libs. Its primary 9332 // ABI should be 64 bit. We can safely assume here that the bundled 9333 // native libraries correspond to the most preferred ABI in the list. 9334 9335 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9336 pkg.applicationInfo.secondaryCpuAbi = null; 9337 } else if (has32BitLibs && !has64BitLibs) { 9338 // The package has 32 bit libs but not 64 bit libs. Its primary 9339 // ABI should be 32 bit. 9340 9341 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9342 pkg.applicationInfo.secondaryCpuAbi = null; 9343 } else if (has32BitLibs && has64BitLibs) { 9344 // The application has both 64 and 32 bit bundled libraries. We check 9345 // here that the app declares multiArch support, and warn if it doesn't. 9346 // 9347 // We will be lenient here and record both ABIs. The primary will be the 9348 // ABI that's higher on the list, i.e, a device that's configured to prefer 9349 // 64 bit apps will see a 64 bit primary ABI, 9350 9351 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9352 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9353 } 9354 9355 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9356 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9357 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9358 } else { 9359 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9360 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9361 } 9362 } else { 9363 pkg.applicationInfo.primaryCpuAbi = null; 9364 pkg.applicationInfo.secondaryCpuAbi = null; 9365 } 9366 } 9367 9368 private void killApplication(String pkgName, int appId, String reason) { 9369 // Request the ActivityManager to kill the process(only for existing packages) 9370 // so that we do not end up in a confused state while the user is still using the older 9371 // version of the application while the new one gets installed. 9372 final long token = Binder.clearCallingIdentity(); 9373 try { 9374 IActivityManager am = ActivityManagerNative.getDefault(); 9375 if (am != null) { 9376 try { 9377 am.killApplicationWithAppId(pkgName, appId, reason); 9378 } catch (RemoteException e) { 9379 } 9380 } 9381 } finally { 9382 Binder.restoreCallingIdentity(token); 9383 } 9384 } 9385 9386 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9387 // Remove the parent package setting 9388 PackageSetting ps = (PackageSetting) pkg.mExtras; 9389 if (ps != null) { 9390 removePackageLI(ps, chatty); 9391 } 9392 // Remove the child package setting 9393 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9394 for (int i = 0; i < childCount; i++) { 9395 PackageParser.Package childPkg = pkg.childPackages.get(i); 9396 ps = (PackageSetting) childPkg.mExtras; 9397 if (ps != null) { 9398 removePackageLI(ps, chatty); 9399 } 9400 } 9401 } 9402 9403 void removePackageLI(PackageSetting ps, boolean chatty) { 9404 if (DEBUG_INSTALL) { 9405 if (chatty) 9406 Log.d(TAG, "Removing package " + ps.name); 9407 } 9408 9409 // writer 9410 synchronized (mPackages) { 9411 mPackages.remove(ps.name); 9412 final PackageParser.Package pkg = ps.pkg; 9413 if (pkg != null) { 9414 cleanPackageDataStructuresLILPw(pkg, chatty); 9415 } 9416 } 9417 } 9418 9419 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9420 if (DEBUG_INSTALL) { 9421 if (chatty) 9422 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9423 } 9424 9425 // writer 9426 synchronized (mPackages) { 9427 // Remove the parent package 9428 mPackages.remove(pkg.applicationInfo.packageName); 9429 cleanPackageDataStructuresLILPw(pkg, chatty); 9430 9431 // Remove the child packages 9432 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9433 for (int i = 0; i < childCount; i++) { 9434 PackageParser.Package childPkg = pkg.childPackages.get(i); 9435 mPackages.remove(childPkg.applicationInfo.packageName); 9436 cleanPackageDataStructuresLILPw(childPkg, chatty); 9437 } 9438 } 9439 } 9440 9441 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9442 int N = pkg.providers.size(); 9443 StringBuilder r = null; 9444 int i; 9445 for (i=0; i<N; i++) { 9446 PackageParser.Provider p = pkg.providers.get(i); 9447 mProviders.removeProvider(p); 9448 if (p.info.authority == null) { 9449 9450 /* There was another ContentProvider with this authority when 9451 * this app was installed so this authority is null, 9452 * Ignore it as we don't have to unregister the provider. 9453 */ 9454 continue; 9455 } 9456 String names[] = p.info.authority.split(";"); 9457 for (int j = 0; j < names.length; j++) { 9458 if (mProvidersByAuthority.get(names[j]) == p) { 9459 mProvidersByAuthority.remove(names[j]); 9460 if (DEBUG_REMOVE) { 9461 if (chatty) 9462 Log.d(TAG, "Unregistered content provider: " + names[j] 9463 + ", className = " + p.info.name + ", isSyncable = " 9464 + p.info.isSyncable); 9465 } 9466 } 9467 } 9468 if (DEBUG_REMOVE && chatty) { 9469 if (r == null) { 9470 r = new StringBuilder(256); 9471 } else { 9472 r.append(' '); 9473 } 9474 r.append(p.info.name); 9475 } 9476 } 9477 if (r != null) { 9478 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9479 } 9480 9481 N = pkg.services.size(); 9482 r = null; 9483 for (i=0; i<N; i++) { 9484 PackageParser.Service s = pkg.services.get(i); 9485 mServices.removeService(s); 9486 if (chatty) { 9487 if (r == null) { 9488 r = new StringBuilder(256); 9489 } else { 9490 r.append(' '); 9491 } 9492 r.append(s.info.name); 9493 } 9494 } 9495 if (r != null) { 9496 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9497 } 9498 9499 N = pkg.receivers.size(); 9500 r = null; 9501 for (i=0; i<N; i++) { 9502 PackageParser.Activity a = pkg.receivers.get(i); 9503 mReceivers.removeActivity(a, "receiver"); 9504 if (DEBUG_REMOVE && chatty) { 9505 if (r == null) { 9506 r = new StringBuilder(256); 9507 } else { 9508 r.append(' '); 9509 } 9510 r.append(a.info.name); 9511 } 9512 } 9513 if (r != null) { 9514 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9515 } 9516 9517 N = pkg.activities.size(); 9518 r = null; 9519 for (i=0; i<N; i++) { 9520 PackageParser.Activity a = pkg.activities.get(i); 9521 mActivities.removeActivity(a, "activity"); 9522 if (DEBUG_REMOVE && chatty) { 9523 if (r == null) { 9524 r = new StringBuilder(256); 9525 } else { 9526 r.append(' '); 9527 } 9528 r.append(a.info.name); 9529 } 9530 } 9531 if (r != null) { 9532 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9533 } 9534 9535 N = pkg.permissions.size(); 9536 r = null; 9537 for (i=0; i<N; i++) { 9538 PackageParser.Permission p = pkg.permissions.get(i); 9539 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9540 if (bp == null) { 9541 bp = mSettings.mPermissionTrees.get(p.info.name); 9542 } 9543 if (bp != null && bp.perm == p) { 9544 bp.perm = null; 9545 if (DEBUG_REMOVE && chatty) { 9546 if (r == null) { 9547 r = new StringBuilder(256); 9548 } else { 9549 r.append(' '); 9550 } 9551 r.append(p.info.name); 9552 } 9553 } 9554 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9555 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9556 if (appOpPkgs != null) { 9557 appOpPkgs.remove(pkg.packageName); 9558 } 9559 } 9560 } 9561 if (r != null) { 9562 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9563 } 9564 9565 N = pkg.requestedPermissions.size(); 9566 r = null; 9567 for (i=0; i<N; i++) { 9568 String perm = pkg.requestedPermissions.get(i); 9569 BasePermission bp = mSettings.mPermissions.get(perm); 9570 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9571 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9572 if (appOpPkgs != null) { 9573 appOpPkgs.remove(pkg.packageName); 9574 if (appOpPkgs.isEmpty()) { 9575 mAppOpPermissionPackages.remove(perm); 9576 } 9577 } 9578 } 9579 } 9580 if (r != null) { 9581 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9582 } 9583 9584 N = pkg.instrumentation.size(); 9585 r = null; 9586 for (i=0; i<N; i++) { 9587 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9588 mInstrumentation.remove(a.getComponentName()); 9589 if (DEBUG_REMOVE && chatty) { 9590 if (r == null) { 9591 r = new StringBuilder(256); 9592 } else { 9593 r.append(' '); 9594 } 9595 r.append(a.info.name); 9596 } 9597 } 9598 if (r != null) { 9599 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9600 } 9601 9602 r = null; 9603 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9604 // Only system apps can hold shared libraries. 9605 if (pkg.libraryNames != null) { 9606 for (i=0; i<pkg.libraryNames.size(); i++) { 9607 String name = pkg.libraryNames.get(i); 9608 SharedLibraryEntry cur = mSharedLibraries.get(name); 9609 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9610 mSharedLibraries.remove(name); 9611 if (DEBUG_REMOVE && chatty) { 9612 if (r == null) { 9613 r = new StringBuilder(256); 9614 } else { 9615 r.append(' '); 9616 } 9617 r.append(name); 9618 } 9619 } 9620 } 9621 } 9622 } 9623 if (r != null) { 9624 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9625 } 9626 } 9627 9628 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9629 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9630 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9631 return true; 9632 } 9633 } 9634 return false; 9635 } 9636 9637 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9638 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9639 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9640 9641 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9642 // Update the parent permissions 9643 updatePermissionsLPw(pkg.packageName, pkg, flags); 9644 // Update the child permissions 9645 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9646 for (int i = 0; i < childCount; i++) { 9647 PackageParser.Package childPkg = pkg.childPackages.get(i); 9648 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9649 } 9650 } 9651 9652 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9653 int flags) { 9654 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9655 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9656 } 9657 9658 private void updatePermissionsLPw(String changingPkg, 9659 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9660 // Make sure there are no dangling permission trees. 9661 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9662 while (it.hasNext()) { 9663 final BasePermission bp = it.next(); 9664 if (bp.packageSetting == null) { 9665 // We may not yet have parsed the package, so just see if 9666 // we still know about its settings. 9667 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9668 } 9669 if (bp.packageSetting == null) { 9670 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9671 + " from package " + bp.sourcePackage); 9672 it.remove(); 9673 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9674 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9675 Slog.i(TAG, "Removing old permission tree: " + bp.name 9676 + " from package " + bp.sourcePackage); 9677 flags |= UPDATE_PERMISSIONS_ALL; 9678 it.remove(); 9679 } 9680 } 9681 } 9682 9683 // Make sure all dynamic permissions have been assigned to a package, 9684 // and make sure there are no dangling permissions. 9685 it = mSettings.mPermissions.values().iterator(); 9686 while (it.hasNext()) { 9687 final BasePermission bp = it.next(); 9688 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9689 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9690 + bp.name + " pkg=" + bp.sourcePackage 9691 + " info=" + bp.pendingInfo); 9692 if (bp.packageSetting == null && bp.pendingInfo != null) { 9693 final BasePermission tree = findPermissionTreeLP(bp.name); 9694 if (tree != null && tree.perm != null) { 9695 bp.packageSetting = tree.packageSetting; 9696 bp.perm = new PackageParser.Permission(tree.perm.owner, 9697 new PermissionInfo(bp.pendingInfo)); 9698 bp.perm.info.packageName = tree.perm.info.packageName; 9699 bp.perm.info.name = bp.name; 9700 bp.uid = tree.uid; 9701 } 9702 } 9703 } 9704 if (bp.packageSetting == null) { 9705 // We may not yet have parsed the package, so just see if 9706 // we still know about its settings. 9707 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9708 } 9709 if (bp.packageSetting == null) { 9710 Slog.w(TAG, "Removing dangling permission: " + bp.name 9711 + " from package " + bp.sourcePackage); 9712 it.remove(); 9713 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9714 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9715 Slog.i(TAG, "Removing old permission: " + bp.name 9716 + " from package " + bp.sourcePackage); 9717 flags |= UPDATE_PERMISSIONS_ALL; 9718 it.remove(); 9719 } 9720 } 9721 } 9722 9723 // Now update the permissions for all packages, in particular 9724 // replace the granted permissions of the system packages. 9725 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9726 for (PackageParser.Package pkg : mPackages.values()) { 9727 if (pkg != pkgInfo) { 9728 // Only replace for packages on requested volume 9729 final String volumeUuid = getVolumeUuidForPackage(pkg); 9730 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9731 && Objects.equals(replaceVolumeUuid, volumeUuid); 9732 grantPermissionsLPw(pkg, replace, changingPkg); 9733 } 9734 } 9735 } 9736 9737 if (pkgInfo != null) { 9738 // Only replace for packages on requested volume 9739 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9740 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9741 && Objects.equals(replaceVolumeUuid, volumeUuid); 9742 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9743 } 9744 } 9745 9746 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9747 String packageOfInterest) { 9748 // IMPORTANT: There are two types of permissions: install and runtime. 9749 // Install time permissions are granted when the app is installed to 9750 // all device users and users added in the future. Runtime permissions 9751 // are granted at runtime explicitly to specific users. Normal and signature 9752 // protected permissions are install time permissions. Dangerous permissions 9753 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9754 // otherwise they are runtime permissions. This function does not manage 9755 // runtime permissions except for the case an app targeting Lollipop MR1 9756 // being upgraded to target a newer SDK, in which case dangerous permissions 9757 // are transformed from install time to runtime ones. 9758 9759 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9760 if (ps == null) { 9761 return; 9762 } 9763 9764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9765 9766 PermissionsState permissionsState = ps.getPermissionsState(); 9767 PermissionsState origPermissions = permissionsState; 9768 9769 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9770 9771 boolean runtimePermissionsRevoked = false; 9772 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9773 9774 boolean changedInstallPermission = false; 9775 9776 if (replace) { 9777 ps.installPermissionsFixed = false; 9778 if (!ps.isSharedUser()) { 9779 origPermissions = new PermissionsState(permissionsState); 9780 permissionsState.reset(); 9781 } else { 9782 // We need to know only about runtime permission changes since the 9783 // calling code always writes the install permissions state but 9784 // the runtime ones are written only if changed. The only cases of 9785 // changed runtime permissions here are promotion of an install to 9786 // runtime and revocation of a runtime from a shared user. 9787 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9788 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9789 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9790 runtimePermissionsRevoked = true; 9791 } 9792 } 9793 } 9794 9795 permissionsState.setGlobalGids(mGlobalGids); 9796 9797 final int N = pkg.requestedPermissions.size(); 9798 for (int i=0; i<N; i++) { 9799 final String name = pkg.requestedPermissions.get(i); 9800 final BasePermission bp = mSettings.mPermissions.get(name); 9801 9802 if (DEBUG_INSTALL) { 9803 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9804 } 9805 9806 if (bp == null || bp.packageSetting == null) { 9807 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9808 Slog.w(TAG, "Unknown permission " + name 9809 + " in package " + pkg.packageName); 9810 } 9811 continue; 9812 } 9813 9814 final String perm = bp.name; 9815 boolean allowedSig = false; 9816 int grant = GRANT_DENIED; 9817 9818 // Keep track of app op permissions. 9819 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9820 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9821 if (pkgs == null) { 9822 pkgs = new ArraySet<>(); 9823 mAppOpPermissionPackages.put(bp.name, pkgs); 9824 } 9825 pkgs.add(pkg.packageName); 9826 } 9827 9828 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9829 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9830 >= Build.VERSION_CODES.M; 9831 switch (level) { 9832 case PermissionInfo.PROTECTION_NORMAL: { 9833 // For all apps normal permissions are install time ones. 9834 grant = GRANT_INSTALL; 9835 } break; 9836 9837 case PermissionInfo.PROTECTION_DANGEROUS: { 9838 // If a permission review is required for legacy apps we represent 9839 // their permissions as always granted runtime ones since we need 9840 // to keep the review required permission flag per user while an 9841 // install permission's state is shared across all users. 9842 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9843 // For legacy apps dangerous permissions are install time ones. 9844 grant = GRANT_INSTALL; 9845 } else if (origPermissions.hasInstallPermission(bp.name)) { 9846 // For legacy apps that became modern, install becomes runtime. 9847 grant = GRANT_UPGRADE; 9848 } else if (mPromoteSystemApps 9849 && isSystemApp(ps) 9850 && mExistingSystemPackages.contains(ps.name)) { 9851 // For legacy system apps, install becomes runtime. 9852 // We cannot check hasInstallPermission() for system apps since those 9853 // permissions were granted implicitly and not persisted pre-M. 9854 grant = GRANT_UPGRADE; 9855 } else { 9856 // For modern apps keep runtime permissions unchanged. 9857 grant = GRANT_RUNTIME; 9858 } 9859 } break; 9860 9861 case PermissionInfo.PROTECTION_SIGNATURE: { 9862 // For all apps signature permissions are install time ones. 9863 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9864 if (allowedSig) { 9865 grant = GRANT_INSTALL; 9866 } 9867 } break; 9868 } 9869 9870 if (DEBUG_INSTALL) { 9871 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9872 } 9873 9874 if (grant != GRANT_DENIED) { 9875 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9876 // If this is an existing, non-system package, then 9877 // we can't add any new permissions to it. 9878 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9879 // Except... if this is a permission that was added 9880 // to the platform (note: need to only do this when 9881 // updating the platform). 9882 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9883 grant = GRANT_DENIED; 9884 } 9885 } 9886 } 9887 9888 switch (grant) { 9889 case GRANT_INSTALL: { 9890 // Revoke this as runtime permission to handle the case of 9891 // a runtime permission being downgraded to an install one. 9892 // Also in permission review mode we keep dangerous permissions 9893 // for legacy apps 9894 for (int userId : UserManagerService.getInstance().getUserIds()) { 9895 if (origPermissions.getRuntimePermissionState( 9896 bp.name, userId) != null) { 9897 // Revoke the runtime permission and clear the flags. 9898 origPermissions.revokeRuntimePermission(bp, userId); 9899 origPermissions.updatePermissionFlags(bp, userId, 9900 PackageManager.MASK_PERMISSION_FLAGS, 0); 9901 // If we revoked a permission permission, we have to write. 9902 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9903 changedRuntimePermissionUserIds, userId); 9904 } 9905 } 9906 // Grant an install permission. 9907 if (permissionsState.grantInstallPermission(bp) != 9908 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9909 changedInstallPermission = true; 9910 } 9911 } break; 9912 9913 case GRANT_RUNTIME: { 9914 // Grant previously granted runtime permissions. 9915 for (int userId : UserManagerService.getInstance().getUserIds()) { 9916 PermissionState permissionState = origPermissions 9917 .getRuntimePermissionState(bp.name, userId); 9918 int flags = permissionState != null 9919 ? permissionState.getFlags() : 0; 9920 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9921 if (permissionsState.grantRuntimePermission(bp, userId) == 9922 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9923 // If we cannot put the permission as it was, we have to write. 9924 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9925 changedRuntimePermissionUserIds, userId); 9926 } 9927 // If the app supports runtime permissions no need for a review. 9928 if (Build.PERMISSIONS_REVIEW_REQUIRED 9929 && appSupportsRuntimePermissions 9930 && (flags & PackageManager 9931 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9932 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9933 // Since we changed the flags, we have to write. 9934 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9935 changedRuntimePermissionUserIds, userId); 9936 } 9937 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9938 && !appSupportsRuntimePermissions) { 9939 // For legacy apps that need a permission review, every new 9940 // runtime permission is granted but it is pending a review. 9941 // We also need to review only platform defined runtime 9942 // permissions as these are the only ones the platform knows 9943 // how to disable the API to simulate revocation as legacy 9944 // apps don't expect to run with revoked permissions. 9945 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9946 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9947 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9948 // We changed the flags, hence have to write. 9949 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9950 changedRuntimePermissionUserIds, userId); 9951 } 9952 } 9953 if (permissionsState.grantRuntimePermission(bp, userId) 9954 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9955 // We changed the permission, hence have to write. 9956 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9957 changedRuntimePermissionUserIds, userId); 9958 } 9959 } 9960 // Propagate the permission flags. 9961 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9962 } 9963 } break; 9964 9965 case GRANT_UPGRADE: { 9966 // Grant runtime permissions for a previously held install permission. 9967 PermissionState permissionState = origPermissions 9968 .getInstallPermissionState(bp.name); 9969 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9970 9971 if (origPermissions.revokeInstallPermission(bp) 9972 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9973 // We will be transferring the permission flags, so clear them. 9974 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9975 PackageManager.MASK_PERMISSION_FLAGS, 0); 9976 changedInstallPermission = true; 9977 } 9978 9979 // If the permission is not to be promoted to runtime we ignore it and 9980 // also its other flags as they are not applicable to install permissions. 9981 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9982 for (int userId : currentUserIds) { 9983 if (permissionsState.grantRuntimePermission(bp, userId) != 9984 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9985 // Transfer the permission flags. 9986 permissionsState.updatePermissionFlags(bp, userId, 9987 flags, flags); 9988 // If we granted the permission, we have to write. 9989 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9990 changedRuntimePermissionUserIds, userId); 9991 } 9992 } 9993 } 9994 } break; 9995 9996 default: { 9997 if (packageOfInterest == null 9998 || packageOfInterest.equals(pkg.packageName)) { 9999 Slog.w(TAG, "Not granting permission " + perm 10000 + " to package " + pkg.packageName 10001 + " because it was previously installed without"); 10002 } 10003 } break; 10004 } 10005 } else { 10006 if (permissionsState.revokeInstallPermission(bp) != 10007 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10008 // Also drop the permission flags. 10009 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10010 PackageManager.MASK_PERMISSION_FLAGS, 0); 10011 changedInstallPermission = true; 10012 Slog.i(TAG, "Un-granting permission " + perm 10013 + " from package " + pkg.packageName 10014 + " (protectionLevel=" + bp.protectionLevel 10015 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10016 + ")"); 10017 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10018 // Don't print warning for app op permissions, since it is fine for them 10019 // not to be granted, there is a UI for the user to decide. 10020 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10021 Slog.w(TAG, "Not granting permission " + perm 10022 + " to package " + pkg.packageName 10023 + " (protectionLevel=" + bp.protectionLevel 10024 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10025 + ")"); 10026 } 10027 } 10028 } 10029 } 10030 10031 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10032 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10033 // This is the first that we have heard about this package, so the 10034 // permissions we have now selected are fixed until explicitly 10035 // changed. 10036 ps.installPermissionsFixed = true; 10037 } 10038 10039 // Persist the runtime permissions state for users with changes. If permissions 10040 // were revoked because no app in the shared user declares them we have to 10041 // write synchronously to avoid losing runtime permissions state. 10042 for (int userId : changedRuntimePermissionUserIds) { 10043 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10044 } 10045 10046 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10047 } 10048 10049 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10050 boolean allowed = false; 10051 final int NP = PackageParser.NEW_PERMISSIONS.length; 10052 for (int ip=0; ip<NP; ip++) { 10053 final PackageParser.NewPermissionInfo npi 10054 = PackageParser.NEW_PERMISSIONS[ip]; 10055 if (npi.name.equals(perm) 10056 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10057 allowed = true; 10058 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10059 + pkg.packageName); 10060 break; 10061 } 10062 } 10063 return allowed; 10064 } 10065 10066 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10067 BasePermission bp, PermissionsState origPermissions) { 10068 boolean allowed; 10069 allowed = (compareSignatures( 10070 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10071 == PackageManager.SIGNATURE_MATCH) 10072 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10073 == PackageManager.SIGNATURE_MATCH); 10074 if (!allowed && (bp.protectionLevel 10075 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10076 if (isSystemApp(pkg)) { 10077 // For updated system applications, a system permission 10078 // is granted only if it had been defined by the original application. 10079 if (pkg.isUpdatedSystemApp()) { 10080 final PackageSetting sysPs = mSettings 10081 .getDisabledSystemPkgLPr(pkg.packageName); 10082 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10083 // If the original was granted this permission, we take 10084 // that grant decision as read and propagate it to the 10085 // update. 10086 if (sysPs.isPrivileged()) { 10087 allowed = true; 10088 } 10089 } else { 10090 // The system apk may have been updated with an older 10091 // version of the one on the data partition, but which 10092 // granted a new system permission that it didn't have 10093 // before. In this case we do want to allow the app to 10094 // now get the new permission if the ancestral apk is 10095 // privileged to get it. 10096 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10097 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10098 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10099 allowed = true; 10100 break; 10101 } 10102 } 10103 } 10104 // Also if a privileged parent package on the system image or any of 10105 // its children requested a privileged permission, the updated child 10106 // packages can also get the permission. 10107 if (pkg.parentPackage != null) { 10108 final PackageSetting disabledSysParentPs = mSettings 10109 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10110 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10111 && disabledSysParentPs.isPrivileged()) { 10112 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10113 allowed = true; 10114 } else if (disabledSysParentPs.pkg.childPackages != null) { 10115 final int count = disabledSysParentPs.pkg.childPackages.size(); 10116 for (int i = 0; i < count; i++) { 10117 PackageParser.Package disabledSysChildPkg = 10118 disabledSysParentPs.pkg.childPackages.get(i); 10119 if (isPackageRequestingPermission(disabledSysChildPkg, 10120 perm)) { 10121 allowed = true; 10122 break; 10123 } 10124 } 10125 } 10126 } 10127 } 10128 } 10129 } else { 10130 allowed = isPrivilegedApp(pkg); 10131 } 10132 } 10133 } 10134 if (!allowed) { 10135 if (!allowed && (bp.protectionLevel 10136 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10137 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10138 // If this was a previously normal/dangerous permission that got moved 10139 // to a system permission as part of the runtime permission redesign, then 10140 // we still want to blindly grant it to old apps. 10141 allowed = true; 10142 } 10143 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10144 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10145 // If this permission is to be granted to the system installer and 10146 // this app is an installer, then it gets the permission. 10147 allowed = true; 10148 } 10149 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10150 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10151 // If this permission is to be granted to the system verifier and 10152 // this app is a verifier, then it gets the permission. 10153 allowed = true; 10154 } 10155 if (!allowed && (bp.protectionLevel 10156 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10157 && isSystemApp(pkg)) { 10158 // Any pre-installed system app is allowed to get this permission. 10159 allowed = true; 10160 } 10161 if (!allowed && (bp.protectionLevel 10162 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10163 // For development permissions, a development permission 10164 // is granted only if it was already granted. 10165 allowed = origPermissions.hasInstallPermission(perm); 10166 } 10167 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10168 && pkg.packageName.equals(mSetupWizardPackage)) { 10169 // If this permission is to be granted to the system setup wizard and 10170 // this app is a setup wizard, then it gets the permission. 10171 allowed = true; 10172 } 10173 } 10174 return allowed; 10175 } 10176 10177 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10178 final int permCount = pkg.requestedPermissions.size(); 10179 for (int j = 0; j < permCount; j++) { 10180 String requestedPermission = pkg.requestedPermissions.get(j); 10181 if (permission.equals(requestedPermission)) { 10182 return true; 10183 } 10184 } 10185 return false; 10186 } 10187 10188 final class ActivityIntentResolver 10189 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10190 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10191 boolean defaultOnly, int userId) { 10192 if (!sUserManager.exists(userId)) return null; 10193 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10194 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10195 } 10196 10197 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10198 int userId) { 10199 if (!sUserManager.exists(userId)) return null; 10200 mFlags = flags; 10201 return super.queryIntent(intent, resolvedType, 10202 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10203 } 10204 10205 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10206 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10207 if (!sUserManager.exists(userId)) return null; 10208 if (packageActivities == null) { 10209 return null; 10210 } 10211 mFlags = flags; 10212 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10213 final int N = packageActivities.size(); 10214 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10215 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10216 10217 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10218 for (int i = 0; i < N; ++i) { 10219 intentFilters = packageActivities.get(i).intents; 10220 if (intentFilters != null && intentFilters.size() > 0) { 10221 PackageParser.ActivityIntentInfo[] array = 10222 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10223 intentFilters.toArray(array); 10224 listCut.add(array); 10225 } 10226 } 10227 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10228 } 10229 10230 /** 10231 * Finds a privileged activity that matches the specified activity names. 10232 */ 10233 private PackageParser.Activity findMatchingActivity( 10234 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10235 for (PackageParser.Activity sysActivity : activityList) { 10236 if (sysActivity.info.name.equals(activityInfo.name)) { 10237 return sysActivity; 10238 } 10239 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10240 return sysActivity; 10241 } 10242 if (sysActivity.info.targetActivity != null) { 10243 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10244 return sysActivity; 10245 } 10246 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10247 return sysActivity; 10248 } 10249 } 10250 } 10251 return null; 10252 } 10253 10254 public class IterGenerator<E> { 10255 public Iterator<E> generate(ActivityIntentInfo info) { 10256 return null; 10257 } 10258 } 10259 10260 public class ActionIterGenerator extends IterGenerator<String> { 10261 @Override 10262 public Iterator<String> generate(ActivityIntentInfo info) { 10263 return info.actionsIterator(); 10264 } 10265 } 10266 10267 public class CategoriesIterGenerator extends IterGenerator<String> { 10268 @Override 10269 public Iterator<String> generate(ActivityIntentInfo info) { 10270 return info.categoriesIterator(); 10271 } 10272 } 10273 10274 public class SchemesIterGenerator extends IterGenerator<String> { 10275 @Override 10276 public Iterator<String> generate(ActivityIntentInfo info) { 10277 return info.schemesIterator(); 10278 } 10279 } 10280 10281 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10282 @Override 10283 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10284 return info.authoritiesIterator(); 10285 } 10286 } 10287 10288 /** 10289 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10290 * MODIFIED. Do not pass in a list that should not be changed. 10291 */ 10292 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10293 IterGenerator<T> generator, Iterator<T> searchIterator) { 10294 // loop through the set of actions; every one must be found in the intent filter 10295 while (searchIterator.hasNext()) { 10296 // we must have at least one filter in the list to consider a match 10297 if (intentList.size() == 0) { 10298 break; 10299 } 10300 10301 final T searchAction = searchIterator.next(); 10302 10303 // loop through the set of intent filters 10304 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10305 while (intentIter.hasNext()) { 10306 final ActivityIntentInfo intentInfo = intentIter.next(); 10307 boolean selectionFound = false; 10308 10309 // loop through the intent filter's selection criteria; at least one 10310 // of them must match the searched criteria 10311 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10312 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10313 final T intentSelection = intentSelectionIter.next(); 10314 if (intentSelection != null && intentSelection.equals(searchAction)) { 10315 selectionFound = true; 10316 break; 10317 } 10318 } 10319 10320 // the selection criteria wasn't found in this filter's set; this filter 10321 // is not a potential match 10322 if (!selectionFound) { 10323 intentIter.remove(); 10324 } 10325 } 10326 } 10327 } 10328 10329 private boolean isProtectedAction(ActivityIntentInfo filter) { 10330 final Iterator<String> actionsIter = filter.actionsIterator(); 10331 while (actionsIter != null && actionsIter.hasNext()) { 10332 final String filterAction = actionsIter.next(); 10333 if (PROTECTED_ACTIONS.contains(filterAction)) { 10334 return true; 10335 } 10336 } 10337 return false; 10338 } 10339 10340 /** 10341 * Adjusts the priority of the given intent filter according to policy. 10342 * <p> 10343 * <ul> 10344 * <li>The priority for non privileged applications is capped to '0'</li> 10345 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10346 * <li>The priority for unbundled updates to privileged applications is capped to the 10347 * priority defined on the system partition</li> 10348 * </ul> 10349 * <p> 10350 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10351 * allowed to obtain any priority on any action. 10352 */ 10353 private void adjustPriority( 10354 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10355 // nothing to do; priority is fine as-is 10356 if (intent.getPriority() <= 0) { 10357 return; 10358 } 10359 10360 final ActivityInfo activityInfo = intent.activity.info; 10361 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10362 10363 final boolean privilegedApp = 10364 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10365 if (!privilegedApp) { 10366 // non-privileged applications can never define a priority >0 10367 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10368 + " package: " + applicationInfo.packageName 10369 + " activity: " + intent.activity.className 10370 + " origPrio: " + intent.getPriority()); 10371 intent.setPriority(0); 10372 return; 10373 } 10374 10375 if (systemActivities == null) { 10376 // the system package is not disabled; we're parsing the system partition 10377 if (isProtectedAction(intent)) { 10378 if (mDeferProtectedFilters) { 10379 // We can't deal with these just yet. No component should ever obtain a 10380 // >0 priority for a protected actions, with ONE exception -- the setup 10381 // wizard. The setup wizard, however, cannot be known until we're able to 10382 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10383 // until all intent filters have been processed. Chicken, meet egg. 10384 // Let the filter temporarily have a high priority and rectify the 10385 // priorities after all system packages have been scanned. 10386 mProtectedFilters.add(intent); 10387 if (DEBUG_FILTERS) { 10388 Slog.i(TAG, "Protected action; save for later;" 10389 + " package: " + applicationInfo.packageName 10390 + " activity: " + intent.activity.className 10391 + " origPrio: " + intent.getPriority()); 10392 } 10393 return; 10394 } else { 10395 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10396 Slog.i(TAG, "No setup wizard;" 10397 + " All protected intents capped to priority 0"); 10398 } 10399 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10400 if (DEBUG_FILTERS) { 10401 Slog.i(TAG, "Found setup wizard;" 10402 + " allow priority " + intent.getPriority() + ";" 10403 + " package: " + intent.activity.info.packageName 10404 + " activity: " + intent.activity.className 10405 + " priority: " + intent.getPriority()); 10406 } 10407 // setup wizard gets whatever it wants 10408 return; 10409 } 10410 Slog.w(TAG, "Protected action; cap priority to 0;" 10411 + " package: " + intent.activity.info.packageName 10412 + " activity: " + intent.activity.className 10413 + " origPrio: " + intent.getPriority()); 10414 intent.setPriority(0); 10415 return; 10416 } 10417 } 10418 // privileged apps on the system image get whatever priority they request 10419 return; 10420 } 10421 10422 // privileged app unbundled update ... try to find the same activity 10423 final PackageParser.Activity foundActivity = 10424 findMatchingActivity(systemActivities, activityInfo); 10425 if (foundActivity == null) { 10426 // this is a new activity; it cannot obtain >0 priority 10427 if (DEBUG_FILTERS) { 10428 Slog.i(TAG, "New activity; cap priority to 0;" 10429 + " package: " + applicationInfo.packageName 10430 + " activity: " + intent.activity.className 10431 + " origPrio: " + intent.getPriority()); 10432 } 10433 intent.setPriority(0); 10434 return; 10435 } 10436 10437 // found activity, now check for filter equivalence 10438 10439 // a shallow copy is enough; we modify the list, not its contents 10440 final List<ActivityIntentInfo> intentListCopy = 10441 new ArrayList<>(foundActivity.intents); 10442 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10443 10444 // find matching action subsets 10445 final Iterator<String> actionsIterator = intent.actionsIterator(); 10446 if (actionsIterator != null) { 10447 getIntentListSubset( 10448 intentListCopy, new ActionIterGenerator(), actionsIterator); 10449 if (intentListCopy.size() == 0) { 10450 // no more intents to match; we're not equivalent 10451 if (DEBUG_FILTERS) { 10452 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10453 + " package: " + applicationInfo.packageName 10454 + " activity: " + intent.activity.className 10455 + " origPrio: " + intent.getPriority()); 10456 } 10457 intent.setPriority(0); 10458 return; 10459 } 10460 } 10461 10462 // find matching category subsets 10463 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10464 if (categoriesIterator != null) { 10465 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10466 categoriesIterator); 10467 if (intentListCopy.size() == 0) { 10468 // no more intents to match; we're not equivalent 10469 if (DEBUG_FILTERS) { 10470 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10471 + " package: " + applicationInfo.packageName 10472 + " activity: " + intent.activity.className 10473 + " origPrio: " + intent.getPriority()); 10474 } 10475 intent.setPriority(0); 10476 return; 10477 } 10478 } 10479 10480 // find matching schemes subsets 10481 final Iterator<String> schemesIterator = intent.schemesIterator(); 10482 if (schemesIterator != null) { 10483 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10484 schemesIterator); 10485 if (intentListCopy.size() == 0) { 10486 // no more intents to match; we're not equivalent 10487 if (DEBUG_FILTERS) { 10488 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10489 + " package: " + applicationInfo.packageName 10490 + " activity: " + intent.activity.className 10491 + " origPrio: " + intent.getPriority()); 10492 } 10493 intent.setPriority(0); 10494 return; 10495 } 10496 } 10497 10498 // find matching authorities subsets 10499 final Iterator<IntentFilter.AuthorityEntry> 10500 authoritiesIterator = intent.authoritiesIterator(); 10501 if (authoritiesIterator != null) { 10502 getIntentListSubset(intentListCopy, 10503 new AuthoritiesIterGenerator(), 10504 authoritiesIterator); 10505 if (intentListCopy.size() == 0) { 10506 // no more intents to match; we're not equivalent 10507 if (DEBUG_FILTERS) { 10508 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10509 + " package: " + applicationInfo.packageName 10510 + " activity: " + intent.activity.className 10511 + " origPrio: " + intent.getPriority()); 10512 } 10513 intent.setPriority(0); 10514 return; 10515 } 10516 } 10517 10518 // we found matching filter(s); app gets the max priority of all intents 10519 int cappedPriority = 0; 10520 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10521 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10522 } 10523 if (intent.getPriority() > cappedPriority) { 10524 if (DEBUG_FILTERS) { 10525 Slog.i(TAG, "Found matching filter(s);" 10526 + " cap priority to " + cappedPriority + ";" 10527 + " package: " + applicationInfo.packageName 10528 + " activity: " + intent.activity.className 10529 + " origPrio: " + intent.getPriority()); 10530 } 10531 intent.setPriority(cappedPriority); 10532 return; 10533 } 10534 // all this for nothing; the requested priority was <= what was on the system 10535 } 10536 10537 public final void addActivity(PackageParser.Activity a, String type) { 10538 mActivities.put(a.getComponentName(), a); 10539 if (DEBUG_SHOW_INFO) 10540 Log.v( 10541 TAG, " " + type + " " + 10542 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10543 if (DEBUG_SHOW_INFO) 10544 Log.v(TAG, " Class=" + a.info.name); 10545 final int NI = a.intents.size(); 10546 for (int j=0; j<NI; j++) { 10547 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10548 if ("activity".equals(type)) { 10549 final PackageSetting ps = 10550 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10551 final List<PackageParser.Activity> systemActivities = 10552 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10553 adjustPriority(systemActivities, intent); 10554 } 10555 if (DEBUG_SHOW_INFO) { 10556 Log.v(TAG, " IntentFilter:"); 10557 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10558 } 10559 if (!intent.debugCheck()) { 10560 Log.w(TAG, "==> For Activity " + a.info.name); 10561 } 10562 addFilter(intent); 10563 } 10564 } 10565 10566 public final void removeActivity(PackageParser.Activity a, String type) { 10567 mActivities.remove(a.getComponentName()); 10568 if (DEBUG_SHOW_INFO) { 10569 Log.v(TAG, " " + type + " " 10570 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10571 : a.info.name) + ":"); 10572 Log.v(TAG, " Class=" + a.info.name); 10573 } 10574 final int NI = a.intents.size(); 10575 for (int j=0; j<NI; j++) { 10576 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10577 if (DEBUG_SHOW_INFO) { 10578 Log.v(TAG, " IntentFilter:"); 10579 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10580 } 10581 removeFilter(intent); 10582 } 10583 } 10584 10585 @Override 10586 protected boolean allowFilterResult( 10587 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10588 ActivityInfo filterAi = filter.activity.info; 10589 for (int i=dest.size()-1; i>=0; i--) { 10590 ActivityInfo destAi = dest.get(i).activityInfo; 10591 if (destAi.name == filterAi.name 10592 && destAi.packageName == filterAi.packageName) { 10593 return false; 10594 } 10595 } 10596 return true; 10597 } 10598 10599 @Override 10600 protected ActivityIntentInfo[] newArray(int size) { 10601 return new ActivityIntentInfo[size]; 10602 } 10603 10604 @Override 10605 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10606 if (!sUserManager.exists(userId)) return true; 10607 PackageParser.Package p = filter.activity.owner; 10608 if (p != null) { 10609 PackageSetting ps = (PackageSetting)p.mExtras; 10610 if (ps != null) { 10611 // System apps are never considered stopped for purposes of 10612 // filtering, because there may be no way for the user to 10613 // actually re-launch them. 10614 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10615 && ps.getStopped(userId); 10616 } 10617 } 10618 return false; 10619 } 10620 10621 @Override 10622 protected boolean isPackageForFilter(String packageName, 10623 PackageParser.ActivityIntentInfo info) { 10624 return packageName.equals(info.activity.owner.packageName); 10625 } 10626 10627 @Override 10628 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10629 int match, int userId) { 10630 if (!sUserManager.exists(userId)) return null; 10631 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10632 return null; 10633 } 10634 final PackageParser.Activity activity = info.activity; 10635 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10636 if (ps == null) { 10637 return null; 10638 } 10639 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10640 ps.readUserState(userId), userId); 10641 if (ai == null) { 10642 return null; 10643 } 10644 final ResolveInfo res = new ResolveInfo(); 10645 res.activityInfo = ai; 10646 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10647 res.filter = info; 10648 } 10649 if (info != null) { 10650 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10651 } 10652 res.priority = info.getPriority(); 10653 res.preferredOrder = activity.owner.mPreferredOrder; 10654 //System.out.println("Result: " + res.activityInfo.className + 10655 // " = " + res.priority); 10656 res.match = match; 10657 res.isDefault = info.hasDefault; 10658 res.labelRes = info.labelRes; 10659 res.nonLocalizedLabel = info.nonLocalizedLabel; 10660 if (userNeedsBadging(userId)) { 10661 res.noResourceId = true; 10662 } else { 10663 res.icon = info.icon; 10664 } 10665 res.iconResourceId = info.icon; 10666 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10667 return res; 10668 } 10669 10670 @Override 10671 protected void sortResults(List<ResolveInfo> results) { 10672 Collections.sort(results, mResolvePrioritySorter); 10673 } 10674 10675 @Override 10676 protected void dumpFilter(PrintWriter out, String prefix, 10677 PackageParser.ActivityIntentInfo filter) { 10678 out.print(prefix); out.print( 10679 Integer.toHexString(System.identityHashCode(filter.activity))); 10680 out.print(' '); 10681 filter.activity.printComponentShortName(out); 10682 out.print(" filter "); 10683 out.println(Integer.toHexString(System.identityHashCode(filter))); 10684 } 10685 10686 @Override 10687 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10688 return filter.activity; 10689 } 10690 10691 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10692 PackageParser.Activity activity = (PackageParser.Activity)label; 10693 out.print(prefix); out.print( 10694 Integer.toHexString(System.identityHashCode(activity))); 10695 out.print(' '); 10696 activity.printComponentShortName(out); 10697 if (count > 1) { 10698 out.print(" ("); out.print(count); out.print(" filters)"); 10699 } 10700 out.println(); 10701 } 10702 10703 // Keys are String (activity class name), values are Activity. 10704 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10705 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10706 private int mFlags; 10707 } 10708 10709 private final class ServiceIntentResolver 10710 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10711 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10712 boolean defaultOnly, int userId) { 10713 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10714 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10715 } 10716 10717 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10718 int userId) { 10719 if (!sUserManager.exists(userId)) return null; 10720 mFlags = flags; 10721 return super.queryIntent(intent, resolvedType, 10722 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10723 } 10724 10725 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10726 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10727 if (!sUserManager.exists(userId)) return null; 10728 if (packageServices == null) { 10729 return null; 10730 } 10731 mFlags = flags; 10732 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10733 final int N = packageServices.size(); 10734 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10735 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10736 10737 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10738 for (int i = 0; i < N; ++i) { 10739 intentFilters = packageServices.get(i).intents; 10740 if (intentFilters != null && intentFilters.size() > 0) { 10741 PackageParser.ServiceIntentInfo[] array = 10742 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10743 intentFilters.toArray(array); 10744 listCut.add(array); 10745 } 10746 } 10747 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10748 } 10749 10750 public final void addService(PackageParser.Service s) { 10751 mServices.put(s.getComponentName(), s); 10752 if (DEBUG_SHOW_INFO) { 10753 Log.v(TAG, " " 10754 + (s.info.nonLocalizedLabel != null 10755 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10756 Log.v(TAG, " Class=" + s.info.name); 10757 } 10758 final int NI = s.intents.size(); 10759 int j; 10760 for (j=0; j<NI; j++) { 10761 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10762 if (DEBUG_SHOW_INFO) { 10763 Log.v(TAG, " IntentFilter:"); 10764 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10765 } 10766 if (!intent.debugCheck()) { 10767 Log.w(TAG, "==> For Service " + s.info.name); 10768 } 10769 addFilter(intent); 10770 } 10771 } 10772 10773 public final void removeService(PackageParser.Service s) { 10774 mServices.remove(s.getComponentName()); 10775 if (DEBUG_SHOW_INFO) { 10776 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10777 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10778 Log.v(TAG, " Class=" + s.info.name); 10779 } 10780 final int NI = s.intents.size(); 10781 int j; 10782 for (j=0; j<NI; j++) { 10783 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10784 if (DEBUG_SHOW_INFO) { 10785 Log.v(TAG, " IntentFilter:"); 10786 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10787 } 10788 removeFilter(intent); 10789 } 10790 } 10791 10792 @Override 10793 protected boolean allowFilterResult( 10794 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10795 ServiceInfo filterSi = filter.service.info; 10796 for (int i=dest.size()-1; i>=0; i--) { 10797 ServiceInfo destAi = dest.get(i).serviceInfo; 10798 if (destAi.name == filterSi.name 10799 && destAi.packageName == filterSi.packageName) { 10800 return false; 10801 } 10802 } 10803 return true; 10804 } 10805 10806 @Override 10807 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10808 return new PackageParser.ServiceIntentInfo[size]; 10809 } 10810 10811 @Override 10812 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10813 if (!sUserManager.exists(userId)) return true; 10814 PackageParser.Package p = filter.service.owner; 10815 if (p != null) { 10816 PackageSetting ps = (PackageSetting)p.mExtras; 10817 if (ps != null) { 10818 // System apps are never considered stopped for purposes of 10819 // filtering, because there may be no way for the user to 10820 // actually re-launch them. 10821 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10822 && ps.getStopped(userId); 10823 } 10824 } 10825 return false; 10826 } 10827 10828 @Override 10829 protected boolean isPackageForFilter(String packageName, 10830 PackageParser.ServiceIntentInfo info) { 10831 return packageName.equals(info.service.owner.packageName); 10832 } 10833 10834 @Override 10835 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10836 int match, int userId) { 10837 if (!sUserManager.exists(userId)) return null; 10838 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10839 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10840 return null; 10841 } 10842 final PackageParser.Service service = info.service; 10843 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10844 if (ps == null) { 10845 return null; 10846 } 10847 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10848 ps.readUserState(userId), userId); 10849 if (si == null) { 10850 return null; 10851 } 10852 final ResolveInfo res = new ResolveInfo(); 10853 res.serviceInfo = si; 10854 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10855 res.filter = filter; 10856 } 10857 res.priority = info.getPriority(); 10858 res.preferredOrder = service.owner.mPreferredOrder; 10859 res.match = match; 10860 res.isDefault = info.hasDefault; 10861 res.labelRes = info.labelRes; 10862 res.nonLocalizedLabel = info.nonLocalizedLabel; 10863 res.icon = info.icon; 10864 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10865 return res; 10866 } 10867 10868 @Override 10869 protected void sortResults(List<ResolveInfo> results) { 10870 Collections.sort(results, mResolvePrioritySorter); 10871 } 10872 10873 @Override 10874 protected void dumpFilter(PrintWriter out, String prefix, 10875 PackageParser.ServiceIntentInfo filter) { 10876 out.print(prefix); out.print( 10877 Integer.toHexString(System.identityHashCode(filter.service))); 10878 out.print(' '); 10879 filter.service.printComponentShortName(out); 10880 out.print(" filter "); 10881 out.println(Integer.toHexString(System.identityHashCode(filter))); 10882 } 10883 10884 @Override 10885 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10886 return filter.service; 10887 } 10888 10889 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10890 PackageParser.Service service = (PackageParser.Service)label; 10891 out.print(prefix); out.print( 10892 Integer.toHexString(System.identityHashCode(service))); 10893 out.print(' '); 10894 service.printComponentShortName(out); 10895 if (count > 1) { 10896 out.print(" ("); out.print(count); out.print(" filters)"); 10897 } 10898 out.println(); 10899 } 10900 10901// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10902// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10903// final List<ResolveInfo> retList = Lists.newArrayList(); 10904// while (i.hasNext()) { 10905// final ResolveInfo resolveInfo = (ResolveInfo) i; 10906// if (isEnabledLP(resolveInfo.serviceInfo)) { 10907// retList.add(resolveInfo); 10908// } 10909// } 10910// return retList; 10911// } 10912 10913 // Keys are String (activity class name), values are Activity. 10914 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10915 = new ArrayMap<ComponentName, PackageParser.Service>(); 10916 private int mFlags; 10917 }; 10918 10919 private final class ProviderIntentResolver 10920 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10921 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10922 boolean defaultOnly, int userId) { 10923 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10924 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10925 } 10926 10927 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10928 int userId) { 10929 if (!sUserManager.exists(userId)) 10930 return null; 10931 mFlags = flags; 10932 return super.queryIntent(intent, resolvedType, 10933 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10934 } 10935 10936 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10937 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10938 if (!sUserManager.exists(userId)) 10939 return null; 10940 if (packageProviders == null) { 10941 return null; 10942 } 10943 mFlags = flags; 10944 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10945 final int N = packageProviders.size(); 10946 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10947 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10948 10949 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10950 for (int i = 0; i < N; ++i) { 10951 intentFilters = packageProviders.get(i).intents; 10952 if (intentFilters != null && intentFilters.size() > 0) { 10953 PackageParser.ProviderIntentInfo[] array = 10954 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10955 intentFilters.toArray(array); 10956 listCut.add(array); 10957 } 10958 } 10959 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10960 } 10961 10962 public final void addProvider(PackageParser.Provider p) { 10963 if (mProviders.containsKey(p.getComponentName())) { 10964 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10965 return; 10966 } 10967 10968 mProviders.put(p.getComponentName(), p); 10969 if (DEBUG_SHOW_INFO) { 10970 Log.v(TAG, " " 10971 + (p.info.nonLocalizedLabel != null 10972 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10973 Log.v(TAG, " Class=" + p.info.name); 10974 } 10975 final int NI = p.intents.size(); 10976 int j; 10977 for (j = 0; j < NI; j++) { 10978 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10979 if (DEBUG_SHOW_INFO) { 10980 Log.v(TAG, " IntentFilter:"); 10981 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10982 } 10983 if (!intent.debugCheck()) { 10984 Log.w(TAG, "==> For Provider " + p.info.name); 10985 } 10986 addFilter(intent); 10987 } 10988 } 10989 10990 public final void removeProvider(PackageParser.Provider p) { 10991 mProviders.remove(p.getComponentName()); 10992 if (DEBUG_SHOW_INFO) { 10993 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10994 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10995 Log.v(TAG, " Class=" + p.info.name); 10996 } 10997 final int NI = p.intents.size(); 10998 int j; 10999 for (j = 0; j < NI; j++) { 11000 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11001 if (DEBUG_SHOW_INFO) { 11002 Log.v(TAG, " IntentFilter:"); 11003 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11004 } 11005 removeFilter(intent); 11006 } 11007 } 11008 11009 @Override 11010 protected boolean allowFilterResult( 11011 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11012 ProviderInfo filterPi = filter.provider.info; 11013 for (int i = dest.size() - 1; i >= 0; i--) { 11014 ProviderInfo destPi = dest.get(i).providerInfo; 11015 if (destPi.name == filterPi.name 11016 && destPi.packageName == filterPi.packageName) { 11017 return false; 11018 } 11019 } 11020 return true; 11021 } 11022 11023 @Override 11024 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11025 return new PackageParser.ProviderIntentInfo[size]; 11026 } 11027 11028 @Override 11029 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11030 if (!sUserManager.exists(userId)) 11031 return true; 11032 PackageParser.Package p = filter.provider.owner; 11033 if (p != null) { 11034 PackageSetting ps = (PackageSetting) p.mExtras; 11035 if (ps != null) { 11036 // System apps are never considered stopped for purposes of 11037 // filtering, because there may be no way for the user to 11038 // actually re-launch them. 11039 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11040 && ps.getStopped(userId); 11041 } 11042 } 11043 return false; 11044 } 11045 11046 @Override 11047 protected boolean isPackageForFilter(String packageName, 11048 PackageParser.ProviderIntentInfo info) { 11049 return packageName.equals(info.provider.owner.packageName); 11050 } 11051 11052 @Override 11053 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11054 int match, int userId) { 11055 if (!sUserManager.exists(userId)) 11056 return null; 11057 final PackageParser.ProviderIntentInfo info = filter; 11058 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11059 return null; 11060 } 11061 final PackageParser.Provider provider = info.provider; 11062 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11063 if (ps == null) { 11064 return null; 11065 } 11066 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11067 ps.readUserState(userId), userId); 11068 if (pi == null) { 11069 return null; 11070 } 11071 final ResolveInfo res = new ResolveInfo(); 11072 res.providerInfo = pi; 11073 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11074 res.filter = filter; 11075 } 11076 res.priority = info.getPriority(); 11077 res.preferredOrder = provider.owner.mPreferredOrder; 11078 res.match = match; 11079 res.isDefault = info.hasDefault; 11080 res.labelRes = info.labelRes; 11081 res.nonLocalizedLabel = info.nonLocalizedLabel; 11082 res.icon = info.icon; 11083 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11084 return res; 11085 } 11086 11087 @Override 11088 protected void sortResults(List<ResolveInfo> results) { 11089 Collections.sort(results, mResolvePrioritySorter); 11090 } 11091 11092 @Override 11093 protected void dumpFilter(PrintWriter out, String prefix, 11094 PackageParser.ProviderIntentInfo filter) { 11095 out.print(prefix); 11096 out.print( 11097 Integer.toHexString(System.identityHashCode(filter.provider))); 11098 out.print(' '); 11099 filter.provider.printComponentShortName(out); 11100 out.print(" filter "); 11101 out.println(Integer.toHexString(System.identityHashCode(filter))); 11102 } 11103 11104 @Override 11105 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11106 return filter.provider; 11107 } 11108 11109 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11110 PackageParser.Provider provider = (PackageParser.Provider)label; 11111 out.print(prefix); out.print( 11112 Integer.toHexString(System.identityHashCode(provider))); 11113 out.print(' '); 11114 provider.printComponentShortName(out); 11115 if (count > 1) { 11116 out.print(" ("); out.print(count); out.print(" filters)"); 11117 } 11118 out.println(); 11119 } 11120 11121 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11122 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11123 private int mFlags; 11124 } 11125 11126 private static final class EphemeralIntentResolver 11127 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11128 @Override 11129 protected EphemeralResolveIntentInfo[] newArray(int size) { 11130 return new EphemeralResolveIntentInfo[size]; 11131 } 11132 11133 @Override 11134 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11135 return true; 11136 } 11137 11138 @Override 11139 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11140 int userId) { 11141 if (!sUserManager.exists(userId)) { 11142 return null; 11143 } 11144 return info.getEphemeralResolveInfo(); 11145 } 11146 } 11147 11148 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11149 new Comparator<ResolveInfo>() { 11150 public int compare(ResolveInfo r1, ResolveInfo r2) { 11151 int v1 = r1.priority; 11152 int v2 = r2.priority; 11153 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11154 if (v1 != v2) { 11155 return (v1 > v2) ? -1 : 1; 11156 } 11157 v1 = r1.preferredOrder; 11158 v2 = r2.preferredOrder; 11159 if (v1 != v2) { 11160 return (v1 > v2) ? -1 : 1; 11161 } 11162 if (r1.isDefault != r2.isDefault) { 11163 return r1.isDefault ? -1 : 1; 11164 } 11165 v1 = r1.match; 11166 v2 = r2.match; 11167 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11168 if (v1 != v2) { 11169 return (v1 > v2) ? -1 : 1; 11170 } 11171 if (r1.system != r2.system) { 11172 return r1.system ? -1 : 1; 11173 } 11174 if (r1.activityInfo != null) { 11175 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11176 } 11177 if (r1.serviceInfo != null) { 11178 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11179 } 11180 if (r1.providerInfo != null) { 11181 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11182 } 11183 return 0; 11184 } 11185 }; 11186 11187 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11188 new Comparator<ProviderInfo>() { 11189 public int compare(ProviderInfo p1, ProviderInfo p2) { 11190 final int v1 = p1.initOrder; 11191 final int v2 = p2.initOrder; 11192 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11193 } 11194 }; 11195 11196 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11197 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11198 final int[] userIds) { 11199 mHandler.post(new Runnable() { 11200 @Override 11201 public void run() { 11202 try { 11203 final IActivityManager am = ActivityManagerNative.getDefault(); 11204 if (am == null) return; 11205 final int[] resolvedUserIds; 11206 if (userIds == null) { 11207 resolvedUserIds = am.getRunningUserIds(); 11208 } else { 11209 resolvedUserIds = userIds; 11210 } 11211 for (int id : resolvedUserIds) { 11212 final Intent intent = new Intent(action, 11213 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11214 if (extras != null) { 11215 intent.putExtras(extras); 11216 } 11217 if (targetPkg != null) { 11218 intent.setPackage(targetPkg); 11219 } 11220 // Modify the UID when posting to other users 11221 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11222 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11223 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11224 intent.putExtra(Intent.EXTRA_UID, uid); 11225 } 11226 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11227 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11228 if (DEBUG_BROADCASTS) { 11229 RuntimeException here = new RuntimeException("here"); 11230 here.fillInStackTrace(); 11231 Slog.d(TAG, "Sending to user " + id + ": " 11232 + intent.toShortString(false, true, false, false) 11233 + " " + intent.getExtras(), here); 11234 } 11235 am.broadcastIntent(null, intent, null, finishedReceiver, 11236 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11237 null, finishedReceiver != null, false, id); 11238 } 11239 } catch (RemoteException ex) { 11240 } 11241 } 11242 }); 11243 } 11244 11245 /** 11246 * Check if the external storage media is available. This is true if there 11247 * is a mounted external storage medium or if the external storage is 11248 * emulated. 11249 */ 11250 private boolean isExternalMediaAvailable() { 11251 return mMediaMounted || Environment.isExternalStorageEmulated(); 11252 } 11253 11254 @Override 11255 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11256 // writer 11257 synchronized (mPackages) { 11258 if (!isExternalMediaAvailable()) { 11259 // If the external storage is no longer mounted at this point, 11260 // the caller may not have been able to delete all of this 11261 // packages files and can not delete any more. Bail. 11262 return null; 11263 } 11264 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11265 if (lastPackage != null) { 11266 pkgs.remove(lastPackage); 11267 } 11268 if (pkgs.size() > 0) { 11269 return pkgs.get(0); 11270 } 11271 } 11272 return null; 11273 } 11274 11275 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11276 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11277 userId, andCode ? 1 : 0, packageName); 11278 if (mSystemReady) { 11279 msg.sendToTarget(); 11280 } else { 11281 if (mPostSystemReadyMessages == null) { 11282 mPostSystemReadyMessages = new ArrayList<>(); 11283 } 11284 mPostSystemReadyMessages.add(msg); 11285 } 11286 } 11287 11288 void startCleaningPackages() { 11289 // reader 11290 if (!isExternalMediaAvailable()) { 11291 return; 11292 } 11293 synchronized (mPackages) { 11294 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11295 return; 11296 } 11297 } 11298 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11299 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11300 IActivityManager am = ActivityManagerNative.getDefault(); 11301 if (am != null) { 11302 try { 11303 am.startService(null, intent, null, mContext.getOpPackageName(), 11304 UserHandle.USER_SYSTEM); 11305 } catch (RemoteException e) { 11306 } 11307 } 11308 } 11309 11310 @Override 11311 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11312 int installFlags, String installerPackageName, int userId) { 11313 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11314 11315 final int callingUid = Binder.getCallingUid(); 11316 enforceCrossUserPermission(callingUid, userId, 11317 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11318 11319 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11320 try { 11321 if (observer != null) { 11322 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11323 } 11324 } catch (RemoteException re) { 11325 } 11326 return; 11327 } 11328 11329 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11330 installFlags |= PackageManager.INSTALL_FROM_ADB; 11331 11332 } else { 11333 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11334 // about installerPackageName. 11335 11336 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11337 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11338 } 11339 11340 UserHandle user; 11341 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11342 user = UserHandle.ALL; 11343 } else { 11344 user = new UserHandle(userId); 11345 } 11346 11347 // Only system components can circumvent runtime permissions when installing. 11348 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11349 && mContext.checkCallingOrSelfPermission(Manifest.permission 11350 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11351 throw new SecurityException("You need the " 11352 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11353 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11354 } 11355 11356 final File originFile = new File(originPath); 11357 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11358 11359 final Message msg = mHandler.obtainMessage(INIT_COPY); 11360 final VerificationInfo verificationInfo = new VerificationInfo( 11361 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11362 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11363 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11364 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11365 null /*certificates*/); 11366 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11367 msg.obj = params; 11368 11369 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11370 System.identityHashCode(msg.obj)); 11371 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11372 System.identityHashCode(msg.obj)); 11373 11374 mHandler.sendMessage(msg); 11375 } 11376 11377 void installStage(String packageName, File stagedDir, String stagedCid, 11378 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11379 String installerPackageName, int installerUid, UserHandle user, 11380 Certificate[][] certificates) { 11381 if (DEBUG_EPHEMERAL) { 11382 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11383 Slog.d(TAG, "Ephemeral install of " + packageName); 11384 } 11385 } 11386 final VerificationInfo verificationInfo = new VerificationInfo( 11387 sessionParams.originatingUri, sessionParams.referrerUri, 11388 sessionParams.originatingUid, installerUid); 11389 11390 final OriginInfo origin; 11391 if (stagedDir != null) { 11392 origin = OriginInfo.fromStagedFile(stagedDir); 11393 } else { 11394 origin = OriginInfo.fromStagedContainer(stagedCid); 11395 } 11396 11397 final Message msg = mHandler.obtainMessage(INIT_COPY); 11398 final InstallParams params = new InstallParams(origin, null, observer, 11399 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11400 verificationInfo, user, sessionParams.abiOverride, 11401 sessionParams.grantedRuntimePermissions, certificates); 11402 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11403 msg.obj = params; 11404 11405 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11406 System.identityHashCode(msg.obj)); 11407 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11408 System.identityHashCode(msg.obj)); 11409 11410 mHandler.sendMessage(msg); 11411 } 11412 11413 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11414 int userId) { 11415 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11416 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11417 } 11418 11419 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11420 int appId, int userId) { 11421 Bundle extras = new Bundle(1); 11422 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11423 11424 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11425 packageName, extras, 0, null, null, new int[] {userId}); 11426 try { 11427 IActivityManager am = ActivityManagerNative.getDefault(); 11428 if (isSystem && am.isUserRunning(userId, 0)) { 11429 // The just-installed/enabled app is bundled on the system, so presumed 11430 // to be able to run automatically without needing an explicit launch. 11431 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11432 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11433 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11434 .setPackage(packageName); 11435 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11436 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11437 } 11438 } catch (RemoteException e) { 11439 // shouldn't happen 11440 Slog.w(TAG, "Unable to bootstrap installed package", e); 11441 } 11442 } 11443 11444 @Override 11445 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11446 int userId) { 11447 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11448 PackageSetting pkgSetting; 11449 final int uid = Binder.getCallingUid(); 11450 enforceCrossUserPermission(uid, userId, 11451 true /* requireFullPermission */, true /* checkShell */, 11452 "setApplicationHiddenSetting for user " + userId); 11453 11454 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11455 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11456 return false; 11457 } 11458 11459 long callingId = Binder.clearCallingIdentity(); 11460 try { 11461 boolean sendAdded = false; 11462 boolean sendRemoved = false; 11463 // writer 11464 synchronized (mPackages) { 11465 pkgSetting = mSettings.mPackages.get(packageName); 11466 if (pkgSetting == null) { 11467 return false; 11468 } 11469 if (pkgSetting.getHidden(userId) != hidden) { 11470 pkgSetting.setHidden(hidden, userId); 11471 mSettings.writePackageRestrictionsLPr(userId); 11472 if (hidden) { 11473 sendRemoved = true; 11474 } else { 11475 sendAdded = true; 11476 } 11477 } 11478 } 11479 if (sendAdded) { 11480 sendPackageAddedForUser(packageName, pkgSetting, userId); 11481 return true; 11482 } 11483 if (sendRemoved) { 11484 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11485 "hiding pkg"); 11486 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11487 return true; 11488 } 11489 } finally { 11490 Binder.restoreCallingIdentity(callingId); 11491 } 11492 return false; 11493 } 11494 11495 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11496 int userId) { 11497 final PackageRemovedInfo info = new PackageRemovedInfo(); 11498 info.removedPackage = packageName; 11499 info.removedUsers = new int[] {userId}; 11500 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11501 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11502 } 11503 11504 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11505 if (pkgList.length > 0) { 11506 Bundle extras = new Bundle(1); 11507 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11508 11509 sendPackageBroadcast( 11510 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11511 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11512 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11513 new int[] {userId}); 11514 } 11515 } 11516 11517 /** 11518 * Returns true if application is not found or there was an error. Otherwise it returns 11519 * the hidden state of the package for the given user. 11520 */ 11521 @Override 11522 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11524 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11525 true /* requireFullPermission */, false /* checkShell */, 11526 "getApplicationHidden for user " + userId); 11527 PackageSetting pkgSetting; 11528 long callingId = Binder.clearCallingIdentity(); 11529 try { 11530 // writer 11531 synchronized (mPackages) { 11532 pkgSetting = mSettings.mPackages.get(packageName); 11533 if (pkgSetting == null) { 11534 return true; 11535 } 11536 return pkgSetting.getHidden(userId); 11537 } 11538 } finally { 11539 Binder.restoreCallingIdentity(callingId); 11540 } 11541 } 11542 11543 /** 11544 * @hide 11545 */ 11546 @Override 11547 public int installExistingPackageAsUser(String packageName, int userId) { 11548 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11549 null); 11550 PackageSetting pkgSetting; 11551 final int uid = Binder.getCallingUid(); 11552 enforceCrossUserPermission(uid, userId, 11553 true /* requireFullPermission */, true /* checkShell */, 11554 "installExistingPackage for user " + userId); 11555 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11556 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11557 } 11558 11559 long callingId = Binder.clearCallingIdentity(); 11560 try { 11561 boolean installed = false; 11562 11563 // writer 11564 synchronized (mPackages) { 11565 pkgSetting = mSettings.mPackages.get(packageName); 11566 if (pkgSetting == null) { 11567 return PackageManager.INSTALL_FAILED_INVALID_URI; 11568 } 11569 if (!pkgSetting.getInstalled(userId)) { 11570 pkgSetting.setInstalled(true, userId); 11571 pkgSetting.setHidden(false, userId); 11572 mSettings.writePackageRestrictionsLPr(userId); 11573 installed = true; 11574 } 11575 } 11576 11577 if (installed) { 11578 if (pkgSetting.pkg != null) { 11579 synchronized (mInstallLock) { 11580 // We don't need to freeze for a brand new install 11581 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11582 } 11583 } 11584 sendPackageAddedForUser(packageName, pkgSetting, userId); 11585 } 11586 } finally { 11587 Binder.restoreCallingIdentity(callingId); 11588 } 11589 11590 return PackageManager.INSTALL_SUCCEEDED; 11591 } 11592 11593 boolean isUserRestricted(int userId, String restrictionKey) { 11594 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11595 if (restrictions.getBoolean(restrictionKey, false)) { 11596 Log.w(TAG, "User is restricted: " + restrictionKey); 11597 return true; 11598 } 11599 return false; 11600 } 11601 11602 @Override 11603 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11604 int userId) { 11605 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11606 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11607 true /* requireFullPermission */, true /* checkShell */, 11608 "setPackagesSuspended for user " + userId); 11609 11610 if (ArrayUtils.isEmpty(packageNames)) { 11611 return packageNames; 11612 } 11613 11614 // List of package names for whom the suspended state has changed. 11615 List<String> changedPackages = new ArrayList<>(packageNames.length); 11616 // List of package names for whom the suspended state is not set as requested in this 11617 // method. 11618 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11619 long callingId = Binder.clearCallingIdentity(); 11620 try { 11621 for (int i = 0; i < packageNames.length; i++) { 11622 String packageName = packageNames[i]; 11623 boolean changed = false; 11624 final int appId; 11625 synchronized (mPackages) { 11626 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11627 if (pkgSetting == null) { 11628 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11629 + "\". Skipping suspending/un-suspending."); 11630 unactionedPackages.add(packageName); 11631 continue; 11632 } 11633 appId = pkgSetting.appId; 11634 if (pkgSetting.getSuspended(userId) != suspended) { 11635 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11636 unactionedPackages.add(packageName); 11637 continue; 11638 } 11639 pkgSetting.setSuspended(suspended, userId); 11640 mSettings.writePackageRestrictionsLPr(userId); 11641 changed = true; 11642 changedPackages.add(packageName); 11643 } 11644 } 11645 11646 if (changed && suspended) { 11647 killApplication(packageName, UserHandle.getUid(userId, appId), 11648 "suspending package"); 11649 } 11650 } 11651 } finally { 11652 Binder.restoreCallingIdentity(callingId); 11653 } 11654 11655 if (!changedPackages.isEmpty()) { 11656 sendPackagesSuspendedForUser(changedPackages.toArray( 11657 new String[changedPackages.size()]), userId, suspended); 11658 } 11659 11660 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11661 } 11662 11663 @Override 11664 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11665 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11666 true /* requireFullPermission */, false /* checkShell */, 11667 "isPackageSuspendedForUser for user " + userId); 11668 synchronized (mPackages) { 11669 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11670 if (pkgSetting == null) { 11671 throw new IllegalArgumentException("Unknown target package: " + packageName); 11672 } 11673 return pkgSetting.getSuspended(userId); 11674 } 11675 } 11676 11677 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11678 if (isPackageDeviceAdmin(packageName, userId)) { 11679 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11680 + "\": has an active device admin"); 11681 return false; 11682 } 11683 11684 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11685 if (packageName.equals(activeLauncherPackageName)) { 11686 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11687 + "\": contains the active launcher"); 11688 return false; 11689 } 11690 11691 if (packageName.equals(mRequiredInstallerPackage)) { 11692 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11693 + "\": required for package installation"); 11694 return false; 11695 } 11696 11697 if (packageName.equals(mRequiredVerifierPackage)) { 11698 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11699 + "\": required for package verification"); 11700 return false; 11701 } 11702 11703 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11704 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11705 + "\": is the default dialer"); 11706 return false; 11707 } 11708 11709 return true; 11710 } 11711 11712 private String getActiveLauncherPackageName(int userId) { 11713 Intent intent = new Intent(Intent.ACTION_MAIN); 11714 intent.addCategory(Intent.CATEGORY_HOME); 11715 ResolveInfo resolveInfo = resolveIntent( 11716 intent, 11717 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11718 PackageManager.MATCH_DEFAULT_ONLY, 11719 userId); 11720 11721 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11722 } 11723 11724 private String getDefaultDialerPackageName(int userId) { 11725 synchronized (mPackages) { 11726 return mSettings.getDefaultDialerPackageNameLPw(userId); 11727 } 11728 } 11729 11730 @Override 11731 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11732 mContext.enforceCallingOrSelfPermission( 11733 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11734 "Only package verification agents can verify applications"); 11735 11736 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11737 final PackageVerificationResponse response = new PackageVerificationResponse( 11738 verificationCode, Binder.getCallingUid()); 11739 msg.arg1 = id; 11740 msg.obj = response; 11741 mHandler.sendMessage(msg); 11742 } 11743 11744 @Override 11745 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11746 long millisecondsToDelay) { 11747 mContext.enforceCallingOrSelfPermission( 11748 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11749 "Only package verification agents can extend verification timeouts"); 11750 11751 final PackageVerificationState state = mPendingVerification.get(id); 11752 final PackageVerificationResponse response = new PackageVerificationResponse( 11753 verificationCodeAtTimeout, Binder.getCallingUid()); 11754 11755 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11756 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11757 } 11758 if (millisecondsToDelay < 0) { 11759 millisecondsToDelay = 0; 11760 } 11761 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11762 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11763 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11764 } 11765 11766 if ((state != null) && !state.timeoutExtended()) { 11767 state.extendTimeout(); 11768 11769 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11770 msg.arg1 = id; 11771 msg.obj = response; 11772 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11773 } 11774 } 11775 11776 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11777 int verificationCode, UserHandle user) { 11778 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11779 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11780 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11781 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11782 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11783 11784 mContext.sendBroadcastAsUser(intent, user, 11785 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11786 } 11787 11788 private ComponentName matchComponentForVerifier(String packageName, 11789 List<ResolveInfo> receivers) { 11790 ActivityInfo targetReceiver = null; 11791 11792 final int NR = receivers.size(); 11793 for (int i = 0; i < NR; i++) { 11794 final ResolveInfo info = receivers.get(i); 11795 if (info.activityInfo == null) { 11796 continue; 11797 } 11798 11799 if (packageName.equals(info.activityInfo.packageName)) { 11800 targetReceiver = info.activityInfo; 11801 break; 11802 } 11803 } 11804 11805 if (targetReceiver == null) { 11806 return null; 11807 } 11808 11809 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11810 } 11811 11812 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11813 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11814 if (pkgInfo.verifiers.length == 0) { 11815 return null; 11816 } 11817 11818 final int N = pkgInfo.verifiers.length; 11819 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11820 for (int i = 0; i < N; i++) { 11821 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11822 11823 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11824 receivers); 11825 if (comp == null) { 11826 continue; 11827 } 11828 11829 final int verifierUid = getUidForVerifier(verifierInfo); 11830 if (verifierUid == -1) { 11831 continue; 11832 } 11833 11834 if (DEBUG_VERIFY) { 11835 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11836 + " with the correct signature"); 11837 } 11838 sufficientVerifiers.add(comp); 11839 verificationState.addSufficientVerifier(verifierUid); 11840 } 11841 11842 return sufficientVerifiers; 11843 } 11844 11845 private int getUidForVerifier(VerifierInfo verifierInfo) { 11846 synchronized (mPackages) { 11847 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11848 if (pkg == null) { 11849 return -1; 11850 } else if (pkg.mSignatures.length != 1) { 11851 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11852 + " has more than one signature; ignoring"); 11853 return -1; 11854 } 11855 11856 /* 11857 * If the public key of the package's signature does not match 11858 * our expected public key, then this is a different package and 11859 * we should skip. 11860 */ 11861 11862 final byte[] expectedPublicKey; 11863 try { 11864 final Signature verifierSig = pkg.mSignatures[0]; 11865 final PublicKey publicKey = verifierSig.getPublicKey(); 11866 expectedPublicKey = publicKey.getEncoded(); 11867 } catch (CertificateException e) { 11868 return -1; 11869 } 11870 11871 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11872 11873 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11874 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11875 + " does not have the expected public key; ignoring"); 11876 return -1; 11877 } 11878 11879 return pkg.applicationInfo.uid; 11880 } 11881 } 11882 11883 @Override 11884 public void finishPackageInstall(int token, boolean didLaunch) { 11885 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11886 11887 if (DEBUG_INSTALL) { 11888 Slog.v(TAG, "BM finishing package install for " + token); 11889 } 11890 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11891 11892 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11893 mHandler.sendMessage(msg); 11894 } 11895 11896 /** 11897 * Get the verification agent timeout. 11898 * 11899 * @return verification timeout in milliseconds 11900 */ 11901 private long getVerificationTimeout() { 11902 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11903 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11904 DEFAULT_VERIFICATION_TIMEOUT); 11905 } 11906 11907 /** 11908 * Get the default verification agent response code. 11909 * 11910 * @return default verification response code 11911 */ 11912 private int getDefaultVerificationResponse() { 11913 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11914 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11915 DEFAULT_VERIFICATION_RESPONSE); 11916 } 11917 11918 /** 11919 * Check whether or not package verification has been enabled. 11920 * 11921 * @return true if verification should be performed 11922 */ 11923 private boolean isVerificationEnabled(int userId, int installFlags) { 11924 if (!DEFAULT_VERIFY_ENABLE) { 11925 return false; 11926 } 11927 // Ephemeral apps don't get the full verification treatment 11928 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11929 if (DEBUG_EPHEMERAL) { 11930 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11931 } 11932 return false; 11933 } 11934 11935 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11936 11937 // Check if installing from ADB 11938 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11939 // Do not run verification in a test harness environment 11940 if (ActivityManager.isRunningInTestHarness()) { 11941 return false; 11942 } 11943 if (ensureVerifyAppsEnabled) { 11944 return true; 11945 } 11946 // Check if the developer does not want package verification for ADB installs 11947 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11948 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11949 return false; 11950 } 11951 } 11952 11953 if (ensureVerifyAppsEnabled) { 11954 return true; 11955 } 11956 11957 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11958 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11959 } 11960 11961 @Override 11962 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11963 throws RemoteException { 11964 mContext.enforceCallingOrSelfPermission( 11965 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11966 "Only intentfilter verification agents can verify applications"); 11967 11968 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11969 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11970 Binder.getCallingUid(), verificationCode, failedDomains); 11971 msg.arg1 = id; 11972 msg.obj = response; 11973 mHandler.sendMessage(msg); 11974 } 11975 11976 @Override 11977 public int getIntentVerificationStatus(String packageName, int userId) { 11978 synchronized (mPackages) { 11979 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11980 } 11981 } 11982 11983 @Override 11984 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11985 mContext.enforceCallingOrSelfPermission( 11986 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11987 11988 boolean result = false; 11989 synchronized (mPackages) { 11990 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11991 } 11992 if (result) { 11993 scheduleWritePackageRestrictionsLocked(userId); 11994 } 11995 return result; 11996 } 11997 11998 @Override 11999 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12000 String packageName) { 12001 synchronized (mPackages) { 12002 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12003 } 12004 } 12005 12006 @Override 12007 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12008 if (TextUtils.isEmpty(packageName)) { 12009 return ParceledListSlice.emptyList(); 12010 } 12011 synchronized (mPackages) { 12012 PackageParser.Package pkg = mPackages.get(packageName); 12013 if (pkg == null || pkg.activities == null) { 12014 return ParceledListSlice.emptyList(); 12015 } 12016 final int count = pkg.activities.size(); 12017 ArrayList<IntentFilter> result = new ArrayList<>(); 12018 for (int n=0; n<count; n++) { 12019 PackageParser.Activity activity = pkg.activities.get(n); 12020 if (activity.intents != null && activity.intents.size() > 0) { 12021 result.addAll(activity.intents); 12022 } 12023 } 12024 return new ParceledListSlice<>(result); 12025 } 12026 } 12027 12028 @Override 12029 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12030 mContext.enforceCallingOrSelfPermission( 12031 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12032 12033 synchronized (mPackages) { 12034 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12035 if (packageName != null) { 12036 result |= updateIntentVerificationStatus(packageName, 12037 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12038 userId); 12039 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12040 packageName, userId); 12041 } 12042 return result; 12043 } 12044 } 12045 12046 @Override 12047 public String getDefaultBrowserPackageName(int userId) { 12048 synchronized (mPackages) { 12049 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12050 } 12051 } 12052 12053 /** 12054 * Get the "allow unknown sources" setting. 12055 * 12056 * @return the current "allow unknown sources" setting 12057 */ 12058 private int getUnknownSourcesSettings() { 12059 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12060 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12061 -1); 12062 } 12063 12064 @Override 12065 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12066 final int uid = Binder.getCallingUid(); 12067 // writer 12068 synchronized (mPackages) { 12069 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12070 if (targetPackageSetting == null) { 12071 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12072 } 12073 12074 PackageSetting installerPackageSetting; 12075 if (installerPackageName != null) { 12076 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12077 if (installerPackageSetting == null) { 12078 throw new IllegalArgumentException("Unknown installer package: " 12079 + installerPackageName); 12080 } 12081 } else { 12082 installerPackageSetting = null; 12083 } 12084 12085 Signature[] callerSignature; 12086 Object obj = mSettings.getUserIdLPr(uid); 12087 if (obj != null) { 12088 if (obj instanceof SharedUserSetting) { 12089 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12090 } else if (obj instanceof PackageSetting) { 12091 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12092 } else { 12093 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12094 } 12095 } else { 12096 throw new SecurityException("Unknown calling UID: " + uid); 12097 } 12098 12099 // Verify: can't set installerPackageName to a package that is 12100 // not signed with the same cert as the caller. 12101 if (installerPackageSetting != null) { 12102 if (compareSignatures(callerSignature, 12103 installerPackageSetting.signatures.mSignatures) 12104 != PackageManager.SIGNATURE_MATCH) { 12105 throw new SecurityException( 12106 "Caller does not have same cert as new installer package " 12107 + installerPackageName); 12108 } 12109 } 12110 12111 // Verify: if target already has an installer package, it must 12112 // be signed with the same cert as the caller. 12113 if (targetPackageSetting.installerPackageName != null) { 12114 PackageSetting setting = mSettings.mPackages.get( 12115 targetPackageSetting.installerPackageName); 12116 // If the currently set package isn't valid, then it's always 12117 // okay to change it. 12118 if (setting != null) { 12119 if (compareSignatures(callerSignature, 12120 setting.signatures.mSignatures) 12121 != PackageManager.SIGNATURE_MATCH) { 12122 throw new SecurityException( 12123 "Caller does not have same cert as old installer package " 12124 + targetPackageSetting.installerPackageName); 12125 } 12126 } 12127 } 12128 12129 // Okay! 12130 targetPackageSetting.installerPackageName = installerPackageName; 12131 if (installerPackageName != null) { 12132 mSettings.mInstallerPackages.add(installerPackageName); 12133 } 12134 scheduleWriteSettingsLocked(); 12135 } 12136 } 12137 12138 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12139 // Queue up an async operation since the package installation may take a little while. 12140 mHandler.post(new Runnable() { 12141 public void run() { 12142 mHandler.removeCallbacks(this); 12143 // Result object to be returned 12144 PackageInstalledInfo res = new PackageInstalledInfo(); 12145 res.setReturnCode(currentStatus); 12146 res.uid = -1; 12147 res.pkg = null; 12148 res.removedInfo = null; 12149 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12150 args.doPreInstall(res.returnCode); 12151 synchronized (mInstallLock) { 12152 installPackageTracedLI(args, res); 12153 } 12154 args.doPostInstall(res.returnCode, res.uid); 12155 } 12156 12157 // A restore should be performed at this point if (a) the install 12158 // succeeded, (b) the operation is not an update, and (c) the new 12159 // package has not opted out of backup participation. 12160 final boolean update = res.removedInfo != null 12161 && res.removedInfo.removedPackage != null; 12162 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12163 boolean doRestore = !update 12164 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12165 12166 // Set up the post-install work request bookkeeping. This will be used 12167 // and cleaned up by the post-install event handling regardless of whether 12168 // there's a restore pass performed. Token values are >= 1. 12169 int token; 12170 if (mNextInstallToken < 0) mNextInstallToken = 1; 12171 token = mNextInstallToken++; 12172 12173 PostInstallData data = new PostInstallData(args, res); 12174 mRunningInstalls.put(token, data); 12175 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12176 12177 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12178 // Pass responsibility to the Backup Manager. It will perform a 12179 // restore if appropriate, then pass responsibility back to the 12180 // Package Manager to run the post-install observer callbacks 12181 // and broadcasts. 12182 IBackupManager bm = IBackupManager.Stub.asInterface( 12183 ServiceManager.getService(Context.BACKUP_SERVICE)); 12184 if (bm != null) { 12185 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12186 + " to BM for possible restore"); 12187 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12188 try { 12189 // TODO: http://b/22388012 12190 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12191 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12192 } else { 12193 doRestore = false; 12194 } 12195 } catch (RemoteException e) { 12196 // can't happen; the backup manager is local 12197 } catch (Exception e) { 12198 Slog.e(TAG, "Exception trying to enqueue restore", e); 12199 doRestore = false; 12200 } 12201 } else { 12202 Slog.e(TAG, "Backup Manager not found!"); 12203 doRestore = false; 12204 } 12205 } 12206 12207 if (!doRestore) { 12208 // No restore possible, or the Backup Manager was mysteriously not 12209 // available -- just fire the post-install work request directly. 12210 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12211 12212 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12213 12214 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12215 mHandler.sendMessage(msg); 12216 } 12217 } 12218 }); 12219 } 12220 12221 /** 12222 * Callback from PackageSettings whenever an app is first transitioned out of the 12223 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12224 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12225 * here whether the app is the target of an ongoing install, and only send the 12226 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12227 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12228 * handling. 12229 */ 12230 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12231 // Serialize this with the rest of the install-process message chain. In the 12232 // restore-at-install case, this Runnable will necessarily run before the 12233 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12234 // are coherent. In the non-restore case, the app has already completed install 12235 // and been launched through some other means, so it is not in a problematic 12236 // state for observers to see the FIRST_LAUNCH signal. 12237 mHandler.post(new Runnable() { 12238 @Override 12239 public void run() { 12240 for (int i = 0; i < mRunningInstalls.size(); i++) { 12241 final PostInstallData data = mRunningInstalls.valueAt(i); 12242 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12243 // right package; but is it for the right user? 12244 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12245 if (userId == data.res.newUsers[uIndex]) { 12246 if (DEBUG_BACKUP) { 12247 Slog.i(TAG, "Package " + pkgName 12248 + " being restored so deferring FIRST_LAUNCH"); 12249 } 12250 return; 12251 } 12252 } 12253 } 12254 } 12255 // didn't find it, so not being restored 12256 if (DEBUG_BACKUP) { 12257 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12258 } 12259 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12260 } 12261 }); 12262 } 12263 12264 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12265 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12266 installerPkg, null, userIds); 12267 } 12268 12269 private abstract class HandlerParams { 12270 private static final int MAX_RETRIES = 4; 12271 12272 /** 12273 * Number of times startCopy() has been attempted and had a non-fatal 12274 * error. 12275 */ 12276 private int mRetries = 0; 12277 12278 /** User handle for the user requesting the information or installation. */ 12279 private final UserHandle mUser; 12280 String traceMethod; 12281 int traceCookie; 12282 12283 HandlerParams(UserHandle user) { 12284 mUser = user; 12285 } 12286 12287 UserHandle getUser() { 12288 return mUser; 12289 } 12290 12291 HandlerParams setTraceMethod(String traceMethod) { 12292 this.traceMethod = traceMethod; 12293 return this; 12294 } 12295 12296 HandlerParams setTraceCookie(int traceCookie) { 12297 this.traceCookie = traceCookie; 12298 return this; 12299 } 12300 12301 final boolean startCopy() { 12302 boolean res; 12303 try { 12304 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12305 12306 if (++mRetries > MAX_RETRIES) { 12307 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12308 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12309 handleServiceError(); 12310 return false; 12311 } else { 12312 handleStartCopy(); 12313 res = true; 12314 } 12315 } catch (RemoteException e) { 12316 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12317 mHandler.sendEmptyMessage(MCS_RECONNECT); 12318 res = false; 12319 } 12320 handleReturnCode(); 12321 return res; 12322 } 12323 12324 final void serviceError() { 12325 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12326 handleServiceError(); 12327 handleReturnCode(); 12328 } 12329 12330 abstract void handleStartCopy() throws RemoteException; 12331 abstract void handleServiceError(); 12332 abstract void handleReturnCode(); 12333 } 12334 12335 class MeasureParams extends HandlerParams { 12336 private final PackageStats mStats; 12337 private boolean mSuccess; 12338 12339 private final IPackageStatsObserver mObserver; 12340 12341 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12342 super(new UserHandle(stats.userHandle)); 12343 mObserver = observer; 12344 mStats = stats; 12345 } 12346 12347 @Override 12348 public String toString() { 12349 return "MeasureParams{" 12350 + Integer.toHexString(System.identityHashCode(this)) 12351 + " " + mStats.packageName + "}"; 12352 } 12353 12354 @Override 12355 void handleStartCopy() throws RemoteException { 12356 synchronized (mInstallLock) { 12357 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12358 } 12359 12360 if (mSuccess) { 12361 final boolean mounted; 12362 if (Environment.isExternalStorageEmulated()) { 12363 mounted = true; 12364 } else { 12365 final String status = Environment.getExternalStorageState(); 12366 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12367 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12368 } 12369 12370 if (mounted) { 12371 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12372 12373 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12374 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12375 12376 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12377 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12378 12379 // Always subtract cache size, since it's a subdirectory 12380 mStats.externalDataSize -= mStats.externalCacheSize; 12381 12382 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12383 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12384 12385 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12386 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12387 } 12388 } 12389 } 12390 12391 @Override 12392 void handleReturnCode() { 12393 if (mObserver != null) { 12394 try { 12395 mObserver.onGetStatsCompleted(mStats, mSuccess); 12396 } catch (RemoteException e) { 12397 Slog.i(TAG, "Observer no longer exists."); 12398 } 12399 } 12400 } 12401 12402 @Override 12403 void handleServiceError() { 12404 Slog.e(TAG, "Could not measure application " + mStats.packageName 12405 + " external storage"); 12406 } 12407 } 12408 12409 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12410 throws RemoteException { 12411 long result = 0; 12412 for (File path : paths) { 12413 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12414 } 12415 return result; 12416 } 12417 12418 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12419 for (File path : paths) { 12420 try { 12421 mcs.clearDirectory(path.getAbsolutePath()); 12422 } catch (RemoteException e) { 12423 } 12424 } 12425 } 12426 12427 static class OriginInfo { 12428 /** 12429 * Location where install is coming from, before it has been 12430 * copied/renamed into place. This could be a single monolithic APK 12431 * file, or a cluster directory. This location may be untrusted. 12432 */ 12433 final File file; 12434 final String cid; 12435 12436 /** 12437 * Flag indicating that {@link #file} or {@link #cid} has already been 12438 * staged, meaning downstream users don't need to defensively copy the 12439 * contents. 12440 */ 12441 final boolean staged; 12442 12443 /** 12444 * Flag indicating that {@link #file} or {@link #cid} is an already 12445 * installed app that is being moved. 12446 */ 12447 final boolean existing; 12448 12449 final String resolvedPath; 12450 final File resolvedFile; 12451 12452 static OriginInfo fromNothing() { 12453 return new OriginInfo(null, null, false, false); 12454 } 12455 12456 static OriginInfo fromUntrustedFile(File file) { 12457 return new OriginInfo(file, null, false, false); 12458 } 12459 12460 static OriginInfo fromExistingFile(File file) { 12461 return new OriginInfo(file, null, false, true); 12462 } 12463 12464 static OriginInfo fromStagedFile(File file) { 12465 return new OriginInfo(file, null, true, false); 12466 } 12467 12468 static OriginInfo fromStagedContainer(String cid) { 12469 return new OriginInfo(null, cid, true, false); 12470 } 12471 12472 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12473 this.file = file; 12474 this.cid = cid; 12475 this.staged = staged; 12476 this.existing = existing; 12477 12478 if (cid != null) { 12479 resolvedPath = PackageHelper.getSdDir(cid); 12480 resolvedFile = new File(resolvedPath); 12481 } else if (file != null) { 12482 resolvedPath = file.getAbsolutePath(); 12483 resolvedFile = file; 12484 } else { 12485 resolvedPath = null; 12486 resolvedFile = null; 12487 } 12488 } 12489 } 12490 12491 static class MoveInfo { 12492 final int moveId; 12493 final String fromUuid; 12494 final String toUuid; 12495 final String packageName; 12496 final String dataAppName; 12497 final int appId; 12498 final String seinfo; 12499 final int targetSdkVersion; 12500 12501 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12502 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12503 this.moveId = moveId; 12504 this.fromUuid = fromUuid; 12505 this.toUuid = toUuid; 12506 this.packageName = packageName; 12507 this.dataAppName = dataAppName; 12508 this.appId = appId; 12509 this.seinfo = seinfo; 12510 this.targetSdkVersion = targetSdkVersion; 12511 } 12512 } 12513 12514 static class VerificationInfo { 12515 /** A constant used to indicate that a uid value is not present. */ 12516 public static final int NO_UID = -1; 12517 12518 /** URI referencing where the package was downloaded from. */ 12519 final Uri originatingUri; 12520 12521 /** HTTP referrer URI associated with the originatingURI. */ 12522 final Uri referrer; 12523 12524 /** UID of the application that the install request originated from. */ 12525 final int originatingUid; 12526 12527 /** UID of application requesting the install */ 12528 final int installerUid; 12529 12530 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12531 this.originatingUri = originatingUri; 12532 this.referrer = referrer; 12533 this.originatingUid = originatingUid; 12534 this.installerUid = installerUid; 12535 } 12536 } 12537 12538 class InstallParams extends HandlerParams { 12539 final OriginInfo origin; 12540 final MoveInfo move; 12541 final IPackageInstallObserver2 observer; 12542 int installFlags; 12543 final String installerPackageName; 12544 final String volumeUuid; 12545 private InstallArgs mArgs; 12546 private int mRet; 12547 final String packageAbiOverride; 12548 final String[] grantedRuntimePermissions; 12549 final VerificationInfo verificationInfo; 12550 final Certificate[][] certificates; 12551 12552 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12553 int installFlags, String installerPackageName, String volumeUuid, 12554 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12555 String[] grantedPermissions, Certificate[][] certificates) { 12556 super(user); 12557 this.origin = origin; 12558 this.move = move; 12559 this.observer = observer; 12560 this.installFlags = installFlags; 12561 this.installerPackageName = installerPackageName; 12562 this.volumeUuid = volumeUuid; 12563 this.verificationInfo = verificationInfo; 12564 this.packageAbiOverride = packageAbiOverride; 12565 this.grantedRuntimePermissions = grantedPermissions; 12566 this.certificates = certificates; 12567 } 12568 12569 @Override 12570 public String toString() { 12571 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12572 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12573 } 12574 12575 private int installLocationPolicy(PackageInfoLite pkgLite) { 12576 String packageName = pkgLite.packageName; 12577 int installLocation = pkgLite.installLocation; 12578 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12579 // reader 12580 synchronized (mPackages) { 12581 // Currently installed package which the new package is attempting to replace or 12582 // null if no such package is installed. 12583 PackageParser.Package installedPkg = mPackages.get(packageName); 12584 // Package which currently owns the data which the new package will own if installed. 12585 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12586 // will be null whereas dataOwnerPkg will contain information about the package 12587 // which was uninstalled while keeping its data. 12588 PackageParser.Package dataOwnerPkg = installedPkg; 12589 if (dataOwnerPkg == null) { 12590 PackageSetting ps = mSettings.mPackages.get(packageName); 12591 if (ps != null) { 12592 dataOwnerPkg = ps.pkg; 12593 } 12594 } 12595 12596 if (dataOwnerPkg != null) { 12597 // If installed, the package will get access to data left on the device by its 12598 // predecessor. As a security measure, this is permited only if this is not a 12599 // version downgrade or if the predecessor package is marked as debuggable and 12600 // a downgrade is explicitly requested. 12601 // 12602 // On debuggable platform builds, downgrades are permitted even for 12603 // non-debuggable packages to make testing easier. Debuggable platform builds do 12604 // not offer security guarantees and thus it's OK to disable some security 12605 // mechanisms to make debugging/testing easier on those builds. However, even on 12606 // debuggable builds downgrades of packages are permitted only if requested via 12607 // installFlags. This is because we aim to keep the behavior of debuggable 12608 // platform builds as close as possible to the behavior of non-debuggable 12609 // platform builds. 12610 final boolean downgradeRequested = 12611 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12612 final boolean packageDebuggable = 12613 (dataOwnerPkg.applicationInfo.flags 12614 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12615 final boolean downgradePermitted = 12616 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12617 if (!downgradePermitted) { 12618 try { 12619 checkDowngrade(dataOwnerPkg, pkgLite); 12620 } catch (PackageManagerException e) { 12621 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12622 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12623 } 12624 } 12625 } 12626 12627 if (installedPkg != null) { 12628 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12629 // Check for updated system application. 12630 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12631 if (onSd) { 12632 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12633 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12634 } 12635 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12636 } else { 12637 if (onSd) { 12638 // Install flag overrides everything. 12639 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12640 } 12641 // If current upgrade specifies particular preference 12642 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12643 // Application explicitly specified internal. 12644 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12645 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12646 // App explictly prefers external. Let policy decide 12647 } else { 12648 // Prefer previous location 12649 if (isExternal(installedPkg)) { 12650 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12651 } 12652 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12653 } 12654 } 12655 } else { 12656 // Invalid install. Return error code 12657 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12658 } 12659 } 12660 } 12661 // All the special cases have been taken care of. 12662 // Return result based on recommended install location. 12663 if (onSd) { 12664 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12665 } 12666 return pkgLite.recommendedInstallLocation; 12667 } 12668 12669 /* 12670 * Invoke remote method to get package information and install 12671 * location values. Override install location based on default 12672 * policy if needed and then create install arguments based 12673 * on the install location. 12674 */ 12675 public void handleStartCopy() throws RemoteException { 12676 int ret = PackageManager.INSTALL_SUCCEEDED; 12677 12678 // If we're already staged, we've firmly committed to an install location 12679 if (origin.staged) { 12680 if (origin.file != null) { 12681 installFlags |= PackageManager.INSTALL_INTERNAL; 12682 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12683 } else if (origin.cid != null) { 12684 installFlags |= PackageManager.INSTALL_EXTERNAL; 12685 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12686 } else { 12687 throw new IllegalStateException("Invalid stage location"); 12688 } 12689 } 12690 12691 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12692 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12693 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12694 PackageInfoLite pkgLite = null; 12695 12696 if (onInt && onSd) { 12697 // Check if both bits are set. 12698 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12699 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12700 } else if (onSd && ephemeral) { 12701 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12702 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12703 } else { 12704 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12705 packageAbiOverride); 12706 12707 if (DEBUG_EPHEMERAL && ephemeral) { 12708 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12709 } 12710 12711 /* 12712 * If we have too little free space, try to free cache 12713 * before giving up. 12714 */ 12715 if (!origin.staged && pkgLite.recommendedInstallLocation 12716 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12717 // TODO: focus freeing disk space on the target device 12718 final StorageManager storage = StorageManager.from(mContext); 12719 final long lowThreshold = storage.getStorageLowBytes( 12720 Environment.getDataDirectory()); 12721 12722 final long sizeBytes = mContainerService.calculateInstalledSize( 12723 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12724 12725 try { 12726 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12727 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12728 installFlags, packageAbiOverride); 12729 } catch (InstallerException e) { 12730 Slog.w(TAG, "Failed to free cache", e); 12731 } 12732 12733 /* 12734 * The cache free must have deleted the file we 12735 * downloaded to install. 12736 * 12737 * TODO: fix the "freeCache" call to not delete 12738 * the file we care about. 12739 */ 12740 if (pkgLite.recommendedInstallLocation 12741 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12742 pkgLite.recommendedInstallLocation 12743 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12744 } 12745 } 12746 } 12747 12748 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12749 int loc = pkgLite.recommendedInstallLocation; 12750 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12751 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12752 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12753 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12754 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12755 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12756 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12757 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12758 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12759 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12760 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12761 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12762 } else { 12763 // Override with defaults if needed. 12764 loc = installLocationPolicy(pkgLite); 12765 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12766 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12767 } else if (!onSd && !onInt) { 12768 // Override install location with flags 12769 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12770 // Set the flag to install on external media. 12771 installFlags |= PackageManager.INSTALL_EXTERNAL; 12772 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12773 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12774 if (DEBUG_EPHEMERAL) { 12775 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12776 } 12777 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12778 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12779 |PackageManager.INSTALL_INTERNAL); 12780 } else { 12781 // Make sure the flag for installing on external 12782 // media is unset 12783 installFlags |= PackageManager.INSTALL_INTERNAL; 12784 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12785 } 12786 } 12787 } 12788 } 12789 12790 final InstallArgs args = createInstallArgs(this); 12791 mArgs = args; 12792 12793 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12794 // TODO: http://b/22976637 12795 // Apps installed for "all" users use the device owner to verify the app 12796 UserHandle verifierUser = getUser(); 12797 if (verifierUser == UserHandle.ALL) { 12798 verifierUser = UserHandle.SYSTEM; 12799 } 12800 12801 /* 12802 * Determine if we have any installed package verifiers. If we 12803 * do, then we'll defer to them to verify the packages. 12804 */ 12805 final int requiredUid = mRequiredVerifierPackage == null ? -1 12806 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12807 verifierUser.getIdentifier()); 12808 if (!origin.existing && requiredUid != -1 12809 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12810 final Intent verification = new Intent( 12811 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12812 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12813 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12814 PACKAGE_MIME_TYPE); 12815 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12816 12817 // Query all live verifiers based on current user state 12818 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12819 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12820 12821 if (DEBUG_VERIFY) { 12822 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12823 + verification.toString() + " with " + pkgLite.verifiers.length 12824 + " optional verifiers"); 12825 } 12826 12827 final int verificationId = mPendingVerificationToken++; 12828 12829 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12830 12831 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12832 installerPackageName); 12833 12834 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12835 installFlags); 12836 12837 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12838 pkgLite.packageName); 12839 12840 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12841 pkgLite.versionCode); 12842 12843 if (verificationInfo != null) { 12844 if (verificationInfo.originatingUri != null) { 12845 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12846 verificationInfo.originatingUri); 12847 } 12848 if (verificationInfo.referrer != null) { 12849 verification.putExtra(Intent.EXTRA_REFERRER, 12850 verificationInfo.referrer); 12851 } 12852 if (verificationInfo.originatingUid >= 0) { 12853 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12854 verificationInfo.originatingUid); 12855 } 12856 if (verificationInfo.installerUid >= 0) { 12857 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12858 verificationInfo.installerUid); 12859 } 12860 } 12861 12862 final PackageVerificationState verificationState = new PackageVerificationState( 12863 requiredUid, args); 12864 12865 mPendingVerification.append(verificationId, verificationState); 12866 12867 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12868 receivers, verificationState); 12869 12870 /* 12871 * If any sufficient verifiers were listed in the package 12872 * manifest, attempt to ask them. 12873 */ 12874 if (sufficientVerifiers != null) { 12875 final int N = sufficientVerifiers.size(); 12876 if (N == 0) { 12877 Slog.i(TAG, "Additional verifiers required, but none installed."); 12878 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12879 } else { 12880 for (int i = 0; i < N; i++) { 12881 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12882 12883 final Intent sufficientIntent = new Intent(verification); 12884 sufficientIntent.setComponent(verifierComponent); 12885 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12886 } 12887 } 12888 } 12889 12890 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12891 mRequiredVerifierPackage, receivers); 12892 if (ret == PackageManager.INSTALL_SUCCEEDED 12893 && mRequiredVerifierPackage != null) { 12894 Trace.asyncTraceBegin( 12895 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12896 /* 12897 * Send the intent to the required verification agent, 12898 * but only start the verification timeout after the 12899 * target BroadcastReceivers have run. 12900 */ 12901 verification.setComponent(requiredVerifierComponent); 12902 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12903 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12904 new BroadcastReceiver() { 12905 @Override 12906 public void onReceive(Context context, Intent intent) { 12907 final Message msg = mHandler 12908 .obtainMessage(CHECK_PENDING_VERIFICATION); 12909 msg.arg1 = verificationId; 12910 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12911 } 12912 }, null, 0, null, null); 12913 12914 /* 12915 * We don't want the copy to proceed until verification 12916 * succeeds, so null out this field. 12917 */ 12918 mArgs = null; 12919 } 12920 } else { 12921 /* 12922 * No package verification is enabled, so immediately start 12923 * the remote call to initiate copy using temporary file. 12924 */ 12925 ret = args.copyApk(mContainerService, true); 12926 } 12927 } 12928 12929 mRet = ret; 12930 } 12931 12932 @Override 12933 void handleReturnCode() { 12934 // If mArgs is null, then MCS couldn't be reached. When it 12935 // reconnects, it will try again to install. At that point, this 12936 // will succeed. 12937 if (mArgs != null) { 12938 processPendingInstall(mArgs, mRet); 12939 } 12940 } 12941 12942 @Override 12943 void handleServiceError() { 12944 mArgs = createInstallArgs(this); 12945 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12946 } 12947 12948 public boolean isForwardLocked() { 12949 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12950 } 12951 } 12952 12953 /** 12954 * Used during creation of InstallArgs 12955 * 12956 * @param installFlags package installation flags 12957 * @return true if should be installed on external storage 12958 */ 12959 private static boolean installOnExternalAsec(int installFlags) { 12960 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12961 return false; 12962 } 12963 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12964 return true; 12965 } 12966 return false; 12967 } 12968 12969 /** 12970 * Used during creation of InstallArgs 12971 * 12972 * @param installFlags package installation flags 12973 * @return true if should be installed as forward locked 12974 */ 12975 private static boolean installForwardLocked(int installFlags) { 12976 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12977 } 12978 12979 private InstallArgs createInstallArgs(InstallParams params) { 12980 if (params.move != null) { 12981 return new MoveInstallArgs(params); 12982 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12983 return new AsecInstallArgs(params); 12984 } else { 12985 return new FileInstallArgs(params); 12986 } 12987 } 12988 12989 /** 12990 * Create args that describe an existing installed package. Typically used 12991 * when cleaning up old installs, or used as a move source. 12992 */ 12993 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12994 String resourcePath, String[] instructionSets) { 12995 final boolean isInAsec; 12996 if (installOnExternalAsec(installFlags)) { 12997 /* Apps on SD card are always in ASEC containers. */ 12998 isInAsec = true; 12999 } else if (installForwardLocked(installFlags) 13000 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13001 /* 13002 * Forward-locked apps are only in ASEC containers if they're the 13003 * new style 13004 */ 13005 isInAsec = true; 13006 } else { 13007 isInAsec = false; 13008 } 13009 13010 if (isInAsec) { 13011 return new AsecInstallArgs(codePath, instructionSets, 13012 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13013 } else { 13014 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13015 } 13016 } 13017 13018 static abstract class InstallArgs { 13019 /** @see InstallParams#origin */ 13020 final OriginInfo origin; 13021 /** @see InstallParams#move */ 13022 final MoveInfo move; 13023 13024 final IPackageInstallObserver2 observer; 13025 // Always refers to PackageManager flags only 13026 final int installFlags; 13027 final String installerPackageName; 13028 final String volumeUuid; 13029 final UserHandle user; 13030 final String abiOverride; 13031 final String[] installGrantPermissions; 13032 /** If non-null, drop an async trace when the install completes */ 13033 final String traceMethod; 13034 final int traceCookie; 13035 final Certificate[][] certificates; 13036 13037 // The list of instruction sets supported by this app. This is currently 13038 // only used during the rmdex() phase to clean up resources. We can get rid of this 13039 // if we move dex files under the common app path. 13040 /* nullable */ String[] instructionSets; 13041 13042 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13043 int installFlags, String installerPackageName, String volumeUuid, 13044 UserHandle user, String[] instructionSets, 13045 String abiOverride, String[] installGrantPermissions, 13046 String traceMethod, int traceCookie, Certificate[][] certificates) { 13047 this.origin = origin; 13048 this.move = move; 13049 this.installFlags = installFlags; 13050 this.observer = observer; 13051 this.installerPackageName = installerPackageName; 13052 this.volumeUuid = volumeUuid; 13053 this.user = user; 13054 this.instructionSets = instructionSets; 13055 this.abiOverride = abiOverride; 13056 this.installGrantPermissions = installGrantPermissions; 13057 this.traceMethod = traceMethod; 13058 this.traceCookie = traceCookie; 13059 this.certificates = certificates; 13060 } 13061 13062 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13063 abstract int doPreInstall(int status); 13064 13065 /** 13066 * Rename package into final resting place. All paths on the given 13067 * scanned package should be updated to reflect the rename. 13068 */ 13069 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13070 abstract int doPostInstall(int status, int uid); 13071 13072 /** @see PackageSettingBase#codePathString */ 13073 abstract String getCodePath(); 13074 /** @see PackageSettingBase#resourcePathString */ 13075 abstract String getResourcePath(); 13076 13077 // Need installer lock especially for dex file removal. 13078 abstract void cleanUpResourcesLI(); 13079 abstract boolean doPostDeleteLI(boolean delete); 13080 13081 /** 13082 * Called before the source arguments are copied. This is used mostly 13083 * for MoveParams when it needs to read the source file to put it in the 13084 * destination. 13085 */ 13086 int doPreCopy() { 13087 return PackageManager.INSTALL_SUCCEEDED; 13088 } 13089 13090 /** 13091 * Called after the source arguments are copied. This is used mostly for 13092 * MoveParams when it needs to read the source file to put it in the 13093 * destination. 13094 */ 13095 int doPostCopy(int uid) { 13096 return PackageManager.INSTALL_SUCCEEDED; 13097 } 13098 13099 protected boolean isFwdLocked() { 13100 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13101 } 13102 13103 protected boolean isExternalAsec() { 13104 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13105 } 13106 13107 protected boolean isEphemeral() { 13108 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13109 } 13110 13111 UserHandle getUser() { 13112 return user; 13113 } 13114 } 13115 13116 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13117 if (!allCodePaths.isEmpty()) { 13118 if (instructionSets == null) { 13119 throw new IllegalStateException("instructionSet == null"); 13120 } 13121 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13122 for (String codePath : allCodePaths) { 13123 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13124 try { 13125 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13126 } catch (InstallerException ignored) { 13127 } 13128 } 13129 } 13130 } 13131 } 13132 13133 /** 13134 * Logic to handle installation of non-ASEC applications, including copying 13135 * and renaming logic. 13136 */ 13137 class FileInstallArgs extends InstallArgs { 13138 private File codeFile; 13139 private File resourceFile; 13140 13141 // Example topology: 13142 // /data/app/com.example/base.apk 13143 // /data/app/com.example/split_foo.apk 13144 // /data/app/com.example/lib/arm/libfoo.so 13145 // /data/app/com.example/lib/arm64/libfoo.so 13146 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13147 13148 /** New install */ 13149 FileInstallArgs(InstallParams params) { 13150 super(params.origin, params.move, params.observer, params.installFlags, 13151 params.installerPackageName, params.volumeUuid, 13152 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13153 params.grantedRuntimePermissions, 13154 params.traceMethod, params.traceCookie, params.certificates); 13155 if (isFwdLocked()) { 13156 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13157 } 13158 } 13159 13160 /** Existing install */ 13161 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13162 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13163 null, null, null, 0, null /*certificates*/); 13164 this.codeFile = (codePath != null) ? new File(codePath) : null; 13165 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13166 } 13167 13168 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13169 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13170 try { 13171 return doCopyApk(imcs, temp); 13172 } finally { 13173 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13174 } 13175 } 13176 13177 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13178 if (origin.staged) { 13179 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13180 codeFile = origin.file; 13181 resourceFile = origin.file; 13182 return PackageManager.INSTALL_SUCCEEDED; 13183 } 13184 13185 try { 13186 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13187 final File tempDir = 13188 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13189 codeFile = tempDir; 13190 resourceFile = tempDir; 13191 } catch (IOException e) { 13192 Slog.w(TAG, "Failed to create copy file: " + e); 13193 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13194 } 13195 13196 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13197 @Override 13198 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13199 if (!FileUtils.isValidExtFilename(name)) { 13200 throw new IllegalArgumentException("Invalid filename: " + name); 13201 } 13202 try { 13203 final File file = new File(codeFile, name); 13204 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13205 O_RDWR | O_CREAT, 0644); 13206 Os.chmod(file.getAbsolutePath(), 0644); 13207 return new ParcelFileDescriptor(fd); 13208 } catch (ErrnoException e) { 13209 throw new RemoteException("Failed to open: " + e.getMessage()); 13210 } 13211 } 13212 }; 13213 13214 int ret = PackageManager.INSTALL_SUCCEEDED; 13215 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13216 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13217 Slog.e(TAG, "Failed to copy package"); 13218 return ret; 13219 } 13220 13221 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13222 NativeLibraryHelper.Handle handle = null; 13223 try { 13224 handle = NativeLibraryHelper.Handle.create(codeFile); 13225 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13226 abiOverride); 13227 } catch (IOException e) { 13228 Slog.e(TAG, "Copying native libraries failed", e); 13229 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13230 } finally { 13231 IoUtils.closeQuietly(handle); 13232 } 13233 13234 return ret; 13235 } 13236 13237 int doPreInstall(int status) { 13238 if (status != PackageManager.INSTALL_SUCCEEDED) { 13239 cleanUp(); 13240 } 13241 return status; 13242 } 13243 13244 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13245 if (status != PackageManager.INSTALL_SUCCEEDED) { 13246 cleanUp(); 13247 return false; 13248 } 13249 13250 final File targetDir = codeFile.getParentFile(); 13251 final File beforeCodeFile = codeFile; 13252 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13253 13254 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13255 try { 13256 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13257 } catch (ErrnoException e) { 13258 Slog.w(TAG, "Failed to rename", e); 13259 return false; 13260 } 13261 13262 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13263 Slog.w(TAG, "Failed to restorecon"); 13264 return false; 13265 } 13266 13267 // Reflect the rename internally 13268 codeFile = afterCodeFile; 13269 resourceFile = afterCodeFile; 13270 13271 // Reflect the rename in scanned details 13272 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13273 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13274 afterCodeFile, pkg.baseCodePath)); 13275 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13276 afterCodeFile, pkg.splitCodePaths)); 13277 13278 // Reflect the rename in app info 13279 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13280 pkg.setApplicationInfoCodePath(pkg.codePath); 13281 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13282 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13283 pkg.setApplicationInfoResourcePath(pkg.codePath); 13284 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13285 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13286 13287 return true; 13288 } 13289 13290 int doPostInstall(int status, int uid) { 13291 if (status != PackageManager.INSTALL_SUCCEEDED) { 13292 cleanUp(); 13293 } 13294 return status; 13295 } 13296 13297 @Override 13298 String getCodePath() { 13299 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13300 } 13301 13302 @Override 13303 String getResourcePath() { 13304 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13305 } 13306 13307 private boolean cleanUp() { 13308 if (codeFile == null || !codeFile.exists()) { 13309 return false; 13310 } 13311 13312 removeCodePathLI(codeFile); 13313 13314 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13315 resourceFile.delete(); 13316 } 13317 13318 return true; 13319 } 13320 13321 void cleanUpResourcesLI() { 13322 // Try enumerating all code paths before deleting 13323 List<String> allCodePaths = Collections.EMPTY_LIST; 13324 if (codeFile != null && codeFile.exists()) { 13325 try { 13326 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13327 allCodePaths = pkg.getAllCodePaths(); 13328 } catch (PackageParserException e) { 13329 // Ignored; we tried our best 13330 } 13331 } 13332 13333 cleanUp(); 13334 removeDexFiles(allCodePaths, instructionSets); 13335 } 13336 13337 boolean doPostDeleteLI(boolean delete) { 13338 // XXX err, shouldn't we respect the delete flag? 13339 cleanUpResourcesLI(); 13340 return true; 13341 } 13342 } 13343 13344 private boolean isAsecExternal(String cid) { 13345 final String asecPath = PackageHelper.getSdFilesystem(cid); 13346 return !asecPath.startsWith(mAsecInternalPath); 13347 } 13348 13349 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13350 PackageManagerException { 13351 if (copyRet < 0) { 13352 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13353 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13354 throw new PackageManagerException(copyRet, message); 13355 } 13356 } 13357 } 13358 13359 /** 13360 * Extract the MountService "container ID" from the full code path of an 13361 * .apk. 13362 */ 13363 static String cidFromCodePath(String fullCodePath) { 13364 int eidx = fullCodePath.lastIndexOf("/"); 13365 String subStr1 = fullCodePath.substring(0, eidx); 13366 int sidx = subStr1.lastIndexOf("/"); 13367 return subStr1.substring(sidx+1, eidx); 13368 } 13369 13370 /** 13371 * Logic to handle installation of ASEC applications, including copying and 13372 * renaming logic. 13373 */ 13374 class AsecInstallArgs extends InstallArgs { 13375 static final String RES_FILE_NAME = "pkg.apk"; 13376 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13377 13378 String cid; 13379 String packagePath; 13380 String resourcePath; 13381 13382 /** New install */ 13383 AsecInstallArgs(InstallParams params) { 13384 super(params.origin, params.move, params.observer, params.installFlags, 13385 params.installerPackageName, params.volumeUuid, 13386 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13387 params.grantedRuntimePermissions, 13388 params.traceMethod, params.traceCookie, params.certificates); 13389 } 13390 13391 /** Existing install */ 13392 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13393 boolean isExternal, boolean isForwardLocked) { 13394 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13395 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13396 instructionSets, null, null, null, 0, null /*certificates*/); 13397 // Hackily pretend we're still looking at a full code path 13398 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13399 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13400 } 13401 13402 // Extract cid from fullCodePath 13403 int eidx = fullCodePath.lastIndexOf("/"); 13404 String subStr1 = fullCodePath.substring(0, eidx); 13405 int sidx = subStr1.lastIndexOf("/"); 13406 cid = subStr1.substring(sidx+1, eidx); 13407 setMountPath(subStr1); 13408 } 13409 13410 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13411 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13412 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13413 instructionSets, null, null, null, 0, null /*certificates*/); 13414 this.cid = cid; 13415 setMountPath(PackageHelper.getSdDir(cid)); 13416 } 13417 13418 void createCopyFile() { 13419 cid = mInstallerService.allocateExternalStageCidLegacy(); 13420 } 13421 13422 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13423 if (origin.staged && origin.cid != null) { 13424 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13425 cid = origin.cid; 13426 setMountPath(PackageHelper.getSdDir(cid)); 13427 return PackageManager.INSTALL_SUCCEEDED; 13428 } 13429 13430 if (temp) { 13431 createCopyFile(); 13432 } else { 13433 /* 13434 * Pre-emptively destroy the container since it's destroyed if 13435 * copying fails due to it existing anyway. 13436 */ 13437 PackageHelper.destroySdDir(cid); 13438 } 13439 13440 final String newMountPath = imcs.copyPackageToContainer( 13441 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13442 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13443 13444 if (newMountPath != null) { 13445 setMountPath(newMountPath); 13446 return PackageManager.INSTALL_SUCCEEDED; 13447 } else { 13448 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13449 } 13450 } 13451 13452 @Override 13453 String getCodePath() { 13454 return packagePath; 13455 } 13456 13457 @Override 13458 String getResourcePath() { 13459 return resourcePath; 13460 } 13461 13462 int doPreInstall(int status) { 13463 if (status != PackageManager.INSTALL_SUCCEEDED) { 13464 // Destroy container 13465 PackageHelper.destroySdDir(cid); 13466 } else { 13467 boolean mounted = PackageHelper.isContainerMounted(cid); 13468 if (!mounted) { 13469 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13470 Process.SYSTEM_UID); 13471 if (newMountPath != null) { 13472 setMountPath(newMountPath); 13473 } else { 13474 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13475 } 13476 } 13477 } 13478 return status; 13479 } 13480 13481 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13482 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13483 String newMountPath = null; 13484 if (PackageHelper.isContainerMounted(cid)) { 13485 // Unmount the container 13486 if (!PackageHelper.unMountSdDir(cid)) { 13487 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13488 return false; 13489 } 13490 } 13491 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13492 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13493 " which might be stale. Will try to clean up."); 13494 // Clean up the stale container and proceed to recreate. 13495 if (!PackageHelper.destroySdDir(newCacheId)) { 13496 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13497 return false; 13498 } 13499 // Successfully cleaned up stale container. Try to rename again. 13500 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13501 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13502 + " inspite of cleaning it up."); 13503 return false; 13504 } 13505 } 13506 if (!PackageHelper.isContainerMounted(newCacheId)) { 13507 Slog.w(TAG, "Mounting container " + newCacheId); 13508 newMountPath = PackageHelper.mountSdDir(newCacheId, 13509 getEncryptKey(), Process.SYSTEM_UID); 13510 } else { 13511 newMountPath = PackageHelper.getSdDir(newCacheId); 13512 } 13513 if (newMountPath == null) { 13514 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13515 return false; 13516 } 13517 Log.i(TAG, "Succesfully renamed " + cid + 13518 " to " + newCacheId + 13519 " at new path: " + newMountPath); 13520 cid = newCacheId; 13521 13522 final File beforeCodeFile = new File(packagePath); 13523 setMountPath(newMountPath); 13524 final File afterCodeFile = new File(packagePath); 13525 13526 // Reflect the rename in scanned details 13527 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13528 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13529 afterCodeFile, pkg.baseCodePath)); 13530 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13531 afterCodeFile, pkg.splitCodePaths)); 13532 13533 // Reflect the rename in app info 13534 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13535 pkg.setApplicationInfoCodePath(pkg.codePath); 13536 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13537 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13538 pkg.setApplicationInfoResourcePath(pkg.codePath); 13539 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13540 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13541 13542 return true; 13543 } 13544 13545 private void setMountPath(String mountPath) { 13546 final File mountFile = new File(mountPath); 13547 13548 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13549 if (monolithicFile.exists()) { 13550 packagePath = monolithicFile.getAbsolutePath(); 13551 if (isFwdLocked()) { 13552 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13553 } else { 13554 resourcePath = packagePath; 13555 } 13556 } else { 13557 packagePath = mountFile.getAbsolutePath(); 13558 resourcePath = packagePath; 13559 } 13560 } 13561 13562 int doPostInstall(int status, int uid) { 13563 if (status != PackageManager.INSTALL_SUCCEEDED) { 13564 cleanUp(); 13565 } else { 13566 final int groupOwner; 13567 final String protectedFile; 13568 if (isFwdLocked()) { 13569 groupOwner = UserHandle.getSharedAppGid(uid); 13570 protectedFile = RES_FILE_NAME; 13571 } else { 13572 groupOwner = -1; 13573 protectedFile = null; 13574 } 13575 13576 if (uid < Process.FIRST_APPLICATION_UID 13577 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13578 Slog.e(TAG, "Failed to finalize " + cid); 13579 PackageHelper.destroySdDir(cid); 13580 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13581 } 13582 13583 boolean mounted = PackageHelper.isContainerMounted(cid); 13584 if (!mounted) { 13585 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13586 } 13587 } 13588 return status; 13589 } 13590 13591 private void cleanUp() { 13592 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13593 13594 // Destroy secure container 13595 PackageHelper.destroySdDir(cid); 13596 } 13597 13598 private List<String> getAllCodePaths() { 13599 final File codeFile = new File(getCodePath()); 13600 if (codeFile != null && codeFile.exists()) { 13601 try { 13602 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13603 return pkg.getAllCodePaths(); 13604 } catch (PackageParserException e) { 13605 // Ignored; we tried our best 13606 } 13607 } 13608 return Collections.EMPTY_LIST; 13609 } 13610 13611 void cleanUpResourcesLI() { 13612 // Enumerate all code paths before deleting 13613 cleanUpResourcesLI(getAllCodePaths()); 13614 } 13615 13616 private void cleanUpResourcesLI(List<String> allCodePaths) { 13617 cleanUp(); 13618 removeDexFiles(allCodePaths, instructionSets); 13619 } 13620 13621 String getPackageName() { 13622 return getAsecPackageName(cid); 13623 } 13624 13625 boolean doPostDeleteLI(boolean delete) { 13626 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13627 final List<String> allCodePaths = getAllCodePaths(); 13628 boolean mounted = PackageHelper.isContainerMounted(cid); 13629 if (mounted) { 13630 // Unmount first 13631 if (PackageHelper.unMountSdDir(cid)) { 13632 mounted = false; 13633 } 13634 } 13635 if (!mounted && delete) { 13636 cleanUpResourcesLI(allCodePaths); 13637 } 13638 return !mounted; 13639 } 13640 13641 @Override 13642 int doPreCopy() { 13643 if (isFwdLocked()) { 13644 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13645 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13647 } 13648 } 13649 13650 return PackageManager.INSTALL_SUCCEEDED; 13651 } 13652 13653 @Override 13654 int doPostCopy(int uid) { 13655 if (isFwdLocked()) { 13656 if (uid < Process.FIRST_APPLICATION_UID 13657 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13658 RES_FILE_NAME)) { 13659 Slog.e(TAG, "Failed to finalize " + cid); 13660 PackageHelper.destroySdDir(cid); 13661 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13662 } 13663 } 13664 13665 return PackageManager.INSTALL_SUCCEEDED; 13666 } 13667 } 13668 13669 /** 13670 * Logic to handle movement of existing installed applications. 13671 */ 13672 class MoveInstallArgs extends InstallArgs { 13673 private File codeFile; 13674 private File resourceFile; 13675 13676 /** New install */ 13677 MoveInstallArgs(InstallParams params) { 13678 super(params.origin, params.move, params.observer, params.installFlags, 13679 params.installerPackageName, params.volumeUuid, 13680 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13681 params.grantedRuntimePermissions, 13682 params.traceMethod, params.traceCookie, params.certificates); 13683 } 13684 13685 int copyApk(IMediaContainerService imcs, boolean temp) { 13686 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13687 + move.fromUuid + " to " + move.toUuid); 13688 synchronized (mInstaller) { 13689 try { 13690 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13691 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13692 } catch (InstallerException e) { 13693 Slog.w(TAG, "Failed to move app", e); 13694 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13695 } 13696 } 13697 13698 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13699 resourceFile = codeFile; 13700 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13701 13702 return PackageManager.INSTALL_SUCCEEDED; 13703 } 13704 13705 int doPreInstall(int status) { 13706 if (status != PackageManager.INSTALL_SUCCEEDED) { 13707 cleanUp(move.toUuid); 13708 } 13709 return status; 13710 } 13711 13712 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13713 if (status != PackageManager.INSTALL_SUCCEEDED) { 13714 cleanUp(move.toUuid); 13715 return false; 13716 } 13717 13718 // Reflect the move in app info 13719 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13720 pkg.setApplicationInfoCodePath(pkg.codePath); 13721 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13722 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13723 pkg.setApplicationInfoResourcePath(pkg.codePath); 13724 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13725 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13726 13727 return true; 13728 } 13729 13730 int doPostInstall(int status, int uid) { 13731 if (status == PackageManager.INSTALL_SUCCEEDED) { 13732 cleanUp(move.fromUuid); 13733 } else { 13734 cleanUp(move.toUuid); 13735 } 13736 return status; 13737 } 13738 13739 @Override 13740 String getCodePath() { 13741 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13742 } 13743 13744 @Override 13745 String getResourcePath() { 13746 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13747 } 13748 13749 private boolean cleanUp(String volumeUuid) { 13750 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13751 move.dataAppName); 13752 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13753 final int[] userIds = sUserManager.getUserIds(); 13754 synchronized (mInstallLock) { 13755 // Clean up both app data and code 13756 // All package moves are frozen until finished 13757 for (int userId : userIds) { 13758 try { 13759 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13760 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13761 } catch (InstallerException e) { 13762 Slog.w(TAG, String.valueOf(e)); 13763 } 13764 } 13765 removeCodePathLI(codeFile); 13766 } 13767 return true; 13768 } 13769 13770 void cleanUpResourcesLI() { 13771 throw new UnsupportedOperationException(); 13772 } 13773 13774 boolean doPostDeleteLI(boolean delete) { 13775 throw new UnsupportedOperationException(); 13776 } 13777 } 13778 13779 static String getAsecPackageName(String packageCid) { 13780 int idx = packageCid.lastIndexOf("-"); 13781 if (idx == -1) { 13782 return packageCid; 13783 } 13784 return packageCid.substring(0, idx); 13785 } 13786 13787 // Utility method used to create code paths based on package name and available index. 13788 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13789 String idxStr = ""; 13790 int idx = 1; 13791 // Fall back to default value of idx=1 if prefix is not 13792 // part of oldCodePath 13793 if (oldCodePath != null) { 13794 String subStr = oldCodePath; 13795 // Drop the suffix right away 13796 if (suffix != null && subStr.endsWith(suffix)) { 13797 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13798 } 13799 // If oldCodePath already contains prefix find out the 13800 // ending index to either increment or decrement. 13801 int sidx = subStr.lastIndexOf(prefix); 13802 if (sidx != -1) { 13803 subStr = subStr.substring(sidx + prefix.length()); 13804 if (subStr != null) { 13805 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13806 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13807 } 13808 try { 13809 idx = Integer.parseInt(subStr); 13810 if (idx <= 1) { 13811 idx++; 13812 } else { 13813 idx--; 13814 } 13815 } catch(NumberFormatException e) { 13816 } 13817 } 13818 } 13819 } 13820 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13821 return prefix + idxStr; 13822 } 13823 13824 private File getNextCodePath(File targetDir, String packageName) { 13825 int suffix = 1; 13826 File result; 13827 do { 13828 result = new File(targetDir, packageName + "-" + suffix); 13829 suffix++; 13830 } while (result.exists()); 13831 return result; 13832 } 13833 13834 // Utility method that returns the relative package path with respect 13835 // to the installation directory. Like say for /data/data/com.test-1.apk 13836 // string com.test-1 is returned. 13837 static String deriveCodePathName(String codePath) { 13838 if (codePath == null) { 13839 return null; 13840 } 13841 final File codeFile = new File(codePath); 13842 final String name = codeFile.getName(); 13843 if (codeFile.isDirectory()) { 13844 return name; 13845 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13846 final int lastDot = name.lastIndexOf('.'); 13847 return name.substring(0, lastDot); 13848 } else { 13849 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13850 return null; 13851 } 13852 } 13853 13854 static class PackageInstalledInfo { 13855 String name; 13856 int uid; 13857 // The set of users that originally had this package installed. 13858 int[] origUsers; 13859 // The set of users that now have this package installed. 13860 int[] newUsers; 13861 PackageParser.Package pkg; 13862 int returnCode; 13863 String returnMsg; 13864 PackageRemovedInfo removedInfo; 13865 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13866 13867 public void setError(int code, String msg) { 13868 setReturnCode(code); 13869 setReturnMessage(msg); 13870 Slog.w(TAG, msg); 13871 } 13872 13873 public void setError(String msg, PackageParserException e) { 13874 setReturnCode(e.error); 13875 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13876 Slog.w(TAG, msg, e); 13877 } 13878 13879 public void setError(String msg, PackageManagerException e) { 13880 returnCode = e.error; 13881 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13882 Slog.w(TAG, msg, e); 13883 } 13884 13885 public void setReturnCode(int returnCode) { 13886 this.returnCode = returnCode; 13887 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13888 for (int i = 0; i < childCount; i++) { 13889 addedChildPackages.valueAt(i).returnCode = returnCode; 13890 } 13891 } 13892 13893 private void setReturnMessage(String returnMsg) { 13894 this.returnMsg = returnMsg; 13895 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13896 for (int i = 0; i < childCount; i++) { 13897 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13898 } 13899 } 13900 13901 // In some error cases we want to convey more info back to the observer 13902 String origPackage; 13903 String origPermission; 13904 } 13905 13906 /* 13907 * Install a non-existing package. 13908 */ 13909 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13910 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13911 PackageInstalledInfo res) { 13912 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13913 13914 // Remember this for later, in case we need to rollback this install 13915 String pkgName = pkg.packageName; 13916 13917 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13918 13919 synchronized(mPackages) { 13920 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13921 // A package with the same name is already installed, though 13922 // it has been renamed to an older name. The package we 13923 // are trying to install should be installed as an update to 13924 // the existing one, but that has not been requested, so bail. 13925 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13926 + " without first uninstalling package running as " 13927 + mSettings.mRenamedPackages.get(pkgName)); 13928 return; 13929 } 13930 if (mPackages.containsKey(pkgName)) { 13931 // Don't allow installation over an existing package with the same name. 13932 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13933 + " without first uninstalling."); 13934 return; 13935 } 13936 } 13937 13938 try { 13939 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13940 System.currentTimeMillis(), user); 13941 13942 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13943 13944 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13945 prepareAppDataAfterInstallLIF(newPackage); 13946 13947 } else { 13948 // Remove package from internal structures, but keep around any 13949 // data that might have already existed 13950 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13951 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13952 } 13953 } catch (PackageManagerException e) { 13954 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13955 } 13956 13957 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13958 } 13959 13960 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13961 // Can't rotate keys during boot or if sharedUser. 13962 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13963 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13964 return false; 13965 } 13966 // app is using upgradeKeySets; make sure all are valid 13967 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13968 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13969 for (int i = 0; i < upgradeKeySets.length; i++) { 13970 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13971 Slog.wtf(TAG, "Package " 13972 + (oldPs.name != null ? oldPs.name : "<null>") 13973 + " contains upgrade-key-set reference to unknown key-set: " 13974 + upgradeKeySets[i] 13975 + " reverting to signatures check."); 13976 return false; 13977 } 13978 } 13979 return true; 13980 } 13981 13982 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13983 // Upgrade keysets are being used. Determine if new package has a superset of the 13984 // required keys. 13985 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13986 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13987 for (int i = 0; i < upgradeKeySets.length; i++) { 13988 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13989 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13990 return true; 13991 } 13992 } 13993 return false; 13994 } 13995 13996 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13997 try (DigestInputStream digestStream = 13998 new DigestInputStream(new FileInputStream(file), digest)) { 13999 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14000 } 14001 } 14002 14003 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14004 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14005 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14006 14007 final PackageParser.Package oldPackage; 14008 final String pkgName = pkg.packageName; 14009 final int[] allUsers; 14010 final int[] installedUsers; 14011 14012 synchronized(mPackages) { 14013 oldPackage = mPackages.get(pkgName); 14014 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14015 14016 // don't allow upgrade to target a release SDK from a pre-release SDK 14017 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14018 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14019 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14020 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14021 if (oldTargetsPreRelease 14022 && !newTargetsPreRelease 14023 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14024 Slog.w(TAG, "Can't install package targeting released sdk"); 14025 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14026 return; 14027 } 14028 14029 // don't allow an upgrade from full to ephemeral 14030 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14031 if (isEphemeral && !oldIsEphemeral) { 14032 // can't downgrade from full to ephemeral 14033 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14034 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14035 return; 14036 } 14037 14038 // verify signatures are valid 14039 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14040 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14041 if (!checkUpgradeKeySetLP(ps, pkg)) { 14042 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14043 "New package not signed by keys specified by upgrade-keysets: " 14044 + pkgName); 14045 return; 14046 } 14047 } else { 14048 // default to original signature matching 14049 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14050 != PackageManager.SIGNATURE_MATCH) { 14051 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14052 "New package has a different signature: " + pkgName); 14053 return; 14054 } 14055 } 14056 14057 // don't allow a system upgrade unless the upgrade hash matches 14058 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14059 byte[] digestBytes = null; 14060 try { 14061 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14062 updateDigest(digest, new File(pkg.baseCodePath)); 14063 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14064 for (String path : pkg.splitCodePaths) { 14065 updateDigest(digest, new File(path)); 14066 } 14067 } 14068 digestBytes = digest.digest(); 14069 } catch (NoSuchAlgorithmException | IOException e) { 14070 res.setError(INSTALL_FAILED_INVALID_APK, 14071 "Could not compute hash: " + pkgName); 14072 return; 14073 } 14074 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14075 res.setError(INSTALL_FAILED_INVALID_APK, 14076 "New package fails restrict-update check: " + pkgName); 14077 return; 14078 } 14079 // retain upgrade restriction 14080 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14081 } 14082 14083 // Check for shared user id changes 14084 String invalidPackageName = 14085 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14086 if (invalidPackageName != null) { 14087 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14088 "Package " + invalidPackageName + " tried to change user " 14089 + oldPackage.mSharedUserId); 14090 return; 14091 } 14092 14093 // In case of rollback, remember per-user/profile install state 14094 allUsers = sUserManager.getUserIds(); 14095 installedUsers = ps.queryInstalledUsers(allUsers, true); 14096 } 14097 14098 // Update what is removed 14099 res.removedInfo = new PackageRemovedInfo(); 14100 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14101 res.removedInfo.removedPackage = oldPackage.packageName; 14102 res.removedInfo.isUpdate = true; 14103 res.removedInfo.origUsers = installedUsers; 14104 final int childCount = (oldPackage.childPackages != null) 14105 ? oldPackage.childPackages.size() : 0; 14106 for (int i = 0; i < childCount; i++) { 14107 boolean childPackageUpdated = false; 14108 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14109 if (res.addedChildPackages != null) { 14110 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14111 if (childRes != null) { 14112 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14113 childRes.removedInfo.removedPackage = childPkg.packageName; 14114 childRes.removedInfo.isUpdate = true; 14115 childPackageUpdated = true; 14116 } 14117 } 14118 if (!childPackageUpdated) { 14119 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14120 childRemovedRes.removedPackage = childPkg.packageName; 14121 childRemovedRes.isUpdate = false; 14122 childRemovedRes.dataRemoved = true; 14123 synchronized (mPackages) { 14124 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14125 if (childPs != null) { 14126 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14127 } 14128 } 14129 if (res.removedInfo.removedChildPackages == null) { 14130 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14131 } 14132 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14133 } 14134 } 14135 14136 boolean sysPkg = (isSystemApp(oldPackage)); 14137 if (sysPkg) { 14138 // Set the system/privileged flags as needed 14139 final boolean privileged = 14140 (oldPackage.applicationInfo.privateFlags 14141 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14142 final int systemPolicyFlags = policyFlags 14143 | PackageParser.PARSE_IS_SYSTEM 14144 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14145 14146 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14147 user, allUsers, installerPackageName, res); 14148 } else { 14149 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14150 user, allUsers, installerPackageName, res); 14151 } 14152 } 14153 14154 public List<String> getPreviousCodePaths(String packageName) { 14155 final PackageSetting ps = mSettings.mPackages.get(packageName); 14156 final List<String> result = new ArrayList<String>(); 14157 if (ps != null && ps.oldCodePaths != null) { 14158 result.addAll(ps.oldCodePaths); 14159 } 14160 return result; 14161 } 14162 14163 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14164 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14165 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14166 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14167 + deletedPackage); 14168 14169 String pkgName = deletedPackage.packageName; 14170 boolean deletedPkg = true; 14171 boolean addedPkg = false; 14172 boolean updatedSettings = false; 14173 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14174 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14175 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14176 14177 final long origUpdateTime = (pkg.mExtras != null) 14178 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14179 14180 // First delete the existing package while retaining the data directory 14181 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14182 res.removedInfo, true, pkg)) { 14183 // If the existing package wasn't successfully deleted 14184 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14185 deletedPkg = false; 14186 } else { 14187 // Successfully deleted the old package; proceed with replace. 14188 14189 // If deleted package lived in a container, give users a chance to 14190 // relinquish resources before killing. 14191 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14192 if (DEBUG_INSTALL) { 14193 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14194 } 14195 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14196 final ArrayList<String> pkgList = new ArrayList<String>(1); 14197 pkgList.add(deletedPackage.applicationInfo.packageName); 14198 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14199 } 14200 14201 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14202 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14203 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14204 14205 try { 14206 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14207 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14208 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14209 14210 // Update the in-memory copy of the previous code paths. 14211 PackageSetting ps = mSettings.mPackages.get(pkgName); 14212 if (!killApp) { 14213 if (ps.oldCodePaths == null) { 14214 ps.oldCodePaths = new ArraySet<>(); 14215 } 14216 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14217 if (deletedPackage.splitCodePaths != null) { 14218 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14219 } 14220 } else { 14221 ps.oldCodePaths = null; 14222 } 14223 if (ps.childPackageNames != null) { 14224 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14225 final String childPkgName = ps.childPackageNames.get(i); 14226 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14227 childPs.oldCodePaths = ps.oldCodePaths; 14228 } 14229 } 14230 prepareAppDataAfterInstallLIF(newPackage); 14231 addedPkg = true; 14232 } catch (PackageManagerException e) { 14233 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14234 } 14235 } 14236 14237 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14238 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14239 14240 // Revert all internal state mutations and added folders for the failed install 14241 if (addedPkg) { 14242 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14243 res.removedInfo, true, null); 14244 } 14245 14246 // Restore the old package 14247 if (deletedPkg) { 14248 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14249 File restoreFile = new File(deletedPackage.codePath); 14250 // Parse old package 14251 boolean oldExternal = isExternal(deletedPackage); 14252 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14253 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14254 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14255 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14256 try { 14257 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14258 null); 14259 } catch (PackageManagerException e) { 14260 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14261 + e.getMessage()); 14262 return; 14263 } 14264 14265 synchronized (mPackages) { 14266 // Ensure the installer package name up to date 14267 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14268 14269 // Update permissions for restored package 14270 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14271 14272 mSettings.writeLPr(); 14273 } 14274 14275 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14276 } 14277 } else { 14278 synchronized (mPackages) { 14279 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14280 if (ps != null) { 14281 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14282 if (res.removedInfo.removedChildPackages != null) { 14283 final int childCount = res.removedInfo.removedChildPackages.size(); 14284 // Iterate in reverse as we may modify the collection 14285 for (int i = childCount - 1; i >= 0; i--) { 14286 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14287 if (res.addedChildPackages.containsKey(childPackageName)) { 14288 res.removedInfo.removedChildPackages.removeAt(i); 14289 } else { 14290 PackageRemovedInfo childInfo = res.removedInfo 14291 .removedChildPackages.valueAt(i); 14292 childInfo.removedForAllUsers = mPackages.get( 14293 childInfo.removedPackage) == null; 14294 } 14295 } 14296 } 14297 } 14298 } 14299 } 14300 } 14301 14302 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14303 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14304 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14305 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14306 + ", old=" + deletedPackage); 14307 14308 final boolean disabledSystem; 14309 14310 // Remove existing system package 14311 removePackageLI(deletedPackage, true); 14312 14313 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14314 if (!disabledSystem) { 14315 // We didn't need to disable the .apk as a current system package, 14316 // which means we are replacing another update that is already 14317 // installed. We need to make sure to delete the older one's .apk. 14318 res.removedInfo.args = createInstallArgsForExisting(0, 14319 deletedPackage.applicationInfo.getCodePath(), 14320 deletedPackage.applicationInfo.getResourcePath(), 14321 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14322 } else { 14323 res.removedInfo.args = null; 14324 } 14325 14326 // Successfully disabled the old package. Now proceed with re-installation 14327 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14328 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14329 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14330 14331 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14332 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14333 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14334 14335 PackageParser.Package newPackage = null; 14336 try { 14337 // Add the package to the internal data structures 14338 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14339 14340 // Set the update and install times 14341 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14342 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14343 System.currentTimeMillis()); 14344 14345 // Update the package dynamic state if succeeded 14346 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14347 // Now that the install succeeded make sure we remove data 14348 // directories for any child package the update removed. 14349 final int deletedChildCount = (deletedPackage.childPackages != null) 14350 ? deletedPackage.childPackages.size() : 0; 14351 final int newChildCount = (newPackage.childPackages != null) 14352 ? newPackage.childPackages.size() : 0; 14353 for (int i = 0; i < deletedChildCount; i++) { 14354 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14355 boolean childPackageDeleted = true; 14356 for (int j = 0; j < newChildCount; j++) { 14357 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14358 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14359 childPackageDeleted = false; 14360 break; 14361 } 14362 } 14363 if (childPackageDeleted) { 14364 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14365 deletedChildPkg.packageName); 14366 if (ps != null && res.removedInfo.removedChildPackages != null) { 14367 PackageRemovedInfo removedChildRes = res.removedInfo 14368 .removedChildPackages.get(deletedChildPkg.packageName); 14369 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14370 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14371 } 14372 } 14373 } 14374 14375 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14376 prepareAppDataAfterInstallLIF(newPackage); 14377 } 14378 } catch (PackageManagerException e) { 14379 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14380 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14381 } 14382 14383 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14384 // Re installation failed. Restore old information 14385 // Remove new pkg information 14386 if (newPackage != null) { 14387 removeInstalledPackageLI(newPackage, true); 14388 } 14389 // Add back the old system package 14390 try { 14391 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14392 } catch (PackageManagerException e) { 14393 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14394 } 14395 14396 synchronized (mPackages) { 14397 if (disabledSystem) { 14398 enableSystemPackageLPw(deletedPackage); 14399 } 14400 14401 // Ensure the installer package name up to date 14402 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14403 14404 // Update permissions for restored package 14405 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14406 14407 mSettings.writeLPr(); 14408 } 14409 14410 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14411 + " after failed upgrade"); 14412 } 14413 } 14414 14415 /** 14416 * Checks whether the parent or any of the child packages have a change shared 14417 * user. For a package to be a valid update the shred users of the parent and 14418 * the children should match. We may later support changing child shared users. 14419 * @param oldPkg The updated package. 14420 * @param newPkg The update package. 14421 * @return The shared user that change between the versions. 14422 */ 14423 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14424 PackageParser.Package newPkg) { 14425 // Check parent shared user 14426 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14427 return newPkg.packageName; 14428 } 14429 // Check child shared users 14430 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14431 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14432 for (int i = 0; i < newChildCount; i++) { 14433 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14434 // If this child was present, did it have the same shared user? 14435 for (int j = 0; j < oldChildCount; j++) { 14436 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14437 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14438 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14439 return newChildPkg.packageName; 14440 } 14441 } 14442 } 14443 return null; 14444 } 14445 14446 private void removeNativeBinariesLI(PackageSetting ps) { 14447 // Remove the lib path for the parent package 14448 if (ps != null) { 14449 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14450 // Remove the lib path for the child packages 14451 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14452 for (int i = 0; i < childCount; i++) { 14453 PackageSetting childPs = null; 14454 synchronized (mPackages) { 14455 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14456 } 14457 if (childPs != null) { 14458 NativeLibraryHelper.removeNativeBinariesLI(childPs 14459 .legacyNativeLibraryPathString); 14460 } 14461 } 14462 } 14463 } 14464 14465 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14466 // Enable the parent package 14467 mSettings.enableSystemPackageLPw(pkg.packageName); 14468 // Enable the child packages 14469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14470 for (int i = 0; i < childCount; i++) { 14471 PackageParser.Package childPkg = pkg.childPackages.get(i); 14472 mSettings.enableSystemPackageLPw(childPkg.packageName); 14473 } 14474 } 14475 14476 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14477 PackageParser.Package newPkg) { 14478 // Disable the parent package (parent always replaced) 14479 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14480 // Disable the child packages 14481 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14482 for (int i = 0; i < childCount; i++) { 14483 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14484 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14485 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14486 } 14487 return disabled; 14488 } 14489 14490 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14491 String installerPackageName) { 14492 // Enable the parent package 14493 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14494 // Enable the child packages 14495 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14496 for (int i = 0; i < childCount; i++) { 14497 PackageParser.Package childPkg = pkg.childPackages.get(i); 14498 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14499 } 14500 } 14501 14502 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14503 // Collect all used permissions in the UID 14504 ArraySet<String> usedPermissions = new ArraySet<>(); 14505 final int packageCount = su.packages.size(); 14506 for (int i = 0; i < packageCount; i++) { 14507 PackageSetting ps = su.packages.valueAt(i); 14508 if (ps.pkg == null) { 14509 continue; 14510 } 14511 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14512 for (int j = 0; j < requestedPermCount; j++) { 14513 String permission = ps.pkg.requestedPermissions.get(j); 14514 BasePermission bp = mSettings.mPermissions.get(permission); 14515 if (bp != null) { 14516 usedPermissions.add(permission); 14517 } 14518 } 14519 } 14520 14521 PermissionsState permissionsState = su.getPermissionsState(); 14522 // Prune install permissions 14523 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14524 final int installPermCount = installPermStates.size(); 14525 for (int i = installPermCount - 1; i >= 0; i--) { 14526 PermissionState permissionState = installPermStates.get(i); 14527 if (!usedPermissions.contains(permissionState.getName())) { 14528 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14529 if (bp != null) { 14530 permissionsState.revokeInstallPermission(bp); 14531 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14532 PackageManager.MASK_PERMISSION_FLAGS, 0); 14533 } 14534 } 14535 } 14536 14537 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14538 14539 // Prune runtime permissions 14540 for (int userId : allUserIds) { 14541 List<PermissionState> runtimePermStates = permissionsState 14542 .getRuntimePermissionStates(userId); 14543 final int runtimePermCount = runtimePermStates.size(); 14544 for (int i = runtimePermCount - 1; i >= 0; i--) { 14545 PermissionState permissionState = runtimePermStates.get(i); 14546 if (!usedPermissions.contains(permissionState.getName())) { 14547 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14548 if (bp != null) { 14549 permissionsState.revokeRuntimePermission(bp, userId); 14550 permissionsState.updatePermissionFlags(bp, userId, 14551 PackageManager.MASK_PERMISSION_FLAGS, 0); 14552 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14553 runtimePermissionChangedUserIds, userId); 14554 } 14555 } 14556 } 14557 } 14558 14559 return runtimePermissionChangedUserIds; 14560 } 14561 14562 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14563 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14564 // Update the parent package setting 14565 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14566 res, user); 14567 // Update the child packages setting 14568 final int childCount = (newPackage.childPackages != null) 14569 ? newPackage.childPackages.size() : 0; 14570 for (int i = 0; i < childCount; i++) { 14571 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14572 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14573 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14574 childRes.origUsers, childRes, user); 14575 } 14576 } 14577 14578 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14579 String installerPackageName, int[] allUsers, int[] installedForUsers, 14580 PackageInstalledInfo res, UserHandle user) { 14581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14582 14583 String pkgName = newPackage.packageName; 14584 synchronized (mPackages) { 14585 //write settings. the installStatus will be incomplete at this stage. 14586 //note that the new package setting would have already been 14587 //added to mPackages. It hasn't been persisted yet. 14588 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14590 mSettings.writeLPr(); 14591 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14592 } 14593 14594 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14595 synchronized (mPackages) { 14596 updatePermissionsLPw(newPackage.packageName, newPackage, 14597 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14598 ? UPDATE_PERMISSIONS_ALL : 0)); 14599 // For system-bundled packages, we assume that installing an upgraded version 14600 // of the package implies that the user actually wants to run that new code, 14601 // so we enable the package. 14602 PackageSetting ps = mSettings.mPackages.get(pkgName); 14603 final int userId = user.getIdentifier(); 14604 if (ps != null) { 14605 if (isSystemApp(newPackage)) { 14606 if (DEBUG_INSTALL) { 14607 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14608 } 14609 // Enable system package for requested users 14610 if (res.origUsers != null) { 14611 for (int origUserId : res.origUsers) { 14612 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14613 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14614 origUserId, installerPackageName); 14615 } 14616 } 14617 } 14618 // Also convey the prior install/uninstall state 14619 if (allUsers != null && installedForUsers != null) { 14620 for (int currentUserId : allUsers) { 14621 final boolean installed = ArrayUtils.contains( 14622 installedForUsers, currentUserId); 14623 if (DEBUG_INSTALL) { 14624 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14625 } 14626 ps.setInstalled(installed, currentUserId); 14627 } 14628 // these install state changes will be persisted in the 14629 // upcoming call to mSettings.writeLPr(). 14630 } 14631 } 14632 // It's implied that when a user requests installation, they want the app to be 14633 // installed and enabled. 14634 if (userId != UserHandle.USER_ALL) { 14635 ps.setInstalled(true, userId); 14636 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14637 } 14638 } 14639 res.name = pkgName; 14640 res.uid = newPackage.applicationInfo.uid; 14641 res.pkg = newPackage; 14642 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14643 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14644 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14645 //to update install status 14646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14647 mSettings.writeLPr(); 14648 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14649 } 14650 14651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14652 } 14653 14654 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14655 try { 14656 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14657 installPackageLI(args, res); 14658 } finally { 14659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14660 } 14661 } 14662 14663 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14664 final int installFlags = args.installFlags; 14665 final String installerPackageName = args.installerPackageName; 14666 final String volumeUuid = args.volumeUuid; 14667 final File tmpPackageFile = new File(args.getCodePath()); 14668 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14669 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14670 || (args.volumeUuid != null)); 14671 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14672 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14673 boolean replace = false; 14674 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14675 if (args.move != null) { 14676 // moving a complete application; perform an initial scan on the new install location 14677 scanFlags |= SCAN_INITIAL; 14678 } 14679 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14680 scanFlags |= SCAN_DONT_KILL_APP; 14681 } 14682 14683 // Result object to be returned 14684 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14685 14686 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14687 14688 // Sanity check 14689 if (ephemeral && (forwardLocked || onExternal)) { 14690 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14691 + " external=" + onExternal); 14692 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14693 return; 14694 } 14695 14696 // Retrieve PackageSettings and parse package 14697 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14698 | PackageParser.PARSE_ENFORCE_CODE 14699 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14700 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14701 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14702 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14703 PackageParser pp = new PackageParser(); 14704 pp.setSeparateProcesses(mSeparateProcesses); 14705 pp.setDisplayMetrics(mMetrics); 14706 14707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14708 final PackageParser.Package pkg; 14709 try { 14710 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14711 } catch (PackageParserException e) { 14712 res.setError("Failed parse during installPackageLI", e); 14713 return; 14714 } finally { 14715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14716 } 14717 14718 // If we are installing a clustered package add results for the children 14719 if (pkg.childPackages != null) { 14720 synchronized (mPackages) { 14721 final int childCount = pkg.childPackages.size(); 14722 for (int i = 0; i < childCount; i++) { 14723 PackageParser.Package childPkg = pkg.childPackages.get(i); 14724 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14725 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14726 childRes.pkg = childPkg; 14727 childRes.name = childPkg.packageName; 14728 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14729 if (childPs != null) { 14730 childRes.origUsers = childPs.queryInstalledUsers( 14731 sUserManager.getUserIds(), true); 14732 } 14733 if ((mPackages.containsKey(childPkg.packageName))) { 14734 childRes.removedInfo = new PackageRemovedInfo(); 14735 childRes.removedInfo.removedPackage = childPkg.packageName; 14736 } 14737 if (res.addedChildPackages == null) { 14738 res.addedChildPackages = new ArrayMap<>(); 14739 } 14740 res.addedChildPackages.put(childPkg.packageName, childRes); 14741 } 14742 } 14743 } 14744 14745 // If package doesn't declare API override, mark that we have an install 14746 // time CPU ABI override. 14747 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14748 pkg.cpuAbiOverride = args.abiOverride; 14749 } 14750 14751 String pkgName = res.name = pkg.packageName; 14752 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14753 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14754 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14755 return; 14756 } 14757 } 14758 14759 try { 14760 // either use what we've been given or parse directly from the APK 14761 if (args.certificates != null) { 14762 try { 14763 PackageParser.populateCertificates(pkg, args.certificates); 14764 } catch (PackageParserException e) { 14765 // there was something wrong with the certificates we were given; 14766 // try to pull them from the APK 14767 PackageParser.collectCertificates(pkg, parseFlags); 14768 } 14769 } else { 14770 PackageParser.collectCertificates(pkg, parseFlags); 14771 } 14772 } catch (PackageParserException e) { 14773 res.setError("Failed collect during installPackageLI", e); 14774 return; 14775 } 14776 14777 // Get rid of all references to package scan path via parser. 14778 pp = null; 14779 String oldCodePath = null; 14780 boolean systemApp = false; 14781 synchronized (mPackages) { 14782 // Check if installing already existing package 14783 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14784 String oldName = mSettings.mRenamedPackages.get(pkgName); 14785 if (pkg.mOriginalPackages != null 14786 && pkg.mOriginalPackages.contains(oldName) 14787 && mPackages.containsKey(oldName)) { 14788 // This package is derived from an original package, 14789 // and this device has been updating from that original 14790 // name. We must continue using the original name, so 14791 // rename the new package here. 14792 pkg.setPackageName(oldName); 14793 pkgName = pkg.packageName; 14794 replace = true; 14795 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14796 + oldName + " pkgName=" + pkgName); 14797 } else if (mPackages.containsKey(pkgName)) { 14798 // This package, under its official name, already exists 14799 // on the device; we should replace it. 14800 replace = true; 14801 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14802 } 14803 14804 // Child packages are installed through the parent package 14805 if (pkg.parentPackage != null) { 14806 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14807 "Package " + pkg.packageName + " is child of package " 14808 + pkg.parentPackage.parentPackage + ". Child packages " 14809 + "can be updated only through the parent package."); 14810 return; 14811 } 14812 14813 if (replace) { 14814 // Prevent apps opting out from runtime permissions 14815 PackageParser.Package oldPackage = mPackages.get(pkgName); 14816 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14817 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14818 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14819 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14820 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14821 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14822 + " doesn't support runtime permissions but the old" 14823 + " target SDK " + oldTargetSdk + " does."); 14824 return; 14825 } 14826 14827 // Prevent installing of child packages 14828 if (oldPackage.parentPackage != null) { 14829 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14830 "Package " + pkg.packageName + " is child of package " 14831 + oldPackage.parentPackage + ". Child packages " 14832 + "can be updated only through the parent package."); 14833 return; 14834 } 14835 } 14836 } 14837 14838 PackageSetting ps = mSettings.mPackages.get(pkgName); 14839 if (ps != null) { 14840 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14841 14842 // Quick sanity check that we're signed correctly if updating; 14843 // we'll check this again later when scanning, but we want to 14844 // bail early here before tripping over redefined permissions. 14845 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14846 if (!checkUpgradeKeySetLP(ps, pkg)) { 14847 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14848 + pkg.packageName + " upgrade keys do not match the " 14849 + "previously installed version"); 14850 return; 14851 } 14852 } else { 14853 try { 14854 verifySignaturesLP(ps, pkg); 14855 } catch (PackageManagerException e) { 14856 res.setError(e.error, e.getMessage()); 14857 return; 14858 } 14859 } 14860 14861 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14862 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14863 systemApp = (ps.pkg.applicationInfo.flags & 14864 ApplicationInfo.FLAG_SYSTEM) != 0; 14865 } 14866 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14867 } 14868 14869 // Check whether the newly-scanned package wants to define an already-defined perm 14870 int N = pkg.permissions.size(); 14871 for (int i = N-1; i >= 0; i--) { 14872 PackageParser.Permission perm = pkg.permissions.get(i); 14873 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14874 if (bp != null) { 14875 // If the defining package is signed with our cert, it's okay. This 14876 // also includes the "updating the same package" case, of course. 14877 // "updating same package" could also involve key-rotation. 14878 final boolean sigsOk; 14879 if (bp.sourcePackage.equals(pkg.packageName) 14880 && (bp.packageSetting instanceof PackageSetting) 14881 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14882 scanFlags))) { 14883 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14884 } else { 14885 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14886 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14887 } 14888 if (!sigsOk) { 14889 // If the owning package is the system itself, we log but allow 14890 // install to proceed; we fail the install on all other permission 14891 // redefinitions. 14892 if (!bp.sourcePackage.equals("android")) { 14893 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14894 + pkg.packageName + " attempting to redeclare permission " 14895 + perm.info.name + " already owned by " + bp.sourcePackage); 14896 res.origPermission = perm.info.name; 14897 res.origPackage = bp.sourcePackage; 14898 return; 14899 } else { 14900 Slog.w(TAG, "Package " + pkg.packageName 14901 + " attempting to redeclare system permission " 14902 + perm.info.name + "; ignoring new declaration"); 14903 pkg.permissions.remove(i); 14904 } 14905 } 14906 } 14907 } 14908 } 14909 14910 if (systemApp) { 14911 if (onExternal) { 14912 // Abort update; system app can't be replaced with app on sdcard 14913 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14914 "Cannot install updates to system apps on sdcard"); 14915 return; 14916 } else if (ephemeral) { 14917 // Abort update; system app can't be replaced with an ephemeral app 14918 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14919 "Cannot update a system app with an ephemeral app"); 14920 return; 14921 } 14922 } 14923 14924 if (args.move != null) { 14925 // We did an in-place move, so dex is ready to roll 14926 scanFlags |= SCAN_NO_DEX; 14927 scanFlags |= SCAN_MOVE; 14928 14929 synchronized (mPackages) { 14930 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14931 if (ps == null) { 14932 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14933 "Missing settings for moved package " + pkgName); 14934 } 14935 14936 // We moved the entire application as-is, so bring over the 14937 // previously derived ABI information. 14938 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14939 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14940 } 14941 14942 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14943 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14944 scanFlags |= SCAN_NO_DEX; 14945 14946 try { 14947 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14948 args.abiOverride : pkg.cpuAbiOverride); 14949 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14950 true /* extract libs */); 14951 } catch (PackageManagerException pme) { 14952 Slog.e(TAG, "Error deriving application ABI", pme); 14953 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14954 return; 14955 } 14956 14957 // Shared libraries for the package need to be updated. 14958 synchronized (mPackages) { 14959 try { 14960 updateSharedLibrariesLPw(pkg, null); 14961 } catch (PackageManagerException e) { 14962 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14963 } 14964 } 14965 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14966 // Do not run PackageDexOptimizer through the local performDexOpt 14967 // method because `pkg` is not in `mPackages` yet. 14968 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14969 null /* instructionSets */, false /* checkProfiles */, 14970 getCompilerFilterForReason(REASON_INSTALL)); 14971 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14972 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14973 String msg = "Extracting package failed for " + pkgName; 14974 res.setError(INSTALL_FAILED_DEXOPT, msg); 14975 return; 14976 } 14977 14978 // Notify BackgroundDexOptService that the package has been changed. 14979 // If this is an update of a package which used to fail to compile, 14980 // BDOS will remove it from its blacklist. 14981 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14982 } 14983 14984 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14985 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14986 return; 14987 } 14988 14989 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14990 14991 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14992 "installPackageLI")) { 14993 if (replace) { 14994 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14995 installerPackageName, res); 14996 } else { 14997 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14998 args.user, installerPackageName, volumeUuid, res); 14999 } 15000 } 15001 synchronized (mPackages) { 15002 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15003 if (ps != null) { 15004 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15005 } 15006 15007 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15008 for (int i = 0; i < childCount; i++) { 15009 PackageParser.Package childPkg = pkg.childPackages.get(i); 15010 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15011 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15012 if (childPs != null) { 15013 childRes.newUsers = childPs.queryInstalledUsers( 15014 sUserManager.getUserIds(), true); 15015 } 15016 } 15017 } 15018 } 15019 15020 private void startIntentFilterVerifications(int userId, boolean replacing, 15021 PackageParser.Package pkg) { 15022 if (mIntentFilterVerifierComponent == null) { 15023 Slog.w(TAG, "No IntentFilter verification will not be done as " 15024 + "there is no IntentFilterVerifier available!"); 15025 return; 15026 } 15027 15028 final int verifierUid = getPackageUid( 15029 mIntentFilterVerifierComponent.getPackageName(), 15030 MATCH_DEBUG_TRIAGED_MISSING, 15031 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15032 15033 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15034 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15035 mHandler.sendMessage(msg); 15036 15037 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15038 for (int i = 0; i < childCount; i++) { 15039 PackageParser.Package childPkg = pkg.childPackages.get(i); 15040 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15041 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15042 mHandler.sendMessage(msg); 15043 } 15044 } 15045 15046 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15047 PackageParser.Package pkg) { 15048 int size = pkg.activities.size(); 15049 if (size == 0) { 15050 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15051 "No activity, so no need to verify any IntentFilter!"); 15052 return; 15053 } 15054 15055 final boolean hasDomainURLs = hasDomainURLs(pkg); 15056 if (!hasDomainURLs) { 15057 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15058 "No domain URLs, so no need to verify any IntentFilter!"); 15059 return; 15060 } 15061 15062 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15063 + " if any IntentFilter from the " + size 15064 + " Activities needs verification ..."); 15065 15066 int count = 0; 15067 final String packageName = pkg.packageName; 15068 15069 synchronized (mPackages) { 15070 // If this is a new install and we see that we've already run verification for this 15071 // package, we have nothing to do: it means the state was restored from backup. 15072 if (!replacing) { 15073 IntentFilterVerificationInfo ivi = 15074 mSettings.getIntentFilterVerificationLPr(packageName); 15075 if (ivi != null) { 15076 if (DEBUG_DOMAIN_VERIFICATION) { 15077 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15078 + ivi.getStatusString()); 15079 } 15080 return; 15081 } 15082 } 15083 15084 // If any filters need to be verified, then all need to be. 15085 boolean needToVerify = false; 15086 for (PackageParser.Activity a : pkg.activities) { 15087 for (ActivityIntentInfo filter : a.intents) { 15088 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15089 if (DEBUG_DOMAIN_VERIFICATION) { 15090 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15091 } 15092 needToVerify = true; 15093 break; 15094 } 15095 } 15096 } 15097 15098 if (needToVerify) { 15099 final int verificationId = mIntentFilterVerificationToken++; 15100 for (PackageParser.Activity a : pkg.activities) { 15101 for (ActivityIntentInfo filter : a.intents) { 15102 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15103 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15104 "Verification needed for IntentFilter:" + filter.toString()); 15105 mIntentFilterVerifier.addOneIntentFilterVerification( 15106 verifierUid, userId, verificationId, filter, packageName); 15107 count++; 15108 } 15109 } 15110 } 15111 } 15112 } 15113 15114 if (count > 0) { 15115 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15116 + " IntentFilter verification" + (count > 1 ? "s" : "") 15117 + " for userId:" + userId); 15118 mIntentFilterVerifier.startVerifications(userId); 15119 } else { 15120 if (DEBUG_DOMAIN_VERIFICATION) { 15121 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15122 } 15123 } 15124 } 15125 15126 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15127 final ComponentName cn = filter.activity.getComponentName(); 15128 final String packageName = cn.getPackageName(); 15129 15130 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15131 packageName); 15132 if (ivi == null) { 15133 return true; 15134 } 15135 int status = ivi.getStatus(); 15136 switch (status) { 15137 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15138 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15139 return true; 15140 15141 default: 15142 // Nothing to do 15143 return false; 15144 } 15145 } 15146 15147 private static boolean isMultiArch(ApplicationInfo info) { 15148 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15149 } 15150 15151 private static boolean isExternal(PackageParser.Package pkg) { 15152 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15153 } 15154 15155 private static boolean isExternal(PackageSetting ps) { 15156 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15157 } 15158 15159 private static boolean isEphemeral(PackageParser.Package pkg) { 15160 return pkg.applicationInfo.isEphemeralApp(); 15161 } 15162 15163 private static boolean isEphemeral(PackageSetting ps) { 15164 return ps.pkg != null && isEphemeral(ps.pkg); 15165 } 15166 15167 private static boolean isSystemApp(PackageParser.Package pkg) { 15168 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15169 } 15170 15171 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15172 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15173 } 15174 15175 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15176 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15177 } 15178 15179 private static boolean isSystemApp(PackageSetting ps) { 15180 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15181 } 15182 15183 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15184 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15185 } 15186 15187 private int packageFlagsToInstallFlags(PackageSetting ps) { 15188 int installFlags = 0; 15189 if (isEphemeral(ps)) { 15190 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15191 } 15192 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15193 // This existing package was an external ASEC install when we have 15194 // the external flag without a UUID 15195 installFlags |= PackageManager.INSTALL_EXTERNAL; 15196 } 15197 if (ps.isForwardLocked()) { 15198 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15199 } 15200 return installFlags; 15201 } 15202 15203 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15204 if (isExternal(pkg)) { 15205 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15206 return StorageManager.UUID_PRIMARY_PHYSICAL; 15207 } else { 15208 return pkg.volumeUuid; 15209 } 15210 } else { 15211 return StorageManager.UUID_PRIVATE_INTERNAL; 15212 } 15213 } 15214 15215 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15216 if (isExternal(pkg)) { 15217 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15218 return mSettings.getExternalVersion(); 15219 } else { 15220 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15221 } 15222 } else { 15223 return mSettings.getInternalVersion(); 15224 } 15225 } 15226 15227 private void deleteTempPackageFiles() { 15228 final FilenameFilter filter = new FilenameFilter() { 15229 public boolean accept(File dir, String name) { 15230 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15231 } 15232 }; 15233 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15234 file.delete(); 15235 } 15236 } 15237 15238 @Override 15239 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15240 int flags) { 15241 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15242 flags); 15243 } 15244 15245 @Override 15246 public void deletePackage(final String packageName, 15247 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15248 mContext.enforceCallingOrSelfPermission( 15249 android.Manifest.permission.DELETE_PACKAGES, null); 15250 Preconditions.checkNotNull(packageName); 15251 Preconditions.checkNotNull(observer); 15252 final int uid = Binder.getCallingUid(); 15253 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15254 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15255 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15256 mContext.enforceCallingOrSelfPermission( 15257 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15258 "deletePackage for user " + userId); 15259 } 15260 15261 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15262 try { 15263 observer.onPackageDeleted(packageName, 15264 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15265 } catch (RemoteException re) { 15266 } 15267 return; 15268 } 15269 15270 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15271 try { 15272 observer.onPackageDeleted(packageName, 15273 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15274 } catch (RemoteException re) { 15275 } 15276 return; 15277 } 15278 15279 if (DEBUG_REMOVE) { 15280 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15281 + " deleteAllUsers: " + deleteAllUsers ); 15282 } 15283 // Queue up an async operation since the package deletion may take a little while. 15284 mHandler.post(new Runnable() { 15285 public void run() { 15286 mHandler.removeCallbacks(this); 15287 int returnCode; 15288 if (!deleteAllUsers) { 15289 returnCode = deletePackageX(packageName, userId, deleteFlags); 15290 } else { 15291 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15292 // If nobody is blocking uninstall, proceed with delete for all users 15293 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15294 returnCode = deletePackageX(packageName, userId, deleteFlags); 15295 } else { 15296 // Otherwise uninstall individually for users with blockUninstalls=false 15297 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15298 for (int userId : users) { 15299 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15300 returnCode = deletePackageX(packageName, userId, userFlags); 15301 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15302 Slog.w(TAG, "Package delete failed for user " + userId 15303 + ", returnCode " + returnCode); 15304 } 15305 } 15306 } 15307 // The app has only been marked uninstalled for certain users. 15308 // We still need to report that delete was blocked 15309 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15310 } 15311 } 15312 try { 15313 observer.onPackageDeleted(packageName, returnCode, null); 15314 } catch (RemoteException e) { 15315 Log.i(TAG, "Observer no longer exists."); 15316 } //end catch 15317 } //end run 15318 }); 15319 } 15320 15321 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15322 int[] result = EMPTY_INT_ARRAY; 15323 for (int userId : userIds) { 15324 if (getBlockUninstallForUser(packageName, userId)) { 15325 result = ArrayUtils.appendInt(result, userId); 15326 } 15327 } 15328 return result; 15329 } 15330 15331 @Override 15332 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15333 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15334 } 15335 15336 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15337 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15338 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15339 try { 15340 if (dpm != null) { 15341 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15342 /* callingUserOnly =*/ false); 15343 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15344 : deviceOwnerComponentName.getPackageName(); 15345 // Does the package contains the device owner? 15346 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15347 // this check is probably not needed, since DO should be registered as a device 15348 // admin on some user too. (Original bug for this: b/17657954) 15349 if (packageName.equals(deviceOwnerPackageName)) { 15350 return true; 15351 } 15352 // Does it contain a device admin for any user? 15353 int[] users; 15354 if (userId == UserHandle.USER_ALL) { 15355 users = sUserManager.getUserIds(); 15356 } else { 15357 users = new int[]{userId}; 15358 } 15359 for (int i = 0; i < users.length; ++i) { 15360 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15361 return true; 15362 } 15363 } 15364 } 15365 } catch (RemoteException e) { 15366 } 15367 return false; 15368 } 15369 15370 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15371 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15372 } 15373 15374 /** 15375 * This method is an internal method that could be get invoked either 15376 * to delete an installed package or to clean up a failed installation. 15377 * After deleting an installed package, a broadcast is sent to notify any 15378 * listeners that the package has been removed. For cleaning up a failed 15379 * installation, the broadcast is not necessary since the package's 15380 * installation wouldn't have sent the initial broadcast either 15381 * The key steps in deleting a package are 15382 * deleting the package information in internal structures like mPackages, 15383 * deleting the packages base directories through installd 15384 * updating mSettings to reflect current status 15385 * persisting settings for later use 15386 * sending a broadcast if necessary 15387 */ 15388 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15389 final PackageRemovedInfo info = new PackageRemovedInfo(); 15390 final boolean res; 15391 15392 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15393 ? UserHandle.ALL : new UserHandle(userId); 15394 15395 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15396 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15397 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15398 } 15399 15400 PackageSetting uninstalledPs = null; 15401 15402 // for the uninstall-updates case and restricted profiles, remember the per- 15403 // user handle installed state 15404 int[] allUsers; 15405 synchronized (mPackages) { 15406 uninstalledPs = mSettings.mPackages.get(packageName); 15407 if (uninstalledPs == null) { 15408 Slog.w(TAG, "Not removing non-existent package " + packageName); 15409 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15410 } 15411 allUsers = sUserManager.getUserIds(); 15412 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15413 } 15414 15415 synchronized (mInstallLock) { 15416 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15417 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15418 "deletePackageX")) { 15419 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15420 deleteFlags | REMOVE_CHATTY, info, true, null); 15421 } 15422 synchronized (mPackages) { 15423 if (res) { 15424 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15425 } 15426 } 15427 } 15428 15429 if (res) { 15430 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15431 info.sendPackageRemovedBroadcasts(killApp); 15432 info.sendSystemPackageUpdatedBroadcasts(); 15433 info.sendSystemPackageAppearedBroadcasts(); 15434 } 15435 // Force a gc here. 15436 Runtime.getRuntime().gc(); 15437 // Delete the resources here after sending the broadcast to let 15438 // other processes clean up before deleting resources. 15439 if (info.args != null) { 15440 synchronized (mInstallLock) { 15441 info.args.doPostDeleteLI(true); 15442 } 15443 } 15444 15445 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15446 } 15447 15448 class PackageRemovedInfo { 15449 String removedPackage; 15450 int uid = -1; 15451 int removedAppId = -1; 15452 int[] origUsers; 15453 int[] removedUsers = null; 15454 boolean isRemovedPackageSystemUpdate = false; 15455 boolean isUpdate; 15456 boolean dataRemoved; 15457 boolean removedForAllUsers; 15458 // Clean up resources deleted packages. 15459 InstallArgs args = null; 15460 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15461 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15462 15463 void sendPackageRemovedBroadcasts(boolean killApp) { 15464 sendPackageRemovedBroadcastInternal(killApp); 15465 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15466 for (int i = 0; i < childCount; i++) { 15467 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15468 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15469 } 15470 } 15471 15472 void sendSystemPackageUpdatedBroadcasts() { 15473 if (isRemovedPackageSystemUpdate) { 15474 sendSystemPackageUpdatedBroadcastsInternal(); 15475 final int childCount = (removedChildPackages != null) 15476 ? removedChildPackages.size() : 0; 15477 for (int i = 0; i < childCount; i++) { 15478 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15479 if (childInfo.isRemovedPackageSystemUpdate) { 15480 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15481 } 15482 } 15483 } 15484 } 15485 15486 void sendSystemPackageAppearedBroadcasts() { 15487 final int packageCount = (appearedChildPackages != null) 15488 ? appearedChildPackages.size() : 0; 15489 for (int i = 0; i < packageCount; i++) { 15490 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15491 for (int userId : installedInfo.newUsers) { 15492 sendPackageAddedForUser(installedInfo.name, true, 15493 UserHandle.getAppId(installedInfo.uid), userId); 15494 } 15495 } 15496 } 15497 15498 private void sendSystemPackageUpdatedBroadcastsInternal() { 15499 Bundle extras = new Bundle(2); 15500 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15501 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15502 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15503 extras, 0, null, null, null); 15504 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15505 extras, 0, null, null, null); 15506 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15507 null, 0, removedPackage, null, null); 15508 } 15509 15510 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15511 Bundle extras = new Bundle(2); 15512 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15513 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15514 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15515 if (isUpdate || isRemovedPackageSystemUpdate) { 15516 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15517 } 15518 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15519 if (removedPackage != null) { 15520 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15521 extras, 0, null, null, removedUsers); 15522 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15523 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15524 removedPackage, extras, 0, null, null, removedUsers); 15525 } 15526 } 15527 if (removedAppId >= 0) { 15528 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15529 removedUsers); 15530 } 15531 } 15532 } 15533 15534 /* 15535 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15536 * flag is not set, the data directory is removed as well. 15537 * make sure this flag is set for partially installed apps. If not its meaningless to 15538 * delete a partially installed application. 15539 */ 15540 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15541 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15542 String packageName = ps.name; 15543 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15544 // Retrieve object to delete permissions for shared user later on 15545 final PackageParser.Package deletedPkg; 15546 final PackageSetting deletedPs; 15547 // reader 15548 synchronized (mPackages) { 15549 deletedPkg = mPackages.get(packageName); 15550 deletedPs = mSettings.mPackages.get(packageName); 15551 if (outInfo != null) { 15552 outInfo.removedPackage = packageName; 15553 outInfo.removedUsers = deletedPs != null 15554 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15555 : null; 15556 } 15557 } 15558 15559 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15560 15561 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15562 final PackageParser.Package resolvedPkg; 15563 if (deletedPkg != null) { 15564 resolvedPkg = deletedPkg; 15565 } else { 15566 // We don't have a parsed package when it lives on an ejected 15567 // adopted storage device, so fake something together 15568 resolvedPkg = new PackageParser.Package(ps.name); 15569 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15570 } 15571 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15572 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15573 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15574 if (outInfo != null) { 15575 outInfo.dataRemoved = true; 15576 } 15577 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15578 } 15579 15580 // writer 15581 synchronized (mPackages) { 15582 if (deletedPs != null) { 15583 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15584 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15585 clearDefaultBrowserIfNeeded(packageName); 15586 if (outInfo != null) { 15587 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15588 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15589 } 15590 updatePermissionsLPw(deletedPs.name, null, 0); 15591 if (deletedPs.sharedUser != null) { 15592 // Remove permissions associated with package. Since runtime 15593 // permissions are per user we have to kill the removed package 15594 // or packages running under the shared user of the removed 15595 // package if revoking the permissions requested only by the removed 15596 // package is successful and this causes a change in gids. 15597 for (int userId : UserManagerService.getInstance().getUserIds()) { 15598 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15599 userId); 15600 if (userIdToKill == UserHandle.USER_ALL 15601 || userIdToKill >= UserHandle.USER_SYSTEM) { 15602 // If gids changed for this user, kill all affected packages. 15603 mHandler.post(new Runnable() { 15604 @Override 15605 public void run() { 15606 // This has to happen with no lock held. 15607 killApplication(deletedPs.name, deletedPs.appId, 15608 KILL_APP_REASON_GIDS_CHANGED); 15609 } 15610 }); 15611 break; 15612 } 15613 } 15614 } 15615 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15616 } 15617 // make sure to preserve per-user disabled state if this removal was just 15618 // a downgrade of a system app to the factory package 15619 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15620 if (DEBUG_REMOVE) { 15621 Slog.d(TAG, "Propagating install state across downgrade"); 15622 } 15623 for (int userId : allUserHandles) { 15624 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15625 if (DEBUG_REMOVE) { 15626 Slog.d(TAG, " user " + userId + " => " + installed); 15627 } 15628 ps.setInstalled(installed, userId); 15629 } 15630 } 15631 } 15632 // can downgrade to reader 15633 if (writeSettings) { 15634 // Save settings now 15635 mSettings.writeLPr(); 15636 } 15637 } 15638 if (outInfo != null) { 15639 // A user ID was deleted here. Go through all users and remove it 15640 // from KeyStore. 15641 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15642 } 15643 } 15644 15645 static boolean locationIsPrivileged(File path) { 15646 try { 15647 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15648 .getCanonicalPath(); 15649 return path.getCanonicalPath().startsWith(privilegedAppDir); 15650 } catch (IOException e) { 15651 Slog.e(TAG, "Unable to access code path " + path); 15652 } 15653 return false; 15654 } 15655 15656 /* 15657 * Tries to delete system package. 15658 */ 15659 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15660 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15661 boolean writeSettings) { 15662 if (deletedPs.parentPackageName != null) { 15663 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15664 return false; 15665 } 15666 15667 final boolean applyUserRestrictions 15668 = (allUserHandles != null) && (outInfo.origUsers != null); 15669 final PackageSetting disabledPs; 15670 // Confirm if the system package has been updated 15671 // An updated system app can be deleted. This will also have to restore 15672 // the system pkg from system partition 15673 // reader 15674 synchronized (mPackages) { 15675 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15676 } 15677 15678 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15679 + " disabledPs=" + disabledPs); 15680 15681 if (disabledPs == null) { 15682 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15683 return false; 15684 } else if (DEBUG_REMOVE) { 15685 Slog.d(TAG, "Deleting system pkg from data partition"); 15686 } 15687 15688 if (DEBUG_REMOVE) { 15689 if (applyUserRestrictions) { 15690 Slog.d(TAG, "Remembering install states:"); 15691 for (int userId : allUserHandles) { 15692 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15693 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15694 } 15695 } 15696 } 15697 15698 // Delete the updated package 15699 outInfo.isRemovedPackageSystemUpdate = true; 15700 if (outInfo.removedChildPackages != null) { 15701 final int childCount = (deletedPs.childPackageNames != null) 15702 ? deletedPs.childPackageNames.size() : 0; 15703 for (int i = 0; i < childCount; i++) { 15704 String childPackageName = deletedPs.childPackageNames.get(i); 15705 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15706 .contains(childPackageName)) { 15707 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15708 childPackageName); 15709 if (childInfo != null) { 15710 childInfo.isRemovedPackageSystemUpdate = true; 15711 } 15712 } 15713 } 15714 } 15715 15716 if (disabledPs.versionCode < deletedPs.versionCode) { 15717 // Delete data for downgrades 15718 flags &= ~PackageManager.DELETE_KEEP_DATA; 15719 } else { 15720 // Preserve data by setting flag 15721 flags |= PackageManager.DELETE_KEEP_DATA; 15722 } 15723 15724 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15725 outInfo, writeSettings, disabledPs.pkg); 15726 if (!ret) { 15727 return false; 15728 } 15729 15730 // writer 15731 synchronized (mPackages) { 15732 // Reinstate the old system package 15733 enableSystemPackageLPw(disabledPs.pkg); 15734 // Remove any native libraries from the upgraded package. 15735 removeNativeBinariesLI(deletedPs); 15736 } 15737 15738 // Install the system package 15739 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15740 int parseFlags = mDefParseFlags 15741 | PackageParser.PARSE_MUST_BE_APK 15742 | PackageParser.PARSE_IS_SYSTEM 15743 | PackageParser.PARSE_IS_SYSTEM_DIR; 15744 if (locationIsPrivileged(disabledPs.codePath)) { 15745 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15746 } 15747 15748 final PackageParser.Package newPkg; 15749 try { 15750 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15751 } catch (PackageManagerException e) { 15752 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15753 + e.getMessage()); 15754 return false; 15755 } 15756 15757 prepareAppDataAfterInstallLIF(newPkg); 15758 15759 // writer 15760 synchronized (mPackages) { 15761 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15762 15763 // Propagate the permissions state as we do not want to drop on the floor 15764 // runtime permissions. The update permissions method below will take 15765 // care of removing obsolete permissions and grant install permissions. 15766 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15767 updatePermissionsLPw(newPkg.packageName, newPkg, 15768 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15769 15770 if (applyUserRestrictions) { 15771 if (DEBUG_REMOVE) { 15772 Slog.d(TAG, "Propagating install state across reinstall"); 15773 } 15774 for (int userId : allUserHandles) { 15775 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15776 if (DEBUG_REMOVE) { 15777 Slog.d(TAG, " user " + userId + " => " + installed); 15778 } 15779 ps.setInstalled(installed, userId); 15780 15781 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15782 } 15783 // Regardless of writeSettings we need to ensure that this restriction 15784 // state propagation is persisted 15785 mSettings.writeAllUsersPackageRestrictionsLPr(); 15786 } 15787 // can downgrade to reader here 15788 if (writeSettings) { 15789 mSettings.writeLPr(); 15790 } 15791 } 15792 return true; 15793 } 15794 15795 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15796 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15797 PackageRemovedInfo outInfo, boolean writeSettings, 15798 PackageParser.Package replacingPackage) { 15799 synchronized (mPackages) { 15800 if (outInfo != null) { 15801 outInfo.uid = ps.appId; 15802 } 15803 15804 if (outInfo != null && outInfo.removedChildPackages != null) { 15805 final int childCount = (ps.childPackageNames != null) 15806 ? ps.childPackageNames.size() : 0; 15807 for (int i = 0; i < childCount; i++) { 15808 String childPackageName = ps.childPackageNames.get(i); 15809 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15810 if (childPs == null) { 15811 return false; 15812 } 15813 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15814 childPackageName); 15815 if (childInfo != null) { 15816 childInfo.uid = childPs.appId; 15817 } 15818 } 15819 } 15820 } 15821 15822 // Delete package data from internal structures and also remove data if flag is set 15823 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15824 15825 // Delete the child packages data 15826 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15827 for (int i = 0; i < childCount; i++) { 15828 PackageSetting childPs; 15829 synchronized (mPackages) { 15830 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15831 } 15832 if (childPs != null) { 15833 PackageRemovedInfo childOutInfo = (outInfo != null 15834 && outInfo.removedChildPackages != null) 15835 ? outInfo.removedChildPackages.get(childPs.name) : null; 15836 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15837 && (replacingPackage != null 15838 && !replacingPackage.hasChildPackage(childPs.name)) 15839 ? flags & ~DELETE_KEEP_DATA : flags; 15840 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15841 deleteFlags, writeSettings); 15842 } 15843 } 15844 15845 // Delete application code and resources only for parent packages 15846 if (ps.parentPackageName == null) { 15847 if (deleteCodeAndResources && (outInfo != null)) { 15848 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15849 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15850 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15851 } 15852 } 15853 15854 return true; 15855 } 15856 15857 @Override 15858 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15859 int userId) { 15860 mContext.enforceCallingOrSelfPermission( 15861 android.Manifest.permission.DELETE_PACKAGES, null); 15862 synchronized (mPackages) { 15863 PackageSetting ps = mSettings.mPackages.get(packageName); 15864 if (ps == null) { 15865 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15866 return false; 15867 } 15868 if (!ps.getInstalled(userId)) { 15869 // Can't block uninstall for an app that is not installed or enabled. 15870 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15871 return false; 15872 } 15873 ps.setBlockUninstall(blockUninstall, userId); 15874 mSettings.writePackageRestrictionsLPr(userId); 15875 } 15876 return true; 15877 } 15878 15879 @Override 15880 public boolean getBlockUninstallForUser(String packageName, int userId) { 15881 synchronized (mPackages) { 15882 PackageSetting ps = mSettings.mPackages.get(packageName); 15883 if (ps == null) { 15884 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15885 return false; 15886 } 15887 return ps.getBlockUninstall(userId); 15888 } 15889 } 15890 15891 @Override 15892 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15893 int callingUid = Binder.getCallingUid(); 15894 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15895 throw new SecurityException( 15896 "setRequiredForSystemUser can only be run by the system or root"); 15897 } 15898 synchronized (mPackages) { 15899 PackageSetting ps = mSettings.mPackages.get(packageName); 15900 if (ps == null) { 15901 Log.w(TAG, "Package doesn't exist: " + packageName); 15902 return false; 15903 } 15904 if (systemUserApp) { 15905 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15906 } else { 15907 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15908 } 15909 mSettings.writeLPr(); 15910 } 15911 return true; 15912 } 15913 15914 /* 15915 * This method handles package deletion in general 15916 */ 15917 private boolean deletePackageLIF(String packageName, UserHandle user, 15918 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15919 PackageRemovedInfo outInfo, boolean writeSettings, 15920 PackageParser.Package replacingPackage) { 15921 if (packageName == null) { 15922 Slog.w(TAG, "Attempt to delete null packageName."); 15923 return false; 15924 } 15925 15926 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15927 15928 PackageSetting ps; 15929 15930 synchronized (mPackages) { 15931 ps = mSettings.mPackages.get(packageName); 15932 if (ps == null) { 15933 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15934 return false; 15935 } 15936 15937 if (ps.parentPackageName != null && (!isSystemApp(ps) 15938 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15939 if (DEBUG_REMOVE) { 15940 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15941 + ((user == null) ? UserHandle.USER_ALL : user)); 15942 } 15943 final int removedUserId = (user != null) ? user.getIdentifier() 15944 : UserHandle.USER_ALL; 15945 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15946 return false; 15947 } 15948 markPackageUninstalledForUserLPw(ps, user); 15949 scheduleWritePackageRestrictionsLocked(user); 15950 return true; 15951 } 15952 } 15953 15954 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15955 && user.getIdentifier() != UserHandle.USER_ALL)) { 15956 // The caller is asking that the package only be deleted for a single 15957 // user. To do this, we just mark its uninstalled state and delete 15958 // its data. If this is a system app, we only allow this to happen if 15959 // they have set the special DELETE_SYSTEM_APP which requests different 15960 // semantics than normal for uninstalling system apps. 15961 markPackageUninstalledForUserLPw(ps, user); 15962 15963 if (!isSystemApp(ps)) { 15964 // Do not uninstall the APK if an app should be cached 15965 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15966 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15967 // Other user still have this package installed, so all 15968 // we need to do is clear this user's data and save that 15969 // it is uninstalled. 15970 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15971 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15972 return false; 15973 } 15974 scheduleWritePackageRestrictionsLocked(user); 15975 return true; 15976 } else { 15977 // We need to set it back to 'installed' so the uninstall 15978 // broadcasts will be sent correctly. 15979 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15980 ps.setInstalled(true, user.getIdentifier()); 15981 } 15982 } else { 15983 // This is a system app, so we assume that the 15984 // other users still have this package installed, so all 15985 // we need to do is clear this user's data and save that 15986 // it is uninstalled. 15987 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15988 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15989 return false; 15990 } 15991 scheduleWritePackageRestrictionsLocked(user); 15992 return true; 15993 } 15994 } 15995 15996 // If we are deleting a composite package for all users, keep track 15997 // of result for each child. 15998 if (ps.childPackageNames != null && outInfo != null) { 15999 synchronized (mPackages) { 16000 final int childCount = ps.childPackageNames.size(); 16001 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16002 for (int i = 0; i < childCount; i++) { 16003 String childPackageName = ps.childPackageNames.get(i); 16004 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16005 childInfo.removedPackage = childPackageName; 16006 outInfo.removedChildPackages.put(childPackageName, childInfo); 16007 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16008 if (childPs != null) { 16009 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16010 } 16011 } 16012 } 16013 } 16014 16015 boolean ret = false; 16016 if (isSystemApp(ps)) { 16017 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16018 // When an updated system application is deleted we delete the existing resources 16019 // as well and fall back to existing code in system partition 16020 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16021 } else { 16022 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16023 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16024 outInfo, writeSettings, replacingPackage); 16025 } 16026 16027 // Take a note whether we deleted the package for all users 16028 if (outInfo != null) { 16029 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16030 if (outInfo.removedChildPackages != null) { 16031 synchronized (mPackages) { 16032 final int childCount = outInfo.removedChildPackages.size(); 16033 for (int i = 0; i < childCount; i++) { 16034 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16035 if (childInfo != null) { 16036 childInfo.removedForAllUsers = mPackages.get( 16037 childInfo.removedPackage) == null; 16038 } 16039 } 16040 } 16041 } 16042 // If we uninstalled an update to a system app there may be some 16043 // child packages that appeared as they are declared in the system 16044 // app but were not declared in the update. 16045 if (isSystemApp(ps)) { 16046 synchronized (mPackages) { 16047 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16048 final int childCount = (updatedPs.childPackageNames != null) 16049 ? updatedPs.childPackageNames.size() : 0; 16050 for (int i = 0; i < childCount; i++) { 16051 String childPackageName = updatedPs.childPackageNames.get(i); 16052 if (outInfo.removedChildPackages == null 16053 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16054 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16055 if (childPs == null) { 16056 continue; 16057 } 16058 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16059 installRes.name = childPackageName; 16060 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16061 installRes.pkg = mPackages.get(childPackageName); 16062 installRes.uid = childPs.pkg.applicationInfo.uid; 16063 if (outInfo.appearedChildPackages == null) { 16064 outInfo.appearedChildPackages = new ArrayMap<>(); 16065 } 16066 outInfo.appearedChildPackages.put(childPackageName, installRes); 16067 } 16068 } 16069 } 16070 } 16071 } 16072 16073 return ret; 16074 } 16075 16076 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16077 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16078 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16079 for (int nextUserId : userIds) { 16080 if (DEBUG_REMOVE) { 16081 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16082 } 16083 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16084 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16085 false /*hidden*/, false /*suspended*/, null, null, null, 16086 false /*blockUninstall*/, 16087 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16088 } 16089 } 16090 16091 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16092 PackageRemovedInfo outInfo) { 16093 final PackageParser.Package pkg; 16094 synchronized (mPackages) { 16095 pkg = mPackages.get(ps.name); 16096 } 16097 16098 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16099 : new int[] {userId}; 16100 for (int nextUserId : userIds) { 16101 if (DEBUG_REMOVE) { 16102 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16103 + nextUserId); 16104 } 16105 16106 destroyAppDataLIF(pkg, userId, 16107 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16108 destroyAppProfilesLIF(pkg, userId); 16109 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16110 schedulePackageCleaning(ps.name, nextUserId, false); 16111 synchronized (mPackages) { 16112 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16113 scheduleWritePackageRestrictionsLocked(nextUserId); 16114 } 16115 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16116 } 16117 } 16118 16119 if (outInfo != null) { 16120 outInfo.removedPackage = ps.name; 16121 outInfo.removedAppId = ps.appId; 16122 outInfo.removedUsers = userIds; 16123 } 16124 16125 return true; 16126 } 16127 16128 private final class ClearStorageConnection implements ServiceConnection { 16129 IMediaContainerService mContainerService; 16130 16131 @Override 16132 public void onServiceConnected(ComponentName name, IBinder service) { 16133 synchronized (this) { 16134 mContainerService = IMediaContainerService.Stub.asInterface(service); 16135 notifyAll(); 16136 } 16137 } 16138 16139 @Override 16140 public void onServiceDisconnected(ComponentName name) { 16141 } 16142 } 16143 16144 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16145 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16146 16147 final boolean mounted; 16148 if (Environment.isExternalStorageEmulated()) { 16149 mounted = true; 16150 } else { 16151 final String status = Environment.getExternalStorageState(); 16152 16153 mounted = status.equals(Environment.MEDIA_MOUNTED) 16154 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16155 } 16156 16157 if (!mounted) { 16158 return; 16159 } 16160 16161 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16162 int[] users; 16163 if (userId == UserHandle.USER_ALL) { 16164 users = sUserManager.getUserIds(); 16165 } else { 16166 users = new int[] { userId }; 16167 } 16168 final ClearStorageConnection conn = new ClearStorageConnection(); 16169 if (mContext.bindServiceAsUser( 16170 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16171 try { 16172 for (int curUser : users) { 16173 long timeout = SystemClock.uptimeMillis() + 5000; 16174 synchronized (conn) { 16175 long now = SystemClock.uptimeMillis(); 16176 while (conn.mContainerService == null && now < timeout) { 16177 try { 16178 conn.wait(timeout - now); 16179 } catch (InterruptedException e) { 16180 } 16181 } 16182 } 16183 if (conn.mContainerService == null) { 16184 return; 16185 } 16186 16187 final UserEnvironment userEnv = new UserEnvironment(curUser); 16188 clearDirectory(conn.mContainerService, 16189 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16190 if (allData) { 16191 clearDirectory(conn.mContainerService, 16192 userEnv.buildExternalStorageAppDataDirs(packageName)); 16193 clearDirectory(conn.mContainerService, 16194 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16195 } 16196 } 16197 } finally { 16198 mContext.unbindService(conn); 16199 } 16200 } 16201 } 16202 16203 @Override 16204 public void clearApplicationProfileData(String packageName) { 16205 enforceSystemOrRoot("Only the system can clear all profile data"); 16206 16207 final PackageParser.Package pkg; 16208 synchronized (mPackages) { 16209 pkg = mPackages.get(packageName); 16210 } 16211 16212 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16213 synchronized (mInstallLock) { 16214 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16215 } 16216 } 16217 } 16218 16219 @Override 16220 public void clearApplicationUserData(final String packageName, 16221 final IPackageDataObserver observer, final int userId) { 16222 mContext.enforceCallingOrSelfPermission( 16223 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16224 16225 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16226 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16227 16228 final DevicePolicyManagerInternal dpmi = LocalServices 16229 .getService(DevicePolicyManagerInternal.class); 16230 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16231 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16232 } 16233 // Queue up an async operation since the package deletion may take a little while. 16234 mHandler.post(new Runnable() { 16235 public void run() { 16236 mHandler.removeCallbacks(this); 16237 final boolean succeeded; 16238 try (PackageFreezer freezer = freezePackage(packageName, 16239 "clearApplicationUserData")) { 16240 synchronized (mInstallLock) { 16241 succeeded = clearApplicationUserDataLIF(packageName, userId); 16242 } 16243 clearExternalStorageDataSync(packageName, userId, true); 16244 } 16245 if (succeeded) { 16246 // invoke DeviceStorageMonitor's update method to clear any notifications 16247 DeviceStorageMonitorInternal dsm = LocalServices 16248 .getService(DeviceStorageMonitorInternal.class); 16249 if (dsm != null) { 16250 dsm.checkMemory(); 16251 } 16252 } 16253 if(observer != null) { 16254 try { 16255 observer.onRemoveCompleted(packageName, succeeded); 16256 } catch (RemoteException e) { 16257 Log.i(TAG, "Observer no longer exists."); 16258 } 16259 } //end if observer 16260 } //end run 16261 }); 16262 } 16263 16264 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16265 if (packageName == null) { 16266 Slog.w(TAG, "Attempt to delete null packageName."); 16267 return false; 16268 } 16269 16270 // Try finding details about the requested package 16271 PackageParser.Package pkg; 16272 synchronized (mPackages) { 16273 pkg = mPackages.get(packageName); 16274 if (pkg == null) { 16275 final PackageSetting ps = mSettings.mPackages.get(packageName); 16276 if (ps != null) { 16277 pkg = ps.pkg; 16278 } 16279 } 16280 16281 if (pkg == null) { 16282 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16283 return false; 16284 } 16285 16286 PackageSetting ps = (PackageSetting) pkg.mExtras; 16287 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16288 } 16289 16290 clearAppDataLIF(pkg, userId, 16291 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16292 16293 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16294 removeKeystoreDataIfNeeded(userId, appId); 16295 16296 UserManagerInternal umInternal = getUserManagerInternal(); 16297 final int flags; 16298 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16299 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16300 } else if (umInternal.isUserRunning(userId)) { 16301 flags = StorageManager.FLAG_STORAGE_DE; 16302 } else { 16303 flags = 0; 16304 } 16305 prepareAppDataContentsLIF(pkg, userId, flags); 16306 16307 return true; 16308 } 16309 16310 /** 16311 * Reverts user permission state changes (permissions and flags) in 16312 * all packages for a given user. 16313 * 16314 * @param userId The device user for which to do a reset. 16315 */ 16316 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16317 final int packageCount = mPackages.size(); 16318 for (int i = 0; i < packageCount; i++) { 16319 PackageParser.Package pkg = mPackages.valueAt(i); 16320 PackageSetting ps = (PackageSetting) pkg.mExtras; 16321 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16322 } 16323 } 16324 16325 private void resetNetworkPolicies(int userId) { 16326 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16327 } 16328 16329 /** 16330 * Reverts user permission state changes (permissions and flags). 16331 * 16332 * @param ps The package for which to reset. 16333 * @param userId The device user for which to do a reset. 16334 */ 16335 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16336 final PackageSetting ps, final int userId) { 16337 if (ps.pkg == null) { 16338 return; 16339 } 16340 16341 // These are flags that can change base on user actions. 16342 final int userSettableMask = FLAG_PERMISSION_USER_SET 16343 | FLAG_PERMISSION_USER_FIXED 16344 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16345 | FLAG_PERMISSION_REVIEW_REQUIRED; 16346 16347 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16348 | FLAG_PERMISSION_POLICY_FIXED; 16349 16350 boolean writeInstallPermissions = false; 16351 boolean writeRuntimePermissions = false; 16352 16353 final int permissionCount = ps.pkg.requestedPermissions.size(); 16354 for (int i = 0; i < permissionCount; i++) { 16355 String permission = ps.pkg.requestedPermissions.get(i); 16356 16357 BasePermission bp = mSettings.mPermissions.get(permission); 16358 if (bp == null) { 16359 continue; 16360 } 16361 16362 // If shared user we just reset the state to which only this app contributed. 16363 if (ps.sharedUser != null) { 16364 boolean used = false; 16365 final int packageCount = ps.sharedUser.packages.size(); 16366 for (int j = 0; j < packageCount; j++) { 16367 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16368 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16369 && pkg.pkg.requestedPermissions.contains(permission)) { 16370 used = true; 16371 break; 16372 } 16373 } 16374 if (used) { 16375 continue; 16376 } 16377 } 16378 16379 PermissionsState permissionsState = ps.getPermissionsState(); 16380 16381 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16382 16383 // Always clear the user settable flags. 16384 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16385 bp.name) != null; 16386 // If permission review is enabled and this is a legacy app, mark the 16387 // permission as requiring a review as this is the initial state. 16388 int flags = 0; 16389 if (Build.PERMISSIONS_REVIEW_REQUIRED 16390 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16391 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16392 } 16393 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16394 if (hasInstallState) { 16395 writeInstallPermissions = true; 16396 } else { 16397 writeRuntimePermissions = true; 16398 } 16399 } 16400 16401 // Below is only runtime permission handling. 16402 if (!bp.isRuntime()) { 16403 continue; 16404 } 16405 16406 // Never clobber system or policy. 16407 if ((oldFlags & policyOrSystemFlags) != 0) { 16408 continue; 16409 } 16410 16411 // If this permission was granted by default, make sure it is. 16412 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16413 if (permissionsState.grantRuntimePermission(bp, userId) 16414 != PERMISSION_OPERATION_FAILURE) { 16415 writeRuntimePermissions = true; 16416 } 16417 // If permission review is enabled the permissions for a legacy apps 16418 // are represented as constantly granted runtime ones, so don't revoke. 16419 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16420 // Otherwise, reset the permission. 16421 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16422 switch (revokeResult) { 16423 case PERMISSION_OPERATION_SUCCESS: 16424 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16425 writeRuntimePermissions = true; 16426 final int appId = ps.appId; 16427 mHandler.post(new Runnable() { 16428 @Override 16429 public void run() { 16430 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16431 } 16432 }); 16433 } break; 16434 } 16435 } 16436 } 16437 16438 // Synchronously write as we are taking permissions away. 16439 if (writeRuntimePermissions) { 16440 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16441 } 16442 16443 // Synchronously write as we are taking permissions away. 16444 if (writeInstallPermissions) { 16445 mSettings.writeLPr(); 16446 } 16447 } 16448 16449 /** 16450 * Remove entries from the keystore daemon. Will only remove it if the 16451 * {@code appId} is valid. 16452 */ 16453 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16454 if (appId < 0) { 16455 return; 16456 } 16457 16458 final KeyStore keyStore = KeyStore.getInstance(); 16459 if (keyStore != null) { 16460 if (userId == UserHandle.USER_ALL) { 16461 for (final int individual : sUserManager.getUserIds()) { 16462 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16463 } 16464 } else { 16465 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16466 } 16467 } else { 16468 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16469 } 16470 } 16471 16472 @Override 16473 public void deleteApplicationCacheFiles(final String packageName, 16474 final IPackageDataObserver observer) { 16475 final int userId = UserHandle.getCallingUserId(); 16476 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16477 } 16478 16479 @Override 16480 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16481 final IPackageDataObserver observer) { 16482 mContext.enforceCallingOrSelfPermission( 16483 android.Manifest.permission.DELETE_CACHE_FILES, null); 16484 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16485 /* requireFullPermission= */ true, /* checkShell= */ false, 16486 "delete application cache files"); 16487 16488 final PackageParser.Package pkg; 16489 synchronized (mPackages) { 16490 pkg = mPackages.get(packageName); 16491 } 16492 16493 // Queue up an async operation since the package deletion may take a little while. 16494 mHandler.post(new Runnable() { 16495 public void run() { 16496 synchronized (mInstallLock) { 16497 final int flags = StorageManager.FLAG_STORAGE_DE 16498 | StorageManager.FLAG_STORAGE_CE; 16499 // We're only clearing cache files, so we don't care if the 16500 // app is unfrozen and still able to run 16501 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16502 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16503 } 16504 clearExternalStorageDataSync(packageName, userId, false); 16505 if (observer != null) { 16506 try { 16507 observer.onRemoveCompleted(packageName, true); 16508 } catch (RemoteException e) { 16509 Log.i(TAG, "Observer no longer exists."); 16510 } 16511 } 16512 } 16513 }); 16514 } 16515 16516 @Override 16517 public void getPackageSizeInfo(final String packageName, int userHandle, 16518 final IPackageStatsObserver observer) { 16519 mContext.enforceCallingOrSelfPermission( 16520 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16521 if (packageName == null) { 16522 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16523 } 16524 16525 PackageStats stats = new PackageStats(packageName, userHandle); 16526 16527 /* 16528 * Queue up an async operation since the package measurement may take a 16529 * little while. 16530 */ 16531 Message msg = mHandler.obtainMessage(INIT_COPY); 16532 msg.obj = new MeasureParams(stats, observer); 16533 mHandler.sendMessage(msg); 16534 } 16535 16536 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16537 final PackageSetting ps; 16538 synchronized (mPackages) { 16539 ps = mSettings.mPackages.get(packageName); 16540 if (ps == null) { 16541 Slog.w(TAG, "Failed to find settings for " + packageName); 16542 return false; 16543 } 16544 } 16545 try { 16546 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16547 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16548 ps.getCeDataInode(userId), ps.codePathString, stats); 16549 } catch (InstallerException e) { 16550 Slog.w(TAG, String.valueOf(e)); 16551 return false; 16552 } 16553 16554 // For now, ignore code size of packages on system partition 16555 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16556 stats.codeSize = 0; 16557 } 16558 16559 return true; 16560 } 16561 16562 private int getUidTargetSdkVersionLockedLPr(int uid) { 16563 Object obj = mSettings.getUserIdLPr(uid); 16564 if (obj instanceof SharedUserSetting) { 16565 final SharedUserSetting sus = (SharedUserSetting) obj; 16566 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16567 final Iterator<PackageSetting> it = sus.packages.iterator(); 16568 while (it.hasNext()) { 16569 final PackageSetting ps = it.next(); 16570 if (ps.pkg != null) { 16571 int v = ps.pkg.applicationInfo.targetSdkVersion; 16572 if (v < vers) vers = v; 16573 } 16574 } 16575 return vers; 16576 } else if (obj instanceof PackageSetting) { 16577 final PackageSetting ps = (PackageSetting) obj; 16578 if (ps.pkg != null) { 16579 return ps.pkg.applicationInfo.targetSdkVersion; 16580 } 16581 } 16582 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16583 } 16584 16585 @Override 16586 public void addPreferredActivity(IntentFilter filter, int match, 16587 ComponentName[] set, ComponentName activity, int userId) { 16588 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16589 "Adding preferred"); 16590 } 16591 16592 private void addPreferredActivityInternal(IntentFilter filter, int match, 16593 ComponentName[] set, ComponentName activity, boolean always, int userId, 16594 String opname) { 16595 // writer 16596 int callingUid = Binder.getCallingUid(); 16597 enforceCrossUserPermission(callingUid, userId, 16598 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16599 if (filter.countActions() == 0) { 16600 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16601 return; 16602 } 16603 synchronized (mPackages) { 16604 if (mContext.checkCallingOrSelfPermission( 16605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16606 != PackageManager.PERMISSION_GRANTED) { 16607 if (getUidTargetSdkVersionLockedLPr(callingUid) 16608 < Build.VERSION_CODES.FROYO) { 16609 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16610 + callingUid); 16611 return; 16612 } 16613 mContext.enforceCallingOrSelfPermission( 16614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16615 } 16616 16617 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16618 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16619 + userId + ":"); 16620 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16621 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16622 scheduleWritePackageRestrictionsLocked(userId); 16623 } 16624 } 16625 16626 @Override 16627 public void replacePreferredActivity(IntentFilter filter, int match, 16628 ComponentName[] set, ComponentName activity, int userId) { 16629 if (filter.countActions() != 1) { 16630 throw new IllegalArgumentException( 16631 "replacePreferredActivity expects filter to have only 1 action."); 16632 } 16633 if (filter.countDataAuthorities() != 0 16634 || filter.countDataPaths() != 0 16635 || filter.countDataSchemes() > 1 16636 || filter.countDataTypes() != 0) { 16637 throw new IllegalArgumentException( 16638 "replacePreferredActivity expects filter to have no data authorities, " + 16639 "paths, or types; and at most one scheme."); 16640 } 16641 16642 final int callingUid = Binder.getCallingUid(); 16643 enforceCrossUserPermission(callingUid, userId, 16644 true /* requireFullPermission */, false /* checkShell */, 16645 "replace preferred activity"); 16646 synchronized (mPackages) { 16647 if (mContext.checkCallingOrSelfPermission( 16648 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16649 != PackageManager.PERMISSION_GRANTED) { 16650 if (getUidTargetSdkVersionLockedLPr(callingUid) 16651 < Build.VERSION_CODES.FROYO) { 16652 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16653 + Binder.getCallingUid()); 16654 return; 16655 } 16656 mContext.enforceCallingOrSelfPermission( 16657 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16658 } 16659 16660 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16661 if (pir != null) { 16662 // Get all of the existing entries that exactly match this filter. 16663 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16664 if (existing != null && existing.size() == 1) { 16665 PreferredActivity cur = existing.get(0); 16666 if (DEBUG_PREFERRED) { 16667 Slog.i(TAG, "Checking replace of preferred:"); 16668 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16669 if (!cur.mPref.mAlways) { 16670 Slog.i(TAG, " -- CUR; not mAlways!"); 16671 } else { 16672 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16673 Slog.i(TAG, " -- CUR: mSet=" 16674 + Arrays.toString(cur.mPref.mSetComponents)); 16675 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16676 Slog.i(TAG, " -- NEW: mMatch=" 16677 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16678 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16679 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16680 } 16681 } 16682 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16683 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16684 && cur.mPref.sameSet(set)) { 16685 // Setting the preferred activity to what it happens to be already 16686 if (DEBUG_PREFERRED) { 16687 Slog.i(TAG, "Replacing with same preferred activity " 16688 + cur.mPref.mShortComponent + " for user " 16689 + userId + ":"); 16690 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16691 } 16692 return; 16693 } 16694 } 16695 16696 if (existing != null) { 16697 if (DEBUG_PREFERRED) { 16698 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16699 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16700 } 16701 for (int i = 0; i < existing.size(); i++) { 16702 PreferredActivity pa = existing.get(i); 16703 if (DEBUG_PREFERRED) { 16704 Slog.i(TAG, "Removing existing preferred activity " 16705 + pa.mPref.mComponent + ":"); 16706 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16707 } 16708 pir.removeFilter(pa); 16709 } 16710 } 16711 } 16712 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16713 "Replacing preferred"); 16714 } 16715 } 16716 16717 @Override 16718 public void clearPackagePreferredActivities(String packageName) { 16719 final int uid = Binder.getCallingUid(); 16720 // writer 16721 synchronized (mPackages) { 16722 PackageParser.Package pkg = mPackages.get(packageName); 16723 if (pkg == null || pkg.applicationInfo.uid != uid) { 16724 if (mContext.checkCallingOrSelfPermission( 16725 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16726 != PackageManager.PERMISSION_GRANTED) { 16727 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16728 < Build.VERSION_CODES.FROYO) { 16729 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16730 + Binder.getCallingUid()); 16731 return; 16732 } 16733 mContext.enforceCallingOrSelfPermission( 16734 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16735 } 16736 } 16737 16738 int user = UserHandle.getCallingUserId(); 16739 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16740 scheduleWritePackageRestrictionsLocked(user); 16741 } 16742 } 16743 } 16744 16745 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16746 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16747 ArrayList<PreferredActivity> removed = null; 16748 boolean changed = false; 16749 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16750 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16751 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16752 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16753 continue; 16754 } 16755 Iterator<PreferredActivity> it = pir.filterIterator(); 16756 while (it.hasNext()) { 16757 PreferredActivity pa = it.next(); 16758 // Mark entry for removal only if it matches the package name 16759 // and the entry is of type "always". 16760 if (packageName == null || 16761 (pa.mPref.mComponent.getPackageName().equals(packageName) 16762 && pa.mPref.mAlways)) { 16763 if (removed == null) { 16764 removed = new ArrayList<PreferredActivity>(); 16765 } 16766 removed.add(pa); 16767 } 16768 } 16769 if (removed != null) { 16770 for (int j=0; j<removed.size(); j++) { 16771 PreferredActivity pa = removed.get(j); 16772 pir.removeFilter(pa); 16773 } 16774 changed = true; 16775 } 16776 } 16777 return changed; 16778 } 16779 16780 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16781 private void clearIntentFilterVerificationsLPw(int userId) { 16782 final int packageCount = mPackages.size(); 16783 for (int i = 0; i < packageCount; i++) { 16784 PackageParser.Package pkg = mPackages.valueAt(i); 16785 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16786 } 16787 } 16788 16789 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16790 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16791 if (userId == UserHandle.USER_ALL) { 16792 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16793 sUserManager.getUserIds())) { 16794 for (int oneUserId : sUserManager.getUserIds()) { 16795 scheduleWritePackageRestrictionsLocked(oneUserId); 16796 } 16797 } 16798 } else { 16799 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16800 scheduleWritePackageRestrictionsLocked(userId); 16801 } 16802 } 16803 } 16804 16805 void clearDefaultBrowserIfNeeded(String packageName) { 16806 for (int oneUserId : sUserManager.getUserIds()) { 16807 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16808 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16809 if (packageName.equals(defaultBrowserPackageName)) { 16810 setDefaultBrowserPackageName(null, oneUserId); 16811 } 16812 } 16813 } 16814 16815 @Override 16816 public void resetApplicationPreferences(int userId) { 16817 mContext.enforceCallingOrSelfPermission( 16818 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16819 final long identity = Binder.clearCallingIdentity(); 16820 // writer 16821 try { 16822 synchronized (mPackages) { 16823 clearPackagePreferredActivitiesLPw(null, userId); 16824 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16825 // TODO: We have to reset the default SMS and Phone. This requires 16826 // significant refactoring to keep all default apps in the package 16827 // manager (cleaner but more work) or have the services provide 16828 // callbacks to the package manager to request a default app reset. 16829 applyFactoryDefaultBrowserLPw(userId); 16830 clearIntentFilterVerificationsLPw(userId); 16831 primeDomainVerificationsLPw(userId); 16832 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16833 scheduleWritePackageRestrictionsLocked(userId); 16834 } 16835 resetNetworkPolicies(userId); 16836 } finally { 16837 Binder.restoreCallingIdentity(identity); 16838 } 16839 } 16840 16841 @Override 16842 public int getPreferredActivities(List<IntentFilter> outFilters, 16843 List<ComponentName> outActivities, String packageName) { 16844 16845 int num = 0; 16846 final int userId = UserHandle.getCallingUserId(); 16847 // reader 16848 synchronized (mPackages) { 16849 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16850 if (pir != null) { 16851 final Iterator<PreferredActivity> it = pir.filterIterator(); 16852 while (it.hasNext()) { 16853 final PreferredActivity pa = it.next(); 16854 if (packageName == null 16855 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16856 && pa.mPref.mAlways)) { 16857 if (outFilters != null) { 16858 outFilters.add(new IntentFilter(pa)); 16859 } 16860 if (outActivities != null) { 16861 outActivities.add(pa.mPref.mComponent); 16862 } 16863 } 16864 } 16865 } 16866 } 16867 16868 return num; 16869 } 16870 16871 @Override 16872 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16873 int userId) { 16874 int callingUid = Binder.getCallingUid(); 16875 if (callingUid != Process.SYSTEM_UID) { 16876 throw new SecurityException( 16877 "addPersistentPreferredActivity can only be run by the system"); 16878 } 16879 if (filter.countActions() == 0) { 16880 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16881 return; 16882 } 16883 synchronized (mPackages) { 16884 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16885 ":"); 16886 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16887 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16888 new PersistentPreferredActivity(filter, activity)); 16889 scheduleWritePackageRestrictionsLocked(userId); 16890 } 16891 } 16892 16893 @Override 16894 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16895 int callingUid = Binder.getCallingUid(); 16896 if (callingUid != Process.SYSTEM_UID) { 16897 throw new SecurityException( 16898 "clearPackagePersistentPreferredActivities can only be run by the system"); 16899 } 16900 ArrayList<PersistentPreferredActivity> removed = null; 16901 boolean changed = false; 16902 synchronized (mPackages) { 16903 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16904 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16905 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16906 .valueAt(i); 16907 if (userId != thisUserId) { 16908 continue; 16909 } 16910 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16911 while (it.hasNext()) { 16912 PersistentPreferredActivity ppa = it.next(); 16913 // Mark entry for removal only if it matches the package name. 16914 if (ppa.mComponent.getPackageName().equals(packageName)) { 16915 if (removed == null) { 16916 removed = new ArrayList<PersistentPreferredActivity>(); 16917 } 16918 removed.add(ppa); 16919 } 16920 } 16921 if (removed != null) { 16922 for (int j=0; j<removed.size(); j++) { 16923 PersistentPreferredActivity ppa = removed.get(j); 16924 ppir.removeFilter(ppa); 16925 } 16926 changed = true; 16927 } 16928 } 16929 16930 if (changed) { 16931 scheduleWritePackageRestrictionsLocked(userId); 16932 } 16933 } 16934 } 16935 16936 /** 16937 * Common machinery for picking apart a restored XML blob and passing 16938 * it to a caller-supplied functor to be applied to the running system. 16939 */ 16940 private void restoreFromXml(XmlPullParser parser, int userId, 16941 String expectedStartTag, BlobXmlRestorer functor) 16942 throws IOException, XmlPullParserException { 16943 int type; 16944 while ((type = parser.next()) != XmlPullParser.START_TAG 16945 && type != XmlPullParser.END_DOCUMENT) { 16946 } 16947 if (type != XmlPullParser.START_TAG) { 16948 // oops didn't find a start tag?! 16949 if (DEBUG_BACKUP) { 16950 Slog.e(TAG, "Didn't find start tag during restore"); 16951 } 16952 return; 16953 } 16954Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16955 // this is supposed to be TAG_PREFERRED_BACKUP 16956 if (!expectedStartTag.equals(parser.getName())) { 16957 if (DEBUG_BACKUP) { 16958 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16959 } 16960 return; 16961 } 16962 16963 // skip interfering stuff, then we're aligned with the backing implementation 16964 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16965Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16966 functor.apply(parser, userId); 16967 } 16968 16969 private interface BlobXmlRestorer { 16970 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16971 } 16972 16973 /** 16974 * Non-Binder method, support for the backup/restore mechanism: write the 16975 * full set of preferred activities in its canonical XML format. Returns the 16976 * XML output as a byte array, or null if there is none. 16977 */ 16978 @Override 16979 public byte[] getPreferredActivityBackup(int userId) { 16980 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16981 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16982 } 16983 16984 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16985 try { 16986 final XmlSerializer serializer = new FastXmlSerializer(); 16987 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16988 serializer.startDocument(null, true); 16989 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16990 16991 synchronized (mPackages) { 16992 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16993 } 16994 16995 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16996 serializer.endDocument(); 16997 serializer.flush(); 16998 } catch (Exception e) { 16999 if (DEBUG_BACKUP) { 17000 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17001 } 17002 return null; 17003 } 17004 17005 return dataStream.toByteArray(); 17006 } 17007 17008 @Override 17009 public void restorePreferredActivities(byte[] backup, int userId) { 17010 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17011 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17012 } 17013 17014 try { 17015 final XmlPullParser parser = Xml.newPullParser(); 17016 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17017 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17018 new BlobXmlRestorer() { 17019 @Override 17020 public void apply(XmlPullParser parser, int userId) 17021 throws XmlPullParserException, IOException { 17022 synchronized (mPackages) { 17023 mSettings.readPreferredActivitiesLPw(parser, userId); 17024 } 17025 } 17026 } ); 17027 } catch (Exception e) { 17028 if (DEBUG_BACKUP) { 17029 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17030 } 17031 } 17032 } 17033 17034 /** 17035 * Non-Binder method, support for the backup/restore mechanism: write the 17036 * default browser (etc) settings in its canonical XML format. Returns the default 17037 * browser XML representation as a byte array, or null if there is none. 17038 */ 17039 @Override 17040 public byte[] getDefaultAppsBackup(int userId) { 17041 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17042 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17043 } 17044 17045 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17046 try { 17047 final XmlSerializer serializer = new FastXmlSerializer(); 17048 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17049 serializer.startDocument(null, true); 17050 serializer.startTag(null, TAG_DEFAULT_APPS); 17051 17052 synchronized (mPackages) { 17053 mSettings.writeDefaultAppsLPr(serializer, userId); 17054 } 17055 17056 serializer.endTag(null, TAG_DEFAULT_APPS); 17057 serializer.endDocument(); 17058 serializer.flush(); 17059 } catch (Exception e) { 17060 if (DEBUG_BACKUP) { 17061 Slog.e(TAG, "Unable to write default apps for backup", e); 17062 } 17063 return null; 17064 } 17065 17066 return dataStream.toByteArray(); 17067 } 17068 17069 @Override 17070 public void restoreDefaultApps(byte[] backup, int userId) { 17071 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17072 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17073 } 17074 17075 try { 17076 final XmlPullParser parser = Xml.newPullParser(); 17077 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17078 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17079 new BlobXmlRestorer() { 17080 @Override 17081 public void apply(XmlPullParser parser, int userId) 17082 throws XmlPullParserException, IOException { 17083 synchronized (mPackages) { 17084 mSettings.readDefaultAppsLPw(parser, userId); 17085 } 17086 } 17087 } ); 17088 } catch (Exception e) { 17089 if (DEBUG_BACKUP) { 17090 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17091 } 17092 } 17093 } 17094 17095 @Override 17096 public byte[] getIntentFilterVerificationBackup(int userId) { 17097 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17098 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17099 } 17100 17101 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17102 try { 17103 final XmlSerializer serializer = new FastXmlSerializer(); 17104 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17105 serializer.startDocument(null, true); 17106 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17107 17108 synchronized (mPackages) { 17109 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17110 } 17111 17112 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17113 serializer.endDocument(); 17114 serializer.flush(); 17115 } catch (Exception e) { 17116 if (DEBUG_BACKUP) { 17117 Slog.e(TAG, "Unable to write default apps for backup", e); 17118 } 17119 return null; 17120 } 17121 17122 return dataStream.toByteArray(); 17123 } 17124 17125 @Override 17126 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17127 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17128 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17129 } 17130 17131 try { 17132 final XmlPullParser parser = Xml.newPullParser(); 17133 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17134 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17135 new BlobXmlRestorer() { 17136 @Override 17137 public void apply(XmlPullParser parser, int userId) 17138 throws XmlPullParserException, IOException { 17139 synchronized (mPackages) { 17140 mSettings.readAllDomainVerificationsLPr(parser, userId); 17141 mSettings.writeLPr(); 17142 } 17143 } 17144 } ); 17145 } catch (Exception e) { 17146 if (DEBUG_BACKUP) { 17147 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17148 } 17149 } 17150 } 17151 17152 @Override 17153 public byte[] getPermissionGrantBackup(int userId) { 17154 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17155 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17156 } 17157 17158 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17159 try { 17160 final XmlSerializer serializer = new FastXmlSerializer(); 17161 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17162 serializer.startDocument(null, true); 17163 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17164 17165 synchronized (mPackages) { 17166 serializeRuntimePermissionGrantsLPr(serializer, userId); 17167 } 17168 17169 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17170 serializer.endDocument(); 17171 serializer.flush(); 17172 } catch (Exception e) { 17173 if (DEBUG_BACKUP) { 17174 Slog.e(TAG, "Unable to write default apps for backup", e); 17175 } 17176 return null; 17177 } 17178 17179 return dataStream.toByteArray(); 17180 } 17181 17182 @Override 17183 public void restorePermissionGrants(byte[] backup, int userId) { 17184 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17185 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17186 } 17187 17188 try { 17189 final XmlPullParser parser = Xml.newPullParser(); 17190 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17191 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17192 new BlobXmlRestorer() { 17193 @Override 17194 public void apply(XmlPullParser parser, int userId) 17195 throws XmlPullParserException, IOException { 17196 synchronized (mPackages) { 17197 processRestoredPermissionGrantsLPr(parser, userId); 17198 } 17199 } 17200 } ); 17201 } catch (Exception e) { 17202 if (DEBUG_BACKUP) { 17203 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17204 } 17205 } 17206 } 17207 17208 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17209 throws IOException { 17210 serializer.startTag(null, TAG_ALL_GRANTS); 17211 17212 final int N = mSettings.mPackages.size(); 17213 for (int i = 0; i < N; i++) { 17214 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17215 boolean pkgGrantsKnown = false; 17216 17217 PermissionsState packagePerms = ps.getPermissionsState(); 17218 17219 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17220 final int grantFlags = state.getFlags(); 17221 // only look at grants that are not system/policy fixed 17222 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17223 final boolean isGranted = state.isGranted(); 17224 // And only back up the user-twiddled state bits 17225 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17226 final String packageName = mSettings.mPackages.keyAt(i); 17227 if (!pkgGrantsKnown) { 17228 serializer.startTag(null, TAG_GRANT); 17229 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17230 pkgGrantsKnown = true; 17231 } 17232 17233 final boolean userSet = 17234 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17235 final boolean userFixed = 17236 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17237 final boolean revoke = 17238 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17239 17240 serializer.startTag(null, TAG_PERMISSION); 17241 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17242 if (isGranted) { 17243 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17244 } 17245 if (userSet) { 17246 serializer.attribute(null, ATTR_USER_SET, "true"); 17247 } 17248 if (userFixed) { 17249 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17250 } 17251 if (revoke) { 17252 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17253 } 17254 serializer.endTag(null, TAG_PERMISSION); 17255 } 17256 } 17257 } 17258 17259 if (pkgGrantsKnown) { 17260 serializer.endTag(null, TAG_GRANT); 17261 } 17262 } 17263 17264 serializer.endTag(null, TAG_ALL_GRANTS); 17265 } 17266 17267 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17268 throws XmlPullParserException, IOException { 17269 String pkgName = null; 17270 int outerDepth = parser.getDepth(); 17271 int type; 17272 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17273 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17274 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17275 continue; 17276 } 17277 17278 final String tagName = parser.getName(); 17279 if (tagName.equals(TAG_GRANT)) { 17280 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17281 if (DEBUG_BACKUP) { 17282 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17283 } 17284 } else if (tagName.equals(TAG_PERMISSION)) { 17285 17286 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17287 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17288 17289 int newFlagSet = 0; 17290 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17291 newFlagSet |= FLAG_PERMISSION_USER_SET; 17292 } 17293 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17294 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17295 } 17296 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17297 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17298 } 17299 if (DEBUG_BACKUP) { 17300 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17301 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17302 } 17303 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17304 if (ps != null) { 17305 // Already installed so we apply the grant immediately 17306 if (DEBUG_BACKUP) { 17307 Slog.v(TAG, " + already installed; applying"); 17308 } 17309 PermissionsState perms = ps.getPermissionsState(); 17310 BasePermission bp = mSettings.mPermissions.get(permName); 17311 if (bp != null) { 17312 if (isGranted) { 17313 perms.grantRuntimePermission(bp, userId); 17314 } 17315 if (newFlagSet != 0) { 17316 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17317 } 17318 } 17319 } else { 17320 // Need to wait for post-restore install to apply the grant 17321 if (DEBUG_BACKUP) { 17322 Slog.v(TAG, " - not yet installed; saving for later"); 17323 } 17324 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17325 isGranted, newFlagSet, userId); 17326 } 17327 } else { 17328 PackageManagerService.reportSettingsProblem(Log.WARN, 17329 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17330 XmlUtils.skipCurrentTag(parser); 17331 } 17332 } 17333 17334 scheduleWriteSettingsLocked(); 17335 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17336 } 17337 17338 @Override 17339 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17340 int sourceUserId, int targetUserId, int flags) { 17341 mContext.enforceCallingOrSelfPermission( 17342 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17343 int callingUid = Binder.getCallingUid(); 17344 enforceOwnerRights(ownerPackage, callingUid); 17345 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17346 if (intentFilter.countActions() == 0) { 17347 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17348 return; 17349 } 17350 synchronized (mPackages) { 17351 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17352 ownerPackage, targetUserId, flags); 17353 CrossProfileIntentResolver resolver = 17354 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17355 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17356 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17357 if (existing != null) { 17358 int size = existing.size(); 17359 for (int i = 0; i < size; i++) { 17360 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17361 return; 17362 } 17363 } 17364 } 17365 resolver.addFilter(newFilter); 17366 scheduleWritePackageRestrictionsLocked(sourceUserId); 17367 } 17368 } 17369 17370 @Override 17371 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17372 mContext.enforceCallingOrSelfPermission( 17373 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17374 int callingUid = Binder.getCallingUid(); 17375 enforceOwnerRights(ownerPackage, callingUid); 17376 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17377 synchronized (mPackages) { 17378 CrossProfileIntentResolver resolver = 17379 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17380 ArraySet<CrossProfileIntentFilter> set = 17381 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17382 for (CrossProfileIntentFilter filter : set) { 17383 if (filter.getOwnerPackage().equals(ownerPackage)) { 17384 resolver.removeFilter(filter); 17385 } 17386 } 17387 scheduleWritePackageRestrictionsLocked(sourceUserId); 17388 } 17389 } 17390 17391 // Enforcing that callingUid is owning pkg on userId 17392 private void enforceOwnerRights(String pkg, int callingUid) { 17393 // The system owns everything. 17394 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17395 return; 17396 } 17397 int callingUserId = UserHandle.getUserId(callingUid); 17398 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17399 if (pi == null) { 17400 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17401 + callingUserId); 17402 } 17403 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17404 throw new SecurityException("Calling uid " + callingUid 17405 + " does not own package " + pkg); 17406 } 17407 } 17408 17409 @Override 17410 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17411 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17412 } 17413 17414 private Intent getHomeIntent() { 17415 Intent intent = new Intent(Intent.ACTION_MAIN); 17416 intent.addCategory(Intent.CATEGORY_HOME); 17417 return intent; 17418 } 17419 17420 private IntentFilter getHomeFilter() { 17421 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17422 filter.addCategory(Intent.CATEGORY_HOME); 17423 filter.addCategory(Intent.CATEGORY_DEFAULT); 17424 return filter; 17425 } 17426 17427 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17428 int userId) { 17429 Intent intent = getHomeIntent(); 17430 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17431 PackageManager.GET_META_DATA, userId); 17432 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17433 true, false, false, userId); 17434 17435 allHomeCandidates.clear(); 17436 if (list != null) { 17437 for (ResolveInfo ri : list) { 17438 allHomeCandidates.add(ri); 17439 } 17440 } 17441 return (preferred == null || preferred.activityInfo == null) 17442 ? null 17443 : new ComponentName(preferred.activityInfo.packageName, 17444 preferred.activityInfo.name); 17445 } 17446 17447 @Override 17448 public void setHomeActivity(ComponentName comp, int userId) { 17449 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17450 getHomeActivitiesAsUser(homeActivities, userId); 17451 17452 boolean found = false; 17453 17454 final int size = homeActivities.size(); 17455 final ComponentName[] set = new ComponentName[size]; 17456 for (int i = 0; i < size; i++) { 17457 final ResolveInfo candidate = homeActivities.get(i); 17458 final ActivityInfo info = candidate.activityInfo; 17459 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17460 set[i] = activityName; 17461 if (!found && activityName.equals(comp)) { 17462 found = true; 17463 } 17464 } 17465 if (!found) { 17466 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17467 + userId); 17468 } 17469 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17470 set, comp, userId); 17471 } 17472 17473 private @Nullable String getSetupWizardPackageName() { 17474 final Intent intent = new Intent(Intent.ACTION_MAIN); 17475 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17476 17477 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17478 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17479 | MATCH_DISABLED_COMPONENTS, 17480 UserHandle.myUserId()); 17481 if (matches.size() == 1) { 17482 return matches.get(0).getComponentInfo().packageName; 17483 } else { 17484 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17485 + ": matches=" + matches); 17486 return null; 17487 } 17488 } 17489 17490 @Override 17491 public void setApplicationEnabledSetting(String appPackageName, 17492 int newState, int flags, int userId, String callingPackage) { 17493 if (!sUserManager.exists(userId)) return; 17494 if (callingPackage == null) { 17495 callingPackage = Integer.toString(Binder.getCallingUid()); 17496 } 17497 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17498 } 17499 17500 @Override 17501 public void setComponentEnabledSetting(ComponentName componentName, 17502 int newState, int flags, int userId) { 17503 if (!sUserManager.exists(userId)) return; 17504 setEnabledSetting(componentName.getPackageName(), 17505 componentName.getClassName(), newState, flags, userId, null); 17506 } 17507 17508 private void setEnabledSetting(final String packageName, String className, int newState, 17509 final int flags, int userId, String callingPackage) { 17510 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17511 || newState == COMPONENT_ENABLED_STATE_ENABLED 17512 || newState == COMPONENT_ENABLED_STATE_DISABLED 17513 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17514 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17515 throw new IllegalArgumentException("Invalid new component state: " 17516 + newState); 17517 } 17518 PackageSetting pkgSetting; 17519 final int uid = Binder.getCallingUid(); 17520 final int permission; 17521 if (uid == Process.SYSTEM_UID) { 17522 permission = PackageManager.PERMISSION_GRANTED; 17523 } else { 17524 permission = mContext.checkCallingOrSelfPermission( 17525 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17526 } 17527 enforceCrossUserPermission(uid, userId, 17528 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17529 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17530 boolean sendNow = false; 17531 boolean isApp = (className == null); 17532 String componentName = isApp ? packageName : className; 17533 int packageUid = -1; 17534 ArrayList<String> components; 17535 17536 // writer 17537 synchronized (mPackages) { 17538 pkgSetting = mSettings.mPackages.get(packageName); 17539 if (pkgSetting == null) { 17540 if (className == null) { 17541 throw new IllegalArgumentException("Unknown package: " + packageName); 17542 } 17543 throw new IllegalArgumentException( 17544 "Unknown component: " + packageName + "/" + className); 17545 } 17546 } 17547 17548 // Limit who can change which apps 17549 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17550 // Don't allow apps that don't have permission to modify other apps 17551 if (!allowedByPermission) { 17552 throw new SecurityException( 17553 "Permission Denial: attempt to change component state from pid=" 17554 + Binder.getCallingPid() 17555 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17556 } 17557 // Don't allow changing profile and device owners. Calling into DPMS, so no locking. 17558 final DevicePolicyManagerInternal dpmi = LocalServices 17559 .getService(DevicePolicyManagerInternal.class); 17560 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17561 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17562 } 17563 } 17564 17565 synchronized (mPackages) { 17566 if (uid == Process.SHELL_UID) { 17567 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17568 int oldState = pkgSetting.getEnabled(userId); 17569 if (className == null 17570 && 17571 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17572 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17573 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17574 && 17575 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17576 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17577 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17578 // ok 17579 } else { 17580 throw new SecurityException( 17581 "Shell cannot change component state for " + packageName + "/" 17582 + className + " to " + newState); 17583 } 17584 } 17585 if (className == null) { 17586 // We're dealing with an application/package level state change 17587 if (pkgSetting.getEnabled(userId) == newState) { 17588 // Nothing to do 17589 return; 17590 } 17591 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17592 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17593 // Don't care about who enables an app. 17594 callingPackage = null; 17595 } 17596 pkgSetting.setEnabled(newState, userId, callingPackage); 17597 // pkgSetting.pkg.mSetEnabled = newState; 17598 } else { 17599 // We're dealing with a component level state change 17600 // First, verify that this is a valid class name. 17601 PackageParser.Package pkg = pkgSetting.pkg; 17602 if (pkg == null || !pkg.hasComponentClassName(className)) { 17603 if (pkg != null && 17604 pkg.applicationInfo.targetSdkVersion >= 17605 Build.VERSION_CODES.JELLY_BEAN) { 17606 throw new IllegalArgumentException("Component class " + className 17607 + " does not exist in " + packageName); 17608 } else { 17609 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17610 + className + " does not exist in " + packageName); 17611 } 17612 } 17613 switch (newState) { 17614 case COMPONENT_ENABLED_STATE_ENABLED: 17615 if (!pkgSetting.enableComponentLPw(className, userId)) { 17616 return; 17617 } 17618 break; 17619 case COMPONENT_ENABLED_STATE_DISABLED: 17620 if (!pkgSetting.disableComponentLPw(className, userId)) { 17621 return; 17622 } 17623 break; 17624 case COMPONENT_ENABLED_STATE_DEFAULT: 17625 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17626 return; 17627 } 17628 break; 17629 default: 17630 Slog.e(TAG, "Invalid new component state: " + newState); 17631 return; 17632 } 17633 } 17634 scheduleWritePackageRestrictionsLocked(userId); 17635 components = mPendingBroadcasts.get(userId, packageName); 17636 final boolean newPackage = components == null; 17637 if (newPackage) { 17638 components = new ArrayList<String>(); 17639 } 17640 if (!components.contains(componentName)) { 17641 components.add(componentName); 17642 } 17643 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17644 sendNow = true; 17645 // Purge entry from pending broadcast list if another one exists already 17646 // since we are sending one right away. 17647 mPendingBroadcasts.remove(userId, packageName); 17648 } else { 17649 if (newPackage) { 17650 mPendingBroadcasts.put(userId, packageName, components); 17651 } 17652 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17653 // Schedule a message 17654 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17655 } 17656 } 17657 } 17658 17659 long callingId = Binder.clearCallingIdentity(); 17660 try { 17661 if (sendNow) { 17662 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17663 sendPackageChangedBroadcast(packageName, 17664 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17665 } 17666 } finally { 17667 Binder.restoreCallingIdentity(callingId); 17668 } 17669 } 17670 17671 @Override 17672 public void flushPackageRestrictionsAsUser(int userId) { 17673 if (!sUserManager.exists(userId)) { 17674 return; 17675 } 17676 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17677 false /* checkShell */, "flushPackageRestrictions"); 17678 synchronized (mPackages) { 17679 mSettings.writePackageRestrictionsLPr(userId); 17680 mDirtyUsers.remove(userId); 17681 if (mDirtyUsers.isEmpty()) { 17682 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17683 } 17684 } 17685 } 17686 17687 private void sendPackageChangedBroadcast(String packageName, 17688 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17689 if (DEBUG_INSTALL) 17690 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17691 + componentNames); 17692 Bundle extras = new Bundle(4); 17693 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17694 String nameList[] = new String[componentNames.size()]; 17695 componentNames.toArray(nameList); 17696 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17697 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17698 extras.putInt(Intent.EXTRA_UID, packageUid); 17699 // If this is not reporting a change of the overall package, then only send it 17700 // to registered receivers. We don't want to launch a swath of apps for every 17701 // little component state change. 17702 final int flags = !componentNames.contains(packageName) 17703 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17704 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17705 new int[] {UserHandle.getUserId(packageUid)}); 17706 } 17707 17708 @Override 17709 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17710 if (!sUserManager.exists(userId)) return; 17711 final int uid = Binder.getCallingUid(); 17712 final int permission = mContext.checkCallingOrSelfPermission( 17713 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17714 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17715 enforceCrossUserPermission(uid, userId, 17716 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17717 // writer 17718 synchronized (mPackages) { 17719 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17720 allowedByPermission, uid, userId)) { 17721 scheduleWritePackageRestrictionsLocked(userId); 17722 } 17723 } 17724 } 17725 17726 @Override 17727 public String getInstallerPackageName(String packageName) { 17728 // reader 17729 synchronized (mPackages) { 17730 return mSettings.getInstallerPackageNameLPr(packageName); 17731 } 17732 } 17733 17734 public boolean isOrphaned(String packageName) { 17735 // reader 17736 synchronized (mPackages) { 17737 return mSettings.isOrphaned(packageName); 17738 } 17739 } 17740 17741 @Override 17742 public int getApplicationEnabledSetting(String packageName, int userId) { 17743 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17744 int uid = Binder.getCallingUid(); 17745 enforceCrossUserPermission(uid, userId, 17746 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17747 // reader 17748 synchronized (mPackages) { 17749 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17750 } 17751 } 17752 17753 @Override 17754 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17755 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17756 int uid = Binder.getCallingUid(); 17757 enforceCrossUserPermission(uid, userId, 17758 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17759 // reader 17760 synchronized (mPackages) { 17761 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17762 } 17763 } 17764 17765 @Override 17766 public void enterSafeMode() { 17767 enforceSystemOrRoot("Only the system can request entering safe mode"); 17768 17769 if (!mSystemReady) { 17770 mSafeMode = true; 17771 } 17772 } 17773 17774 @Override 17775 public void systemReady() { 17776 mSystemReady = true; 17777 17778 // Read the compatibilty setting when the system is ready. 17779 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17780 mContext.getContentResolver(), 17781 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17782 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17783 if (DEBUG_SETTINGS) { 17784 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17785 } 17786 17787 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17788 17789 synchronized (mPackages) { 17790 // Verify that all of the preferred activity components actually 17791 // exist. It is possible for applications to be updated and at 17792 // that point remove a previously declared activity component that 17793 // had been set as a preferred activity. We try to clean this up 17794 // the next time we encounter that preferred activity, but it is 17795 // possible for the user flow to never be able to return to that 17796 // situation so here we do a sanity check to make sure we haven't 17797 // left any junk around. 17798 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17799 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17800 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17801 removed.clear(); 17802 for (PreferredActivity pa : pir.filterSet()) { 17803 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17804 removed.add(pa); 17805 } 17806 } 17807 if (removed.size() > 0) { 17808 for (int r=0; r<removed.size(); r++) { 17809 PreferredActivity pa = removed.get(r); 17810 Slog.w(TAG, "Removing dangling preferred activity: " 17811 + pa.mPref.mComponent); 17812 pir.removeFilter(pa); 17813 } 17814 mSettings.writePackageRestrictionsLPr( 17815 mSettings.mPreferredActivities.keyAt(i)); 17816 } 17817 } 17818 17819 for (int userId : UserManagerService.getInstance().getUserIds()) { 17820 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17821 grantPermissionsUserIds = ArrayUtils.appendInt( 17822 grantPermissionsUserIds, userId); 17823 } 17824 } 17825 } 17826 sUserManager.systemReady(); 17827 17828 // If we upgraded grant all default permissions before kicking off. 17829 for (int userId : grantPermissionsUserIds) { 17830 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17831 } 17832 17833 // Kick off any messages waiting for system ready 17834 if (mPostSystemReadyMessages != null) { 17835 for (Message msg : mPostSystemReadyMessages) { 17836 msg.sendToTarget(); 17837 } 17838 mPostSystemReadyMessages = null; 17839 } 17840 17841 // Watch for external volumes that come and go over time 17842 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17843 storage.registerListener(mStorageListener); 17844 17845 mInstallerService.systemReady(); 17846 mPackageDexOptimizer.systemReady(); 17847 17848 MountServiceInternal mountServiceInternal = LocalServices.getService( 17849 MountServiceInternal.class); 17850 mountServiceInternal.addExternalStoragePolicy( 17851 new MountServiceInternal.ExternalStorageMountPolicy() { 17852 @Override 17853 public int getMountMode(int uid, String packageName) { 17854 if (Process.isIsolated(uid)) { 17855 return Zygote.MOUNT_EXTERNAL_NONE; 17856 } 17857 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17858 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17859 } 17860 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17861 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17862 } 17863 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17864 return Zygote.MOUNT_EXTERNAL_READ; 17865 } 17866 return Zygote.MOUNT_EXTERNAL_WRITE; 17867 } 17868 17869 @Override 17870 public boolean hasExternalStorage(int uid, String packageName) { 17871 return true; 17872 } 17873 }); 17874 17875 // Now that we're mostly running, clean up stale users and apps 17876 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17877 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17878 } 17879 17880 @Override 17881 public boolean isSafeMode() { 17882 return mSafeMode; 17883 } 17884 17885 @Override 17886 public boolean hasSystemUidErrors() { 17887 return mHasSystemUidErrors; 17888 } 17889 17890 static String arrayToString(int[] array) { 17891 StringBuffer buf = new StringBuffer(128); 17892 buf.append('['); 17893 if (array != null) { 17894 for (int i=0; i<array.length; i++) { 17895 if (i > 0) buf.append(", "); 17896 buf.append(array[i]); 17897 } 17898 } 17899 buf.append(']'); 17900 return buf.toString(); 17901 } 17902 17903 static class DumpState { 17904 public static final int DUMP_LIBS = 1 << 0; 17905 public static final int DUMP_FEATURES = 1 << 1; 17906 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17907 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17908 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17909 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17910 public static final int DUMP_PERMISSIONS = 1 << 6; 17911 public static final int DUMP_PACKAGES = 1 << 7; 17912 public static final int DUMP_SHARED_USERS = 1 << 8; 17913 public static final int DUMP_MESSAGES = 1 << 9; 17914 public static final int DUMP_PROVIDERS = 1 << 10; 17915 public static final int DUMP_VERIFIERS = 1 << 11; 17916 public static final int DUMP_PREFERRED = 1 << 12; 17917 public static final int DUMP_PREFERRED_XML = 1 << 13; 17918 public static final int DUMP_KEYSETS = 1 << 14; 17919 public static final int DUMP_VERSION = 1 << 15; 17920 public static final int DUMP_INSTALLS = 1 << 16; 17921 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17922 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17923 public static final int DUMP_FROZEN = 1 << 19; 17924 public static final int DUMP_DEXOPT = 1 << 20; 17925 17926 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17927 17928 private int mTypes; 17929 17930 private int mOptions; 17931 17932 private boolean mTitlePrinted; 17933 17934 private SharedUserSetting mSharedUser; 17935 17936 public boolean isDumping(int type) { 17937 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17938 return true; 17939 } 17940 17941 return (mTypes & type) != 0; 17942 } 17943 17944 public void setDump(int type) { 17945 mTypes |= type; 17946 } 17947 17948 public boolean isOptionEnabled(int option) { 17949 return (mOptions & option) != 0; 17950 } 17951 17952 public void setOptionEnabled(int option) { 17953 mOptions |= option; 17954 } 17955 17956 public boolean onTitlePrinted() { 17957 final boolean printed = mTitlePrinted; 17958 mTitlePrinted = true; 17959 return printed; 17960 } 17961 17962 public boolean getTitlePrinted() { 17963 return mTitlePrinted; 17964 } 17965 17966 public void setTitlePrinted(boolean enabled) { 17967 mTitlePrinted = enabled; 17968 } 17969 17970 public SharedUserSetting getSharedUser() { 17971 return mSharedUser; 17972 } 17973 17974 public void setSharedUser(SharedUserSetting user) { 17975 mSharedUser = user; 17976 } 17977 } 17978 17979 @Override 17980 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17981 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17982 (new PackageManagerShellCommand(this)).exec( 17983 this, in, out, err, args, resultReceiver); 17984 } 17985 17986 @Override 17987 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17988 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17989 != PackageManager.PERMISSION_GRANTED) { 17990 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17991 + Binder.getCallingPid() 17992 + ", uid=" + Binder.getCallingUid() 17993 + " without permission " 17994 + android.Manifest.permission.DUMP); 17995 return; 17996 } 17997 17998 DumpState dumpState = new DumpState(); 17999 boolean fullPreferred = false; 18000 boolean checkin = false; 18001 18002 String packageName = null; 18003 ArraySet<String> permissionNames = null; 18004 18005 int opti = 0; 18006 while (opti < args.length) { 18007 String opt = args[opti]; 18008 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18009 break; 18010 } 18011 opti++; 18012 18013 if ("-a".equals(opt)) { 18014 // Right now we only know how to print all. 18015 } else if ("-h".equals(opt)) { 18016 pw.println("Package manager dump options:"); 18017 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18018 pw.println(" --checkin: dump for a checkin"); 18019 pw.println(" -f: print details of intent filters"); 18020 pw.println(" -h: print this help"); 18021 pw.println(" cmd may be one of:"); 18022 pw.println(" l[ibraries]: list known shared libraries"); 18023 pw.println(" f[eatures]: list device features"); 18024 pw.println(" k[eysets]: print known keysets"); 18025 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18026 pw.println(" perm[issions]: dump permissions"); 18027 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18028 pw.println(" pref[erred]: print preferred package settings"); 18029 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18030 pw.println(" prov[iders]: dump content providers"); 18031 pw.println(" p[ackages]: dump installed packages"); 18032 pw.println(" s[hared-users]: dump shared user IDs"); 18033 pw.println(" m[essages]: print collected runtime messages"); 18034 pw.println(" v[erifiers]: print package verifier info"); 18035 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18036 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18037 pw.println(" version: print database version info"); 18038 pw.println(" write: write current settings now"); 18039 pw.println(" installs: details about install sessions"); 18040 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18041 pw.println(" dexopt: dump dexopt state"); 18042 pw.println(" <package.name>: info about given package"); 18043 return; 18044 } else if ("--checkin".equals(opt)) { 18045 checkin = true; 18046 } else if ("-f".equals(opt)) { 18047 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18048 } else { 18049 pw.println("Unknown argument: " + opt + "; use -h for help"); 18050 } 18051 } 18052 18053 // Is the caller requesting to dump a particular piece of data? 18054 if (opti < args.length) { 18055 String cmd = args[opti]; 18056 opti++; 18057 // Is this a package name? 18058 if ("android".equals(cmd) || cmd.contains(".")) { 18059 packageName = cmd; 18060 // When dumping a single package, we always dump all of its 18061 // filter information since the amount of data will be reasonable. 18062 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18063 } else if ("check-permission".equals(cmd)) { 18064 if (opti >= args.length) { 18065 pw.println("Error: check-permission missing permission argument"); 18066 return; 18067 } 18068 String perm = args[opti]; 18069 opti++; 18070 if (opti >= args.length) { 18071 pw.println("Error: check-permission missing package argument"); 18072 return; 18073 } 18074 String pkg = args[opti]; 18075 opti++; 18076 int user = UserHandle.getUserId(Binder.getCallingUid()); 18077 if (opti < args.length) { 18078 try { 18079 user = Integer.parseInt(args[opti]); 18080 } catch (NumberFormatException e) { 18081 pw.println("Error: check-permission user argument is not a number: " 18082 + args[opti]); 18083 return; 18084 } 18085 } 18086 pw.println(checkPermission(perm, pkg, user)); 18087 return; 18088 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18089 dumpState.setDump(DumpState.DUMP_LIBS); 18090 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18091 dumpState.setDump(DumpState.DUMP_FEATURES); 18092 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18093 if (opti >= args.length) { 18094 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18095 | DumpState.DUMP_SERVICE_RESOLVERS 18096 | DumpState.DUMP_RECEIVER_RESOLVERS 18097 | DumpState.DUMP_CONTENT_RESOLVERS); 18098 } else { 18099 while (opti < args.length) { 18100 String name = args[opti]; 18101 if ("a".equals(name) || "activity".equals(name)) { 18102 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18103 } else if ("s".equals(name) || "service".equals(name)) { 18104 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18105 } else if ("r".equals(name) || "receiver".equals(name)) { 18106 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18107 } else if ("c".equals(name) || "content".equals(name)) { 18108 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18109 } else { 18110 pw.println("Error: unknown resolver table type: " + name); 18111 return; 18112 } 18113 opti++; 18114 } 18115 } 18116 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18117 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18118 } else if ("permission".equals(cmd)) { 18119 if (opti >= args.length) { 18120 pw.println("Error: permission requires permission name"); 18121 return; 18122 } 18123 permissionNames = new ArraySet<>(); 18124 while (opti < args.length) { 18125 permissionNames.add(args[opti]); 18126 opti++; 18127 } 18128 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18129 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18130 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18131 dumpState.setDump(DumpState.DUMP_PREFERRED); 18132 } else if ("preferred-xml".equals(cmd)) { 18133 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18134 if (opti < args.length && "--full".equals(args[opti])) { 18135 fullPreferred = true; 18136 opti++; 18137 } 18138 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18139 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18140 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18141 dumpState.setDump(DumpState.DUMP_PACKAGES); 18142 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18143 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18144 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18145 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18146 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18147 dumpState.setDump(DumpState.DUMP_MESSAGES); 18148 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18149 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18150 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18151 || "intent-filter-verifiers".equals(cmd)) { 18152 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18153 } else if ("version".equals(cmd)) { 18154 dumpState.setDump(DumpState.DUMP_VERSION); 18155 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18156 dumpState.setDump(DumpState.DUMP_KEYSETS); 18157 } else if ("installs".equals(cmd)) { 18158 dumpState.setDump(DumpState.DUMP_INSTALLS); 18159 } else if ("frozen".equals(cmd)) { 18160 dumpState.setDump(DumpState.DUMP_FROZEN); 18161 } else if ("dexopt".equals(cmd)) { 18162 dumpState.setDump(DumpState.DUMP_DEXOPT); 18163 } else if ("write".equals(cmd)) { 18164 synchronized (mPackages) { 18165 mSettings.writeLPr(); 18166 pw.println("Settings written."); 18167 return; 18168 } 18169 } 18170 } 18171 18172 if (checkin) { 18173 pw.println("vers,1"); 18174 } 18175 18176 // reader 18177 synchronized (mPackages) { 18178 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18179 if (!checkin) { 18180 if (dumpState.onTitlePrinted()) 18181 pw.println(); 18182 pw.println("Database versions:"); 18183 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18184 } 18185 } 18186 18187 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18188 if (!checkin) { 18189 if (dumpState.onTitlePrinted()) 18190 pw.println(); 18191 pw.println("Verifiers:"); 18192 pw.print(" Required: "); 18193 pw.print(mRequiredVerifierPackage); 18194 pw.print(" (uid="); 18195 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18196 UserHandle.USER_SYSTEM)); 18197 pw.println(")"); 18198 } else if (mRequiredVerifierPackage != null) { 18199 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18200 pw.print(","); 18201 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18202 UserHandle.USER_SYSTEM)); 18203 } 18204 } 18205 18206 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18207 packageName == null) { 18208 if (mIntentFilterVerifierComponent != null) { 18209 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18210 if (!checkin) { 18211 if (dumpState.onTitlePrinted()) 18212 pw.println(); 18213 pw.println("Intent Filter Verifier:"); 18214 pw.print(" Using: "); 18215 pw.print(verifierPackageName); 18216 pw.print(" (uid="); 18217 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18218 UserHandle.USER_SYSTEM)); 18219 pw.println(")"); 18220 } else if (verifierPackageName != null) { 18221 pw.print("ifv,"); pw.print(verifierPackageName); 18222 pw.print(","); 18223 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18224 UserHandle.USER_SYSTEM)); 18225 } 18226 } else { 18227 pw.println(); 18228 pw.println("No Intent Filter Verifier available!"); 18229 } 18230 } 18231 18232 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18233 boolean printedHeader = false; 18234 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18235 while (it.hasNext()) { 18236 String name = it.next(); 18237 SharedLibraryEntry ent = mSharedLibraries.get(name); 18238 if (!checkin) { 18239 if (!printedHeader) { 18240 if (dumpState.onTitlePrinted()) 18241 pw.println(); 18242 pw.println("Libraries:"); 18243 printedHeader = true; 18244 } 18245 pw.print(" "); 18246 } else { 18247 pw.print("lib,"); 18248 } 18249 pw.print(name); 18250 if (!checkin) { 18251 pw.print(" -> "); 18252 } 18253 if (ent.path != null) { 18254 if (!checkin) { 18255 pw.print("(jar) "); 18256 pw.print(ent.path); 18257 } else { 18258 pw.print(",jar,"); 18259 pw.print(ent.path); 18260 } 18261 } else { 18262 if (!checkin) { 18263 pw.print("(apk) "); 18264 pw.print(ent.apk); 18265 } else { 18266 pw.print(",apk,"); 18267 pw.print(ent.apk); 18268 } 18269 } 18270 pw.println(); 18271 } 18272 } 18273 18274 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18275 if (dumpState.onTitlePrinted()) 18276 pw.println(); 18277 if (!checkin) { 18278 pw.println("Features:"); 18279 } 18280 18281 for (FeatureInfo feat : mAvailableFeatures.values()) { 18282 if (checkin) { 18283 pw.print("feat,"); 18284 pw.print(feat.name); 18285 pw.print(","); 18286 pw.println(feat.version); 18287 } else { 18288 pw.print(" "); 18289 pw.print(feat.name); 18290 if (feat.version > 0) { 18291 pw.print(" version="); 18292 pw.print(feat.version); 18293 } 18294 pw.println(); 18295 } 18296 } 18297 } 18298 18299 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18300 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18301 : "Activity Resolver Table:", " ", packageName, 18302 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18303 dumpState.setTitlePrinted(true); 18304 } 18305 } 18306 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18307 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18308 : "Receiver Resolver Table:", " ", packageName, 18309 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18310 dumpState.setTitlePrinted(true); 18311 } 18312 } 18313 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18314 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18315 : "Service Resolver Table:", " ", packageName, 18316 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18317 dumpState.setTitlePrinted(true); 18318 } 18319 } 18320 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18321 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18322 : "Provider Resolver Table:", " ", packageName, 18323 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18324 dumpState.setTitlePrinted(true); 18325 } 18326 } 18327 18328 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18329 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18330 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18331 int user = mSettings.mPreferredActivities.keyAt(i); 18332 if (pir.dump(pw, 18333 dumpState.getTitlePrinted() 18334 ? "\nPreferred Activities User " + user + ":" 18335 : "Preferred Activities User " + user + ":", " ", 18336 packageName, true, false)) { 18337 dumpState.setTitlePrinted(true); 18338 } 18339 } 18340 } 18341 18342 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18343 pw.flush(); 18344 FileOutputStream fout = new FileOutputStream(fd); 18345 BufferedOutputStream str = new BufferedOutputStream(fout); 18346 XmlSerializer serializer = new FastXmlSerializer(); 18347 try { 18348 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18349 serializer.startDocument(null, true); 18350 serializer.setFeature( 18351 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18352 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18353 serializer.endDocument(); 18354 serializer.flush(); 18355 } catch (IllegalArgumentException e) { 18356 pw.println("Failed writing: " + e); 18357 } catch (IllegalStateException e) { 18358 pw.println("Failed writing: " + e); 18359 } catch (IOException e) { 18360 pw.println("Failed writing: " + e); 18361 } 18362 } 18363 18364 if (!checkin 18365 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18366 && packageName == null) { 18367 pw.println(); 18368 int count = mSettings.mPackages.size(); 18369 if (count == 0) { 18370 pw.println("No applications!"); 18371 pw.println(); 18372 } else { 18373 final String prefix = " "; 18374 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18375 if (allPackageSettings.size() == 0) { 18376 pw.println("No domain preferred apps!"); 18377 pw.println(); 18378 } else { 18379 pw.println("App verification status:"); 18380 pw.println(); 18381 count = 0; 18382 for (PackageSetting ps : allPackageSettings) { 18383 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18384 if (ivi == null || ivi.getPackageName() == null) continue; 18385 pw.println(prefix + "Package: " + ivi.getPackageName()); 18386 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18387 pw.println(prefix + "Status: " + ivi.getStatusString()); 18388 pw.println(); 18389 count++; 18390 } 18391 if (count == 0) { 18392 pw.println(prefix + "No app verification established."); 18393 pw.println(); 18394 } 18395 for (int userId : sUserManager.getUserIds()) { 18396 pw.println("App linkages for user " + userId + ":"); 18397 pw.println(); 18398 count = 0; 18399 for (PackageSetting ps : allPackageSettings) { 18400 final long status = ps.getDomainVerificationStatusForUser(userId); 18401 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18402 continue; 18403 } 18404 pw.println(prefix + "Package: " + ps.name); 18405 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18406 String statusStr = IntentFilterVerificationInfo. 18407 getStatusStringFromValue(status); 18408 pw.println(prefix + "Status: " + statusStr); 18409 pw.println(); 18410 count++; 18411 } 18412 if (count == 0) { 18413 pw.println(prefix + "No configured app linkages."); 18414 pw.println(); 18415 } 18416 } 18417 } 18418 } 18419 } 18420 18421 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18422 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18423 if (packageName == null && permissionNames == null) { 18424 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18425 if (iperm == 0) { 18426 if (dumpState.onTitlePrinted()) 18427 pw.println(); 18428 pw.println("AppOp Permissions:"); 18429 } 18430 pw.print(" AppOp Permission "); 18431 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18432 pw.println(":"); 18433 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18434 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18435 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18436 } 18437 } 18438 } 18439 } 18440 18441 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18442 boolean printedSomething = false; 18443 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18444 if (packageName != null && !packageName.equals(p.info.packageName)) { 18445 continue; 18446 } 18447 if (!printedSomething) { 18448 if (dumpState.onTitlePrinted()) 18449 pw.println(); 18450 pw.println("Registered ContentProviders:"); 18451 printedSomething = true; 18452 } 18453 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18454 pw.print(" "); pw.println(p.toString()); 18455 } 18456 printedSomething = false; 18457 for (Map.Entry<String, PackageParser.Provider> entry : 18458 mProvidersByAuthority.entrySet()) { 18459 PackageParser.Provider p = entry.getValue(); 18460 if (packageName != null && !packageName.equals(p.info.packageName)) { 18461 continue; 18462 } 18463 if (!printedSomething) { 18464 if (dumpState.onTitlePrinted()) 18465 pw.println(); 18466 pw.println("ContentProvider Authorities:"); 18467 printedSomething = true; 18468 } 18469 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18470 pw.print(" "); pw.println(p.toString()); 18471 if (p.info != null && p.info.applicationInfo != null) { 18472 final String appInfo = p.info.applicationInfo.toString(); 18473 pw.print(" applicationInfo="); pw.println(appInfo); 18474 } 18475 } 18476 } 18477 18478 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18479 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18480 } 18481 18482 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18483 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18484 } 18485 18486 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18487 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18488 } 18489 18490 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18491 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18492 } 18493 18494 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18495 // XXX should handle packageName != null by dumping only install data that 18496 // the given package is involved with. 18497 if (dumpState.onTitlePrinted()) pw.println(); 18498 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18499 } 18500 18501 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18502 // XXX should handle packageName != null by dumping only install data that 18503 // the given package is involved with. 18504 if (dumpState.onTitlePrinted()) pw.println(); 18505 18506 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18507 ipw.println(); 18508 ipw.println("Frozen packages:"); 18509 ipw.increaseIndent(); 18510 if (mFrozenPackages.size() == 0) { 18511 ipw.println("(none)"); 18512 } else { 18513 for (int i = 0; i < mFrozenPackages.size(); i++) { 18514 ipw.println(mFrozenPackages.valueAt(i)); 18515 } 18516 } 18517 ipw.decreaseIndent(); 18518 } 18519 18520 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18521 if (dumpState.onTitlePrinted()) pw.println(); 18522 dumpDexoptStateLPr(pw, packageName); 18523 } 18524 18525 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18526 if (dumpState.onTitlePrinted()) pw.println(); 18527 mSettings.dumpReadMessagesLPr(pw, dumpState); 18528 18529 pw.println(); 18530 pw.println("Package warning messages:"); 18531 BufferedReader in = null; 18532 String line = null; 18533 try { 18534 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18535 while ((line = in.readLine()) != null) { 18536 if (line.contains("ignored: updated version")) continue; 18537 pw.println(line); 18538 } 18539 } catch (IOException ignored) { 18540 } finally { 18541 IoUtils.closeQuietly(in); 18542 } 18543 } 18544 18545 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18546 BufferedReader in = null; 18547 String line = null; 18548 try { 18549 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18550 while ((line = in.readLine()) != null) { 18551 if (line.contains("ignored: updated version")) continue; 18552 pw.print("msg,"); 18553 pw.println(line); 18554 } 18555 } catch (IOException ignored) { 18556 } finally { 18557 IoUtils.closeQuietly(in); 18558 } 18559 } 18560 } 18561 } 18562 18563 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18564 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18565 ipw.println(); 18566 ipw.println("Dexopt state:"); 18567 ipw.increaseIndent(); 18568 Collection<PackageParser.Package> packages = null; 18569 if (packageName != null) { 18570 PackageParser.Package targetPackage = mPackages.get(packageName); 18571 if (targetPackage != null) { 18572 packages = Collections.singletonList(targetPackage); 18573 } else { 18574 ipw.println("Unable to find package: " + packageName); 18575 return; 18576 } 18577 } else { 18578 packages = mPackages.values(); 18579 } 18580 18581 for (PackageParser.Package pkg : packages) { 18582 ipw.println("[" + pkg.packageName + "]"); 18583 ipw.increaseIndent(); 18584 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18585 ipw.decreaseIndent(); 18586 } 18587 } 18588 18589 private String dumpDomainString(String packageName) { 18590 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18591 .getList(); 18592 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18593 18594 ArraySet<String> result = new ArraySet<>(); 18595 if (iviList.size() > 0) { 18596 for (IntentFilterVerificationInfo ivi : iviList) { 18597 for (String host : ivi.getDomains()) { 18598 result.add(host); 18599 } 18600 } 18601 } 18602 if (filters != null && filters.size() > 0) { 18603 for (IntentFilter filter : filters) { 18604 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18605 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18606 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18607 result.addAll(filter.getHostsList()); 18608 } 18609 } 18610 } 18611 18612 StringBuilder sb = new StringBuilder(result.size() * 16); 18613 for (String domain : result) { 18614 if (sb.length() > 0) sb.append(" "); 18615 sb.append(domain); 18616 } 18617 return sb.toString(); 18618 } 18619 18620 // ------- apps on sdcard specific code ------- 18621 static final boolean DEBUG_SD_INSTALL = false; 18622 18623 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18624 18625 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18626 18627 private boolean mMediaMounted = false; 18628 18629 static String getEncryptKey() { 18630 try { 18631 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18632 SD_ENCRYPTION_KEYSTORE_NAME); 18633 if (sdEncKey == null) { 18634 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18635 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18636 if (sdEncKey == null) { 18637 Slog.e(TAG, "Failed to create encryption keys"); 18638 return null; 18639 } 18640 } 18641 return sdEncKey; 18642 } catch (NoSuchAlgorithmException nsae) { 18643 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18644 return null; 18645 } catch (IOException ioe) { 18646 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18647 return null; 18648 } 18649 } 18650 18651 /* 18652 * Update media status on PackageManager. 18653 */ 18654 @Override 18655 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18656 int callingUid = Binder.getCallingUid(); 18657 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18658 throw new SecurityException("Media status can only be updated by the system"); 18659 } 18660 // reader; this apparently protects mMediaMounted, but should probably 18661 // be a different lock in that case. 18662 synchronized (mPackages) { 18663 Log.i(TAG, "Updating external media status from " 18664 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18665 + (mediaStatus ? "mounted" : "unmounted")); 18666 if (DEBUG_SD_INSTALL) 18667 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18668 + ", mMediaMounted=" + mMediaMounted); 18669 if (mediaStatus == mMediaMounted) { 18670 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18671 : 0, -1); 18672 mHandler.sendMessage(msg); 18673 return; 18674 } 18675 mMediaMounted = mediaStatus; 18676 } 18677 // Queue up an async operation since the package installation may take a 18678 // little while. 18679 mHandler.post(new Runnable() { 18680 public void run() { 18681 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18682 } 18683 }); 18684 } 18685 18686 /** 18687 * Called by MountService when the initial ASECs to scan are available. 18688 * Should block until all the ASEC containers are finished being scanned. 18689 */ 18690 public void scanAvailableAsecs() { 18691 updateExternalMediaStatusInner(true, false, false); 18692 } 18693 18694 /* 18695 * Collect information of applications on external media, map them against 18696 * existing containers and update information based on current mount status. 18697 * Please note that we always have to report status if reportStatus has been 18698 * set to true especially when unloading packages. 18699 */ 18700 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18701 boolean externalStorage) { 18702 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18703 int[] uidArr = EmptyArray.INT; 18704 18705 final String[] list = PackageHelper.getSecureContainerList(); 18706 if (ArrayUtils.isEmpty(list)) { 18707 Log.i(TAG, "No secure containers found"); 18708 } else { 18709 // Process list of secure containers and categorize them 18710 // as active or stale based on their package internal state. 18711 18712 // reader 18713 synchronized (mPackages) { 18714 for (String cid : list) { 18715 // Leave stages untouched for now; installer service owns them 18716 if (PackageInstallerService.isStageName(cid)) continue; 18717 18718 if (DEBUG_SD_INSTALL) 18719 Log.i(TAG, "Processing container " + cid); 18720 String pkgName = getAsecPackageName(cid); 18721 if (pkgName == null) { 18722 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18723 continue; 18724 } 18725 if (DEBUG_SD_INSTALL) 18726 Log.i(TAG, "Looking for pkg : " + pkgName); 18727 18728 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18729 if (ps == null) { 18730 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18731 continue; 18732 } 18733 18734 /* 18735 * Skip packages that are not external if we're unmounting 18736 * external storage. 18737 */ 18738 if (externalStorage && !isMounted && !isExternal(ps)) { 18739 continue; 18740 } 18741 18742 final AsecInstallArgs args = new AsecInstallArgs(cid, 18743 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18744 // The package status is changed only if the code path 18745 // matches between settings and the container id. 18746 if (ps.codePathString != null 18747 && ps.codePathString.startsWith(args.getCodePath())) { 18748 if (DEBUG_SD_INSTALL) { 18749 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18750 + " at code path: " + ps.codePathString); 18751 } 18752 18753 // We do have a valid package installed on sdcard 18754 processCids.put(args, ps.codePathString); 18755 final int uid = ps.appId; 18756 if (uid != -1) { 18757 uidArr = ArrayUtils.appendInt(uidArr, uid); 18758 } 18759 } else { 18760 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18761 + ps.codePathString); 18762 } 18763 } 18764 } 18765 18766 Arrays.sort(uidArr); 18767 } 18768 18769 // Process packages with valid entries. 18770 if (isMounted) { 18771 if (DEBUG_SD_INSTALL) 18772 Log.i(TAG, "Loading packages"); 18773 loadMediaPackages(processCids, uidArr, externalStorage); 18774 startCleaningPackages(); 18775 mInstallerService.onSecureContainersAvailable(); 18776 } else { 18777 if (DEBUG_SD_INSTALL) 18778 Log.i(TAG, "Unloading packages"); 18779 unloadMediaPackages(processCids, uidArr, reportStatus); 18780 } 18781 } 18782 18783 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18784 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18785 final int size = infos.size(); 18786 final String[] packageNames = new String[size]; 18787 final int[] packageUids = new int[size]; 18788 for (int i = 0; i < size; i++) { 18789 final ApplicationInfo info = infos.get(i); 18790 packageNames[i] = info.packageName; 18791 packageUids[i] = info.uid; 18792 } 18793 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18794 finishedReceiver); 18795 } 18796 18797 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18798 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18799 sendResourcesChangedBroadcast(mediaStatus, replacing, 18800 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18801 } 18802 18803 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18804 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18805 int size = pkgList.length; 18806 if (size > 0) { 18807 // Send broadcasts here 18808 Bundle extras = new Bundle(); 18809 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18810 if (uidArr != null) { 18811 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18812 } 18813 if (replacing) { 18814 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18815 } 18816 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18817 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18818 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18819 } 18820 } 18821 18822 /* 18823 * Look at potentially valid container ids from processCids If package 18824 * information doesn't match the one on record or package scanning fails, 18825 * the cid is added to list of removeCids. We currently don't delete stale 18826 * containers. 18827 */ 18828 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18829 boolean externalStorage) { 18830 ArrayList<String> pkgList = new ArrayList<String>(); 18831 Set<AsecInstallArgs> keys = processCids.keySet(); 18832 18833 for (AsecInstallArgs args : keys) { 18834 String codePath = processCids.get(args); 18835 if (DEBUG_SD_INSTALL) 18836 Log.i(TAG, "Loading container : " + args.cid); 18837 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18838 try { 18839 // Make sure there are no container errors first. 18840 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18841 Slog.e(TAG, "Failed to mount cid : " + args.cid 18842 + " when installing from sdcard"); 18843 continue; 18844 } 18845 // Check code path here. 18846 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18847 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18848 + " does not match one in settings " + codePath); 18849 continue; 18850 } 18851 // Parse package 18852 int parseFlags = mDefParseFlags; 18853 if (args.isExternalAsec()) { 18854 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18855 } 18856 if (args.isFwdLocked()) { 18857 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18858 } 18859 18860 synchronized (mInstallLock) { 18861 PackageParser.Package pkg = null; 18862 try { 18863 // Sadly we don't know the package name yet to freeze it 18864 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18865 SCAN_IGNORE_FROZEN, 0, null); 18866 } catch (PackageManagerException e) { 18867 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18868 } 18869 // Scan the package 18870 if (pkg != null) { 18871 /* 18872 * TODO why is the lock being held? doPostInstall is 18873 * called in other places without the lock. This needs 18874 * to be straightened out. 18875 */ 18876 // writer 18877 synchronized (mPackages) { 18878 retCode = PackageManager.INSTALL_SUCCEEDED; 18879 pkgList.add(pkg.packageName); 18880 // Post process args 18881 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18882 pkg.applicationInfo.uid); 18883 } 18884 } else { 18885 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18886 } 18887 } 18888 18889 } finally { 18890 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18891 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18892 } 18893 } 18894 } 18895 // writer 18896 synchronized (mPackages) { 18897 // If the platform SDK has changed since the last time we booted, 18898 // we need to re-grant app permission to catch any new ones that 18899 // appear. This is really a hack, and means that apps can in some 18900 // cases get permissions that the user didn't initially explicitly 18901 // allow... it would be nice to have some better way to handle 18902 // this situation. 18903 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18904 : mSettings.getInternalVersion(); 18905 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18906 : StorageManager.UUID_PRIVATE_INTERNAL; 18907 18908 int updateFlags = UPDATE_PERMISSIONS_ALL; 18909 if (ver.sdkVersion != mSdkVersion) { 18910 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18911 + mSdkVersion + "; regranting permissions for external"); 18912 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18913 } 18914 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18915 18916 // Yay, everything is now upgraded 18917 ver.forceCurrent(); 18918 18919 // can downgrade to reader 18920 // Persist settings 18921 mSettings.writeLPr(); 18922 } 18923 // Send a broadcast to let everyone know we are done processing 18924 if (pkgList.size() > 0) { 18925 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18926 } 18927 } 18928 18929 /* 18930 * Utility method to unload a list of specified containers 18931 */ 18932 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18933 // Just unmount all valid containers. 18934 for (AsecInstallArgs arg : cidArgs) { 18935 synchronized (mInstallLock) { 18936 arg.doPostDeleteLI(false); 18937 } 18938 } 18939 } 18940 18941 /* 18942 * Unload packages mounted on external media. This involves deleting package 18943 * data from internal structures, sending broadcasts about disabled packages, 18944 * gc'ing to free up references, unmounting all secure containers 18945 * corresponding to packages on external media, and posting a 18946 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18947 * that we always have to post this message if status has been requested no 18948 * matter what. 18949 */ 18950 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18951 final boolean reportStatus) { 18952 if (DEBUG_SD_INSTALL) 18953 Log.i(TAG, "unloading media packages"); 18954 ArrayList<String> pkgList = new ArrayList<String>(); 18955 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18956 final Set<AsecInstallArgs> keys = processCids.keySet(); 18957 for (AsecInstallArgs args : keys) { 18958 String pkgName = args.getPackageName(); 18959 if (DEBUG_SD_INSTALL) 18960 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18961 // Delete package internally 18962 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18963 synchronized (mInstallLock) { 18964 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18965 final boolean res; 18966 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18967 "unloadMediaPackages")) { 18968 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18969 null); 18970 } 18971 if (res) { 18972 pkgList.add(pkgName); 18973 } else { 18974 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18975 failedList.add(args); 18976 } 18977 } 18978 } 18979 18980 // reader 18981 synchronized (mPackages) { 18982 // We didn't update the settings after removing each package; 18983 // write them now for all packages. 18984 mSettings.writeLPr(); 18985 } 18986 18987 // We have to absolutely send UPDATED_MEDIA_STATUS only 18988 // after confirming that all the receivers processed the ordered 18989 // broadcast when packages get disabled, force a gc to clean things up. 18990 // and unload all the containers. 18991 if (pkgList.size() > 0) { 18992 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18993 new IIntentReceiver.Stub() { 18994 public void performReceive(Intent intent, int resultCode, String data, 18995 Bundle extras, boolean ordered, boolean sticky, 18996 int sendingUser) throws RemoteException { 18997 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18998 reportStatus ? 1 : 0, 1, keys); 18999 mHandler.sendMessage(msg); 19000 } 19001 }); 19002 } else { 19003 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19004 keys); 19005 mHandler.sendMessage(msg); 19006 } 19007 } 19008 19009 private void loadPrivatePackages(final VolumeInfo vol) { 19010 mHandler.post(new Runnable() { 19011 @Override 19012 public void run() { 19013 loadPrivatePackagesInner(vol); 19014 } 19015 }); 19016 } 19017 19018 private void loadPrivatePackagesInner(VolumeInfo vol) { 19019 final String volumeUuid = vol.fsUuid; 19020 if (TextUtils.isEmpty(volumeUuid)) { 19021 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19022 return; 19023 } 19024 19025 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19026 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19027 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19028 19029 final VersionInfo ver; 19030 final List<PackageSetting> packages; 19031 synchronized (mPackages) { 19032 ver = mSettings.findOrCreateVersion(volumeUuid); 19033 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19034 } 19035 19036 for (PackageSetting ps : packages) { 19037 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19038 synchronized (mInstallLock) { 19039 final PackageParser.Package pkg; 19040 try { 19041 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19042 loaded.add(pkg.applicationInfo); 19043 19044 } catch (PackageManagerException e) { 19045 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19046 } 19047 19048 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19049 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19050 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19051 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19052 } 19053 } 19054 } 19055 19056 // Reconcile app data for all started/unlocked users 19057 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19058 final UserManager um = mContext.getSystemService(UserManager.class); 19059 UserManagerInternal umInternal = getUserManagerInternal(); 19060 for (UserInfo user : um.getUsers()) { 19061 final int flags; 19062 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19063 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19064 } else if (umInternal.isUserRunning(user.id)) { 19065 flags = StorageManager.FLAG_STORAGE_DE; 19066 } else { 19067 continue; 19068 } 19069 19070 try { 19071 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19072 synchronized (mInstallLock) { 19073 reconcileAppsDataLI(volumeUuid, user.id, flags); 19074 } 19075 } catch (IllegalStateException e) { 19076 // Device was probably ejected, and we'll process that event momentarily 19077 Slog.w(TAG, "Failed to prepare storage: " + e); 19078 } 19079 } 19080 19081 synchronized (mPackages) { 19082 int updateFlags = UPDATE_PERMISSIONS_ALL; 19083 if (ver.sdkVersion != mSdkVersion) { 19084 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19085 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19086 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19087 } 19088 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19089 19090 // Yay, everything is now upgraded 19091 ver.forceCurrent(); 19092 19093 mSettings.writeLPr(); 19094 } 19095 19096 for (PackageFreezer freezer : freezers) { 19097 freezer.close(); 19098 } 19099 19100 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19101 sendResourcesChangedBroadcast(true, false, loaded, null); 19102 } 19103 19104 private void unloadPrivatePackages(final VolumeInfo vol) { 19105 mHandler.post(new Runnable() { 19106 @Override 19107 public void run() { 19108 unloadPrivatePackagesInner(vol); 19109 } 19110 }); 19111 } 19112 19113 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19114 final String volumeUuid = vol.fsUuid; 19115 if (TextUtils.isEmpty(volumeUuid)) { 19116 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19117 return; 19118 } 19119 19120 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19121 synchronized (mInstallLock) { 19122 synchronized (mPackages) { 19123 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19124 for (PackageSetting ps : packages) { 19125 if (ps.pkg == null) continue; 19126 19127 final ApplicationInfo info = ps.pkg.applicationInfo; 19128 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19129 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19130 19131 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19132 "unloadPrivatePackagesInner")) { 19133 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19134 false, null)) { 19135 unloaded.add(info); 19136 } else { 19137 Slog.w(TAG, "Failed to unload " + ps.codePath); 19138 } 19139 } 19140 19141 // Try very hard to release any references to this package 19142 // so we don't risk the system server being killed due to 19143 // open FDs 19144 AttributeCache.instance().removePackage(ps.name); 19145 } 19146 19147 mSettings.writeLPr(); 19148 } 19149 } 19150 19151 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19152 sendResourcesChangedBroadcast(false, false, unloaded, null); 19153 19154 // Try very hard to release any references to this path so we don't risk 19155 // the system server being killed due to open FDs 19156 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19157 19158 for (int i = 0; i < 3; i++) { 19159 System.gc(); 19160 System.runFinalization(); 19161 } 19162 } 19163 19164 /** 19165 * Prepare storage areas for given user on all mounted devices. 19166 */ 19167 void prepareUserData(int userId, int userSerial, int flags) { 19168 synchronized (mInstallLock) { 19169 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19170 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19171 final String volumeUuid = vol.getFsUuid(); 19172 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19173 } 19174 } 19175 } 19176 19177 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19178 boolean allowRecover) { 19179 // Prepare storage and verify that serial numbers are consistent; if 19180 // there's a mismatch we need to destroy to avoid leaking data 19181 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19182 try { 19183 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19184 19185 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19186 UserManagerService.enforceSerialNumber( 19187 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19188 } 19189 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19190 UserManagerService.enforceSerialNumber( 19191 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19192 } 19193 19194 synchronized (mInstallLock) { 19195 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19196 } 19197 } catch (Exception e) { 19198 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19199 + " because we failed to prepare: " + e); 19200 destroyUserDataLI(volumeUuid, userId, 19201 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19202 19203 if (allowRecover) { 19204 // Try one last time; if we fail again we're really in trouble 19205 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19206 } 19207 } 19208 } 19209 19210 /** 19211 * Destroy storage areas for given user on all mounted devices. 19212 */ 19213 void destroyUserData(int userId, int flags) { 19214 synchronized (mInstallLock) { 19215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19216 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19217 final String volumeUuid = vol.getFsUuid(); 19218 destroyUserDataLI(volumeUuid, userId, flags); 19219 } 19220 } 19221 } 19222 19223 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19224 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19225 try { 19226 // Clean up app data, profile data, and media data 19227 mInstaller.destroyUserData(volumeUuid, userId, flags); 19228 19229 // Clean up system data 19230 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19231 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19232 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19233 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19234 } 19235 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19236 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19237 } 19238 } 19239 19240 // Data with special labels is now gone, so finish the job 19241 storage.destroyUserStorage(volumeUuid, userId, flags); 19242 19243 } catch (Exception e) { 19244 logCriticalInfo(Log.WARN, 19245 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19246 } 19247 } 19248 19249 /** 19250 * Examine all users present on given mounted volume, and destroy data 19251 * belonging to users that are no longer valid, or whose user ID has been 19252 * recycled. 19253 */ 19254 private void reconcileUsers(String volumeUuid) { 19255 final List<File> files = new ArrayList<>(); 19256 Collections.addAll(files, FileUtils 19257 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19258 Collections.addAll(files, FileUtils 19259 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19260 for (File file : files) { 19261 if (!file.isDirectory()) continue; 19262 19263 final int userId; 19264 final UserInfo info; 19265 try { 19266 userId = Integer.parseInt(file.getName()); 19267 info = sUserManager.getUserInfo(userId); 19268 } catch (NumberFormatException e) { 19269 Slog.w(TAG, "Invalid user directory " + file); 19270 continue; 19271 } 19272 19273 boolean destroyUser = false; 19274 if (info == null) { 19275 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19276 + " because no matching user was found"); 19277 destroyUser = true; 19278 } else if (!mOnlyCore) { 19279 try { 19280 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19281 } catch (IOException e) { 19282 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19283 + " because we failed to enforce serial number: " + e); 19284 destroyUser = true; 19285 } 19286 } 19287 19288 if (destroyUser) { 19289 synchronized (mInstallLock) { 19290 destroyUserDataLI(volumeUuid, userId, 19291 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19292 } 19293 } 19294 } 19295 } 19296 19297 private void assertPackageKnown(String volumeUuid, String packageName) 19298 throws PackageManagerException { 19299 synchronized (mPackages) { 19300 final PackageSetting ps = mSettings.mPackages.get(packageName); 19301 if (ps == null) { 19302 throw new PackageManagerException("Package " + packageName + " is unknown"); 19303 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19304 throw new PackageManagerException( 19305 "Package " + packageName + " found on unknown volume " + volumeUuid 19306 + "; expected volume " + ps.volumeUuid); 19307 } 19308 } 19309 } 19310 19311 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19312 throws PackageManagerException { 19313 synchronized (mPackages) { 19314 final PackageSetting ps = mSettings.mPackages.get(packageName); 19315 if (ps == null) { 19316 throw new PackageManagerException("Package " + packageName + " is unknown"); 19317 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19318 throw new PackageManagerException( 19319 "Package " + packageName + " found on unknown volume " + volumeUuid 19320 + "; expected volume " + ps.volumeUuid); 19321 } else if (!ps.getInstalled(userId)) { 19322 throw new PackageManagerException( 19323 "Package " + packageName + " not installed for user " + userId); 19324 } 19325 } 19326 } 19327 19328 /** 19329 * Examine all apps present on given mounted volume, and destroy apps that 19330 * aren't expected, either due to uninstallation or reinstallation on 19331 * another volume. 19332 */ 19333 private void reconcileApps(String volumeUuid) { 19334 final File[] files = FileUtils 19335 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19336 for (File file : files) { 19337 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19338 && !PackageInstallerService.isStageName(file.getName()); 19339 if (!isPackage) { 19340 // Ignore entries which are not packages 19341 continue; 19342 } 19343 19344 try { 19345 final PackageLite pkg = PackageParser.parsePackageLite(file, 19346 PackageParser.PARSE_MUST_BE_APK); 19347 assertPackageKnown(volumeUuid, pkg.packageName); 19348 19349 } catch (PackageParserException | PackageManagerException e) { 19350 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19351 synchronized (mInstallLock) { 19352 removeCodePathLI(file); 19353 } 19354 } 19355 } 19356 } 19357 19358 /** 19359 * Reconcile all app data for the given user. 19360 * <p> 19361 * Verifies that directories exist and that ownership and labeling is 19362 * correct for all installed apps on all mounted volumes. 19363 */ 19364 void reconcileAppsData(int userId, int flags) { 19365 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19366 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19367 final String volumeUuid = vol.getFsUuid(); 19368 synchronized (mInstallLock) { 19369 reconcileAppsDataLI(volumeUuid, userId, flags); 19370 } 19371 } 19372 } 19373 19374 /** 19375 * Reconcile all app data on given mounted volume. 19376 * <p> 19377 * Destroys app data that isn't expected, either due to uninstallation or 19378 * reinstallation on another volume. 19379 * <p> 19380 * Verifies that directories exist and that ownership and labeling is 19381 * correct for all installed apps. 19382 */ 19383 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19384 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19385 + Integer.toHexString(flags)); 19386 19387 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19388 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19389 19390 boolean restoreconNeeded = false; 19391 19392 // First look for stale data that doesn't belong, and check if things 19393 // have changed since we did our last restorecon 19394 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19395 if (StorageManager.isFileEncryptedNativeOrEmulated() 19396 && !StorageManager.isUserKeyUnlocked(userId)) { 19397 throw new RuntimeException( 19398 "Yikes, someone asked us to reconcile CE storage while " + userId 19399 + " was still locked; this would have caused massive data loss!"); 19400 } 19401 19402 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19403 19404 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19405 for (File file : files) { 19406 final String packageName = file.getName(); 19407 try { 19408 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19409 } catch (PackageManagerException e) { 19410 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19411 try { 19412 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19413 StorageManager.FLAG_STORAGE_CE, 0); 19414 } catch (InstallerException e2) { 19415 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19416 } 19417 } 19418 } 19419 } 19420 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19421 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19422 19423 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19424 for (File file : files) { 19425 final String packageName = file.getName(); 19426 try { 19427 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19428 } catch (PackageManagerException e) { 19429 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19430 try { 19431 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19432 StorageManager.FLAG_STORAGE_DE, 0); 19433 } catch (InstallerException e2) { 19434 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19435 } 19436 } 19437 } 19438 } 19439 19440 // Ensure that data directories are ready to roll for all packages 19441 // installed for this volume and user 19442 final List<PackageSetting> packages; 19443 synchronized (mPackages) { 19444 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19445 } 19446 int preparedCount = 0; 19447 for (PackageSetting ps : packages) { 19448 final String packageName = ps.name; 19449 if (ps.pkg == null) { 19450 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19451 // TODO: might be due to legacy ASEC apps; we should circle back 19452 // and reconcile again once they're scanned 19453 continue; 19454 } 19455 19456 if (ps.getInstalled(userId)) { 19457 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19458 19459 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19460 // We may have just shuffled around app data directories, so 19461 // prepare them one more time 19462 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19463 } 19464 19465 preparedCount++; 19466 } 19467 } 19468 19469 if (restoreconNeeded) { 19470 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19471 SELinuxMMAC.setRestoreconDone(ceDir); 19472 } 19473 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19474 SELinuxMMAC.setRestoreconDone(deDir); 19475 } 19476 } 19477 19478 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19479 + " packages; restoreconNeeded was " + restoreconNeeded); 19480 } 19481 19482 /** 19483 * Prepare app data for the given app just after it was installed or 19484 * upgraded. This method carefully only touches users that it's installed 19485 * for, and it forces a restorecon to handle any seinfo changes. 19486 * <p> 19487 * Verifies that directories exist and that ownership and labeling is 19488 * correct for all installed apps. If there is an ownership mismatch, it 19489 * will try recovering system apps by wiping data; third-party app data is 19490 * left intact. 19491 * <p> 19492 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19493 */ 19494 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19495 final PackageSetting ps; 19496 synchronized (mPackages) { 19497 ps = mSettings.mPackages.get(pkg.packageName); 19498 mSettings.writeKernelMappingLPr(ps); 19499 } 19500 19501 final UserManager um = mContext.getSystemService(UserManager.class); 19502 UserManagerInternal umInternal = getUserManagerInternal(); 19503 for (UserInfo user : um.getUsers()) { 19504 final int flags; 19505 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19506 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19507 } else if (umInternal.isUserRunning(user.id)) { 19508 flags = StorageManager.FLAG_STORAGE_DE; 19509 } else { 19510 continue; 19511 } 19512 19513 if (ps.getInstalled(user.id)) { 19514 // Whenever an app changes, force a restorecon of its data 19515 // TODO: when user data is locked, mark that we're still dirty 19516 prepareAppDataLIF(pkg, user.id, flags, true); 19517 } 19518 } 19519 } 19520 19521 /** 19522 * Prepare app data for the given app. 19523 * <p> 19524 * Verifies that directories exist and that ownership and labeling is 19525 * correct for all installed apps. If there is an ownership mismatch, this 19526 * will try recovering system apps by wiping data; third-party app data is 19527 * left intact. 19528 */ 19529 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19530 boolean restoreconNeeded) { 19531 if (pkg == null) { 19532 Slog.wtf(TAG, "Package was null!", new Throwable()); 19533 return; 19534 } 19535 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19537 for (int i = 0; i < childCount; i++) { 19538 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19539 } 19540 } 19541 19542 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19543 boolean restoreconNeeded) { 19544 if (DEBUG_APP_DATA) { 19545 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19546 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19547 } 19548 19549 final String volumeUuid = pkg.volumeUuid; 19550 final String packageName = pkg.packageName; 19551 final ApplicationInfo app = pkg.applicationInfo; 19552 final int appId = UserHandle.getAppId(app.uid); 19553 19554 Preconditions.checkNotNull(app.seinfo); 19555 19556 try { 19557 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19558 appId, app.seinfo, app.targetSdkVersion); 19559 } catch (InstallerException e) { 19560 if (app.isSystemApp()) { 19561 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19562 + ", but trying to recover: " + e); 19563 destroyAppDataLeafLIF(pkg, userId, flags); 19564 try { 19565 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19566 appId, app.seinfo, app.targetSdkVersion); 19567 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19568 } catch (InstallerException e2) { 19569 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19570 } 19571 } else { 19572 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19573 } 19574 } 19575 19576 if (restoreconNeeded) { 19577 try { 19578 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19579 app.seinfo); 19580 } catch (InstallerException e) { 19581 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19582 } 19583 } 19584 19585 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19586 try { 19587 // CE storage is unlocked right now, so read out the inode and 19588 // remember for use later when it's locked 19589 // TODO: mark this structure as dirty so we persist it! 19590 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19591 StorageManager.FLAG_STORAGE_CE); 19592 synchronized (mPackages) { 19593 final PackageSetting ps = mSettings.mPackages.get(packageName); 19594 if (ps != null) { 19595 ps.setCeDataInode(ceDataInode, userId); 19596 } 19597 } 19598 } catch (InstallerException e) { 19599 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19600 } 19601 } 19602 19603 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19604 } 19605 19606 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19607 if (pkg == null) { 19608 Slog.wtf(TAG, "Package was null!", new Throwable()); 19609 return; 19610 } 19611 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19612 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19613 for (int i = 0; i < childCount; i++) { 19614 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19615 } 19616 } 19617 19618 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19619 final String volumeUuid = pkg.volumeUuid; 19620 final String packageName = pkg.packageName; 19621 final ApplicationInfo app = pkg.applicationInfo; 19622 19623 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19624 // Create a native library symlink only if we have native libraries 19625 // and if the native libraries are 32 bit libraries. We do not provide 19626 // this symlink for 64 bit libraries. 19627 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19628 final String nativeLibPath = app.nativeLibraryDir; 19629 try { 19630 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19631 nativeLibPath, userId); 19632 } catch (InstallerException e) { 19633 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19634 } 19635 } 19636 } 19637 } 19638 19639 /** 19640 * For system apps on non-FBE devices, this method migrates any existing 19641 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19642 * requested by the app. 19643 */ 19644 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19645 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19646 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19647 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19648 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19649 try { 19650 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19651 storageTarget); 19652 } catch (InstallerException e) { 19653 logCriticalInfo(Log.WARN, 19654 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19655 } 19656 return true; 19657 } else { 19658 return false; 19659 } 19660 } 19661 19662 public PackageFreezer freezePackage(String packageName, String killReason) { 19663 return new PackageFreezer(packageName, killReason); 19664 } 19665 19666 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19667 String killReason) { 19668 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19669 return new PackageFreezer(); 19670 } else { 19671 return freezePackage(packageName, killReason); 19672 } 19673 } 19674 19675 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19676 String killReason) { 19677 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19678 return new PackageFreezer(); 19679 } else { 19680 return freezePackage(packageName, killReason); 19681 } 19682 } 19683 19684 /** 19685 * Class that freezes and kills the given package upon creation, and 19686 * unfreezes it upon closing. This is typically used when doing surgery on 19687 * app code/data to prevent the app from running while you're working. 19688 */ 19689 private class PackageFreezer implements AutoCloseable { 19690 private final String mPackageName; 19691 private final PackageFreezer[] mChildren; 19692 19693 private final boolean mWeFroze; 19694 19695 private final AtomicBoolean mClosed = new AtomicBoolean(); 19696 private final CloseGuard mCloseGuard = CloseGuard.get(); 19697 19698 /** 19699 * Create and return a stub freezer that doesn't actually do anything, 19700 * typically used when someone requested 19701 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19702 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19703 */ 19704 public PackageFreezer() { 19705 mPackageName = null; 19706 mChildren = null; 19707 mWeFroze = false; 19708 mCloseGuard.open("close"); 19709 } 19710 19711 public PackageFreezer(String packageName, String killReason) { 19712 synchronized (mPackages) { 19713 mPackageName = packageName; 19714 mWeFroze = mFrozenPackages.add(mPackageName); 19715 19716 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19717 if (ps != null) { 19718 killApplication(ps.name, ps.appId, killReason); 19719 } 19720 19721 final PackageParser.Package p = mPackages.get(packageName); 19722 if (p != null && p.childPackages != null) { 19723 final int N = p.childPackages.size(); 19724 mChildren = new PackageFreezer[N]; 19725 for (int i = 0; i < N; i++) { 19726 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19727 killReason); 19728 } 19729 } else { 19730 mChildren = null; 19731 } 19732 } 19733 mCloseGuard.open("close"); 19734 } 19735 19736 @Override 19737 protected void finalize() throws Throwable { 19738 try { 19739 mCloseGuard.warnIfOpen(); 19740 close(); 19741 } finally { 19742 super.finalize(); 19743 } 19744 } 19745 19746 @Override 19747 public void close() { 19748 mCloseGuard.close(); 19749 if (mClosed.compareAndSet(false, true)) { 19750 synchronized (mPackages) { 19751 if (mWeFroze) { 19752 mFrozenPackages.remove(mPackageName); 19753 } 19754 19755 if (mChildren != null) { 19756 for (PackageFreezer freezer : mChildren) { 19757 freezer.close(); 19758 } 19759 } 19760 } 19761 } 19762 } 19763 } 19764 19765 /** 19766 * Verify that given package is currently frozen. 19767 */ 19768 private void checkPackageFrozen(String packageName) { 19769 synchronized (mPackages) { 19770 if (!mFrozenPackages.contains(packageName)) { 19771 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19772 } 19773 } 19774 } 19775 19776 @Override 19777 public int movePackage(final String packageName, final String volumeUuid) { 19778 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19779 19780 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19781 final int moveId = mNextMoveId.getAndIncrement(); 19782 mHandler.post(new Runnable() { 19783 @Override 19784 public void run() { 19785 try { 19786 movePackageInternal(packageName, volumeUuid, moveId, user); 19787 } catch (PackageManagerException e) { 19788 Slog.w(TAG, "Failed to move " + packageName, e); 19789 mMoveCallbacks.notifyStatusChanged(moveId, 19790 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19791 } 19792 } 19793 }); 19794 return moveId; 19795 } 19796 19797 private void movePackageInternal(final String packageName, final String volumeUuid, 19798 final int moveId, UserHandle user) throws PackageManagerException { 19799 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19800 final PackageManager pm = mContext.getPackageManager(); 19801 19802 final boolean currentAsec; 19803 final String currentVolumeUuid; 19804 final File codeFile; 19805 final String installerPackageName; 19806 final String packageAbiOverride; 19807 final int appId; 19808 final String seinfo; 19809 final String label; 19810 final int targetSdkVersion; 19811 final PackageFreezer freezer; 19812 final int[] installedUserIds; 19813 19814 // reader 19815 synchronized (mPackages) { 19816 final PackageParser.Package pkg = mPackages.get(packageName); 19817 final PackageSetting ps = mSettings.mPackages.get(packageName); 19818 if (pkg == null || ps == null) { 19819 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19820 } 19821 19822 if (pkg.applicationInfo.isSystemApp()) { 19823 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19824 "Cannot move system application"); 19825 } 19826 19827 if (pkg.applicationInfo.isExternalAsec()) { 19828 currentAsec = true; 19829 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19830 } else if (pkg.applicationInfo.isForwardLocked()) { 19831 currentAsec = true; 19832 currentVolumeUuid = "forward_locked"; 19833 } else { 19834 currentAsec = false; 19835 currentVolumeUuid = ps.volumeUuid; 19836 19837 final File probe = new File(pkg.codePath); 19838 final File probeOat = new File(probe, "oat"); 19839 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19840 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19841 "Move only supported for modern cluster style installs"); 19842 } 19843 } 19844 19845 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19846 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19847 "Package already moved to " + volumeUuid); 19848 } 19849 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19850 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19851 "Device admin cannot be moved"); 19852 } 19853 19854 if (mFrozenPackages.contains(packageName)) { 19855 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19856 "Failed to move already frozen package"); 19857 } 19858 19859 codeFile = new File(pkg.codePath); 19860 installerPackageName = ps.installerPackageName; 19861 packageAbiOverride = ps.cpuAbiOverrideString; 19862 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19863 seinfo = pkg.applicationInfo.seinfo; 19864 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19865 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19866 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19867 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19868 } 19869 19870 final Bundle extras = new Bundle(); 19871 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19872 extras.putString(Intent.EXTRA_TITLE, label); 19873 mMoveCallbacks.notifyCreated(moveId, extras); 19874 19875 int installFlags; 19876 final boolean moveCompleteApp; 19877 final File measurePath; 19878 19879 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19880 installFlags = INSTALL_INTERNAL; 19881 moveCompleteApp = !currentAsec; 19882 measurePath = Environment.getDataAppDirectory(volumeUuid); 19883 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19884 installFlags = INSTALL_EXTERNAL; 19885 moveCompleteApp = false; 19886 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19887 } else { 19888 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19889 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19890 || !volume.isMountedWritable()) { 19891 freezer.close(); 19892 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19893 "Move location not mounted private volume"); 19894 } 19895 19896 Preconditions.checkState(!currentAsec); 19897 19898 installFlags = INSTALL_INTERNAL; 19899 moveCompleteApp = true; 19900 measurePath = Environment.getDataAppDirectory(volumeUuid); 19901 } 19902 19903 final PackageStats stats = new PackageStats(null, -1); 19904 synchronized (mInstaller) { 19905 for (int userId : installedUserIds) { 19906 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19907 freezer.close(); 19908 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19909 "Failed to measure package size"); 19910 } 19911 } 19912 } 19913 19914 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19915 + stats.dataSize); 19916 19917 final long startFreeBytes = measurePath.getFreeSpace(); 19918 final long sizeBytes; 19919 if (moveCompleteApp) { 19920 sizeBytes = stats.codeSize + stats.dataSize; 19921 } else { 19922 sizeBytes = stats.codeSize; 19923 } 19924 19925 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19926 freezer.close(); 19927 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19928 "Not enough free space to move"); 19929 } 19930 19931 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19932 19933 final CountDownLatch installedLatch = new CountDownLatch(1); 19934 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19935 @Override 19936 public void onUserActionRequired(Intent intent) throws RemoteException { 19937 throw new IllegalStateException(); 19938 } 19939 19940 @Override 19941 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19942 Bundle extras) throws RemoteException { 19943 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19944 + PackageManager.installStatusToString(returnCode, msg)); 19945 19946 installedLatch.countDown(); 19947 freezer.close(); 19948 19949 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19950 switch (status) { 19951 case PackageInstaller.STATUS_SUCCESS: 19952 mMoveCallbacks.notifyStatusChanged(moveId, 19953 PackageManager.MOVE_SUCCEEDED); 19954 break; 19955 case PackageInstaller.STATUS_FAILURE_STORAGE: 19956 mMoveCallbacks.notifyStatusChanged(moveId, 19957 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19958 break; 19959 default: 19960 mMoveCallbacks.notifyStatusChanged(moveId, 19961 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19962 break; 19963 } 19964 } 19965 }; 19966 19967 final MoveInfo move; 19968 if (moveCompleteApp) { 19969 // Kick off a thread to report progress estimates 19970 new Thread() { 19971 @Override 19972 public void run() { 19973 while (true) { 19974 try { 19975 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19976 break; 19977 } 19978 } catch (InterruptedException ignored) { 19979 } 19980 19981 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19982 final int progress = 10 + (int) MathUtils.constrain( 19983 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19984 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19985 } 19986 } 19987 }.start(); 19988 19989 final String dataAppName = codeFile.getName(); 19990 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19991 dataAppName, appId, seinfo, targetSdkVersion); 19992 } else { 19993 move = null; 19994 } 19995 19996 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19997 19998 final Message msg = mHandler.obtainMessage(INIT_COPY); 19999 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20000 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20001 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20002 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20003 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20004 msg.obj = params; 20005 20006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20007 System.identityHashCode(msg.obj)); 20008 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20009 System.identityHashCode(msg.obj)); 20010 20011 mHandler.sendMessage(msg); 20012 } 20013 20014 @Override 20015 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20017 20018 final int realMoveId = mNextMoveId.getAndIncrement(); 20019 final Bundle extras = new Bundle(); 20020 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20021 mMoveCallbacks.notifyCreated(realMoveId, extras); 20022 20023 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20024 @Override 20025 public void onCreated(int moveId, Bundle extras) { 20026 // Ignored 20027 } 20028 20029 @Override 20030 public void onStatusChanged(int moveId, int status, long estMillis) { 20031 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20032 } 20033 }; 20034 20035 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20036 storage.setPrimaryStorageUuid(volumeUuid, callback); 20037 return realMoveId; 20038 } 20039 20040 @Override 20041 public int getMoveStatus(int moveId) { 20042 mContext.enforceCallingOrSelfPermission( 20043 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20044 return mMoveCallbacks.mLastStatus.get(moveId); 20045 } 20046 20047 @Override 20048 public void registerMoveCallback(IPackageMoveObserver callback) { 20049 mContext.enforceCallingOrSelfPermission( 20050 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20051 mMoveCallbacks.register(callback); 20052 } 20053 20054 @Override 20055 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20056 mContext.enforceCallingOrSelfPermission( 20057 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20058 mMoveCallbacks.unregister(callback); 20059 } 20060 20061 @Override 20062 public boolean setInstallLocation(int loc) { 20063 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20064 null); 20065 if (getInstallLocation() == loc) { 20066 return true; 20067 } 20068 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20069 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20070 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20071 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20072 return true; 20073 } 20074 return false; 20075 } 20076 20077 @Override 20078 public int getInstallLocation() { 20079 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20080 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20081 PackageHelper.APP_INSTALL_AUTO); 20082 } 20083 20084 /** Called by UserManagerService */ 20085 void cleanUpUser(UserManagerService userManager, int userHandle) { 20086 synchronized (mPackages) { 20087 mDirtyUsers.remove(userHandle); 20088 mUserNeedsBadging.delete(userHandle); 20089 mSettings.removeUserLPw(userHandle); 20090 mPendingBroadcasts.remove(userHandle); 20091 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20092 removeUnusedPackagesLPw(userManager, userHandle); 20093 } 20094 } 20095 20096 /** 20097 * We're removing userHandle and would like to remove any downloaded packages 20098 * that are no longer in use by any other user. 20099 * @param userHandle the user being removed 20100 */ 20101 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20102 final boolean DEBUG_CLEAN_APKS = false; 20103 int [] users = userManager.getUserIds(); 20104 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20105 while (psit.hasNext()) { 20106 PackageSetting ps = psit.next(); 20107 if (ps.pkg == null) { 20108 continue; 20109 } 20110 final String packageName = ps.pkg.packageName; 20111 // Skip over if system app 20112 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20113 continue; 20114 } 20115 if (DEBUG_CLEAN_APKS) { 20116 Slog.i(TAG, "Checking package " + packageName); 20117 } 20118 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20119 if (keep) { 20120 if (DEBUG_CLEAN_APKS) { 20121 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20122 } 20123 } else { 20124 for (int i = 0; i < users.length; i++) { 20125 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20126 keep = true; 20127 if (DEBUG_CLEAN_APKS) { 20128 Slog.i(TAG, " Keeping package " + packageName + " for user " 20129 + users[i]); 20130 } 20131 break; 20132 } 20133 } 20134 } 20135 if (!keep) { 20136 if (DEBUG_CLEAN_APKS) { 20137 Slog.i(TAG, " Removing package " + packageName); 20138 } 20139 mHandler.post(new Runnable() { 20140 public void run() { 20141 deletePackageX(packageName, userHandle, 0); 20142 } //end run 20143 }); 20144 } 20145 } 20146 } 20147 20148 /** Called by UserManagerService */ 20149 void createNewUser(int userId) { 20150 synchronized (mInstallLock) { 20151 mSettings.createNewUserLI(this, mInstaller, userId); 20152 } 20153 synchronized (mPackages) { 20154 scheduleWritePackageRestrictionsLocked(userId); 20155 scheduleWritePackageListLocked(userId); 20156 applyFactoryDefaultBrowserLPw(userId); 20157 primeDomainVerificationsLPw(userId); 20158 } 20159 } 20160 20161 void onBeforeUserStartUninitialized(final int userId) { 20162 synchronized (mPackages) { 20163 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20164 return; 20165 } 20166 } 20167 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20168 // If permission review for legacy apps is required, we represent 20169 // dagerous permissions for such apps as always granted runtime 20170 // permissions to keep per user flag state whether review is needed. 20171 // Hence, if a new user is added we have to propagate dangerous 20172 // permission grants for these legacy apps. 20173 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20174 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20175 | UPDATE_PERMISSIONS_REPLACE_ALL); 20176 } 20177 } 20178 20179 @Override 20180 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20181 mContext.enforceCallingOrSelfPermission( 20182 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20183 "Only package verification agents can read the verifier device identity"); 20184 20185 synchronized (mPackages) { 20186 return mSettings.getVerifierDeviceIdentityLPw(); 20187 } 20188 } 20189 20190 @Override 20191 public void setPermissionEnforced(String permission, boolean enforced) { 20192 // TODO: Now that we no longer change GID for storage, this should to away. 20193 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20194 "setPermissionEnforced"); 20195 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20196 synchronized (mPackages) { 20197 if (mSettings.mReadExternalStorageEnforced == null 20198 || mSettings.mReadExternalStorageEnforced != enforced) { 20199 mSettings.mReadExternalStorageEnforced = enforced; 20200 mSettings.writeLPr(); 20201 } 20202 } 20203 // kill any non-foreground processes so we restart them and 20204 // grant/revoke the GID. 20205 final IActivityManager am = ActivityManagerNative.getDefault(); 20206 if (am != null) { 20207 final long token = Binder.clearCallingIdentity(); 20208 try { 20209 am.killProcessesBelowForeground("setPermissionEnforcement"); 20210 } catch (RemoteException e) { 20211 } finally { 20212 Binder.restoreCallingIdentity(token); 20213 } 20214 } 20215 } else { 20216 throw new IllegalArgumentException("No selective enforcement for " + permission); 20217 } 20218 } 20219 20220 @Override 20221 @Deprecated 20222 public boolean isPermissionEnforced(String permission) { 20223 return true; 20224 } 20225 20226 @Override 20227 public boolean isStorageLow() { 20228 final long token = Binder.clearCallingIdentity(); 20229 try { 20230 final DeviceStorageMonitorInternal 20231 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20232 if (dsm != null) { 20233 return dsm.isMemoryLow(); 20234 } else { 20235 return false; 20236 } 20237 } finally { 20238 Binder.restoreCallingIdentity(token); 20239 } 20240 } 20241 20242 @Override 20243 public IPackageInstaller getPackageInstaller() { 20244 return mInstallerService; 20245 } 20246 20247 private boolean userNeedsBadging(int userId) { 20248 int index = mUserNeedsBadging.indexOfKey(userId); 20249 if (index < 0) { 20250 final UserInfo userInfo; 20251 final long token = Binder.clearCallingIdentity(); 20252 try { 20253 userInfo = sUserManager.getUserInfo(userId); 20254 } finally { 20255 Binder.restoreCallingIdentity(token); 20256 } 20257 final boolean b; 20258 if (userInfo != null && userInfo.isManagedProfile()) { 20259 b = true; 20260 } else { 20261 b = false; 20262 } 20263 mUserNeedsBadging.put(userId, b); 20264 return b; 20265 } 20266 return mUserNeedsBadging.valueAt(index); 20267 } 20268 20269 @Override 20270 public KeySet getKeySetByAlias(String packageName, String alias) { 20271 if (packageName == null || alias == null) { 20272 return null; 20273 } 20274 synchronized(mPackages) { 20275 final PackageParser.Package pkg = mPackages.get(packageName); 20276 if (pkg == null) { 20277 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20278 throw new IllegalArgumentException("Unknown package: " + packageName); 20279 } 20280 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20281 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20282 } 20283 } 20284 20285 @Override 20286 public KeySet getSigningKeySet(String packageName) { 20287 if (packageName == null) { 20288 return null; 20289 } 20290 synchronized(mPackages) { 20291 final PackageParser.Package pkg = mPackages.get(packageName); 20292 if (pkg == null) { 20293 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20294 throw new IllegalArgumentException("Unknown package: " + packageName); 20295 } 20296 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20297 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20298 throw new SecurityException("May not access signing KeySet of other apps."); 20299 } 20300 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20301 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20302 } 20303 } 20304 20305 @Override 20306 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20307 if (packageName == null || ks == null) { 20308 return false; 20309 } 20310 synchronized(mPackages) { 20311 final PackageParser.Package pkg = mPackages.get(packageName); 20312 if (pkg == null) { 20313 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20314 throw new IllegalArgumentException("Unknown package: " + packageName); 20315 } 20316 IBinder ksh = ks.getToken(); 20317 if (ksh instanceof KeySetHandle) { 20318 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20319 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20320 } 20321 return false; 20322 } 20323 } 20324 20325 @Override 20326 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20327 if (packageName == null || ks == null) { 20328 return false; 20329 } 20330 synchronized(mPackages) { 20331 final PackageParser.Package pkg = mPackages.get(packageName); 20332 if (pkg == null) { 20333 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20334 throw new IllegalArgumentException("Unknown package: " + packageName); 20335 } 20336 IBinder ksh = ks.getToken(); 20337 if (ksh instanceof KeySetHandle) { 20338 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20339 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20340 } 20341 return false; 20342 } 20343 } 20344 20345 private void deletePackageIfUnusedLPr(final String packageName) { 20346 PackageSetting ps = mSettings.mPackages.get(packageName); 20347 if (ps == null) { 20348 return; 20349 } 20350 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20351 // TODO Implement atomic delete if package is unused 20352 // It is currently possible that the package will be deleted even if it is installed 20353 // after this method returns. 20354 mHandler.post(new Runnable() { 20355 public void run() { 20356 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20357 } 20358 }); 20359 } 20360 } 20361 20362 /** 20363 * Check and throw if the given before/after packages would be considered a 20364 * downgrade. 20365 */ 20366 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20367 throws PackageManagerException { 20368 if (after.versionCode < before.mVersionCode) { 20369 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20370 "Update version code " + after.versionCode + " is older than current " 20371 + before.mVersionCode); 20372 } else if (after.versionCode == before.mVersionCode) { 20373 if (after.baseRevisionCode < before.baseRevisionCode) { 20374 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20375 "Update base revision code " + after.baseRevisionCode 20376 + " is older than current " + before.baseRevisionCode); 20377 } 20378 20379 if (!ArrayUtils.isEmpty(after.splitNames)) { 20380 for (int i = 0; i < after.splitNames.length; i++) { 20381 final String splitName = after.splitNames[i]; 20382 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20383 if (j != -1) { 20384 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20385 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20386 "Update split " + splitName + " revision code " 20387 + after.splitRevisionCodes[i] + " is older than current " 20388 + before.splitRevisionCodes[j]); 20389 } 20390 } 20391 } 20392 } 20393 } 20394 } 20395 20396 private static class MoveCallbacks extends Handler { 20397 private static final int MSG_CREATED = 1; 20398 private static final int MSG_STATUS_CHANGED = 2; 20399 20400 private final RemoteCallbackList<IPackageMoveObserver> 20401 mCallbacks = new RemoteCallbackList<>(); 20402 20403 private final SparseIntArray mLastStatus = new SparseIntArray(); 20404 20405 public MoveCallbacks(Looper looper) { 20406 super(looper); 20407 } 20408 20409 public void register(IPackageMoveObserver callback) { 20410 mCallbacks.register(callback); 20411 } 20412 20413 public void unregister(IPackageMoveObserver callback) { 20414 mCallbacks.unregister(callback); 20415 } 20416 20417 @Override 20418 public void handleMessage(Message msg) { 20419 final SomeArgs args = (SomeArgs) msg.obj; 20420 final int n = mCallbacks.beginBroadcast(); 20421 for (int i = 0; i < n; i++) { 20422 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20423 try { 20424 invokeCallback(callback, msg.what, args); 20425 } catch (RemoteException ignored) { 20426 } 20427 } 20428 mCallbacks.finishBroadcast(); 20429 args.recycle(); 20430 } 20431 20432 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20433 throws RemoteException { 20434 switch (what) { 20435 case MSG_CREATED: { 20436 callback.onCreated(args.argi1, (Bundle) args.arg2); 20437 break; 20438 } 20439 case MSG_STATUS_CHANGED: { 20440 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20441 break; 20442 } 20443 } 20444 } 20445 20446 private void notifyCreated(int moveId, Bundle extras) { 20447 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20448 20449 final SomeArgs args = SomeArgs.obtain(); 20450 args.argi1 = moveId; 20451 args.arg2 = extras; 20452 obtainMessage(MSG_CREATED, args).sendToTarget(); 20453 } 20454 20455 private void notifyStatusChanged(int moveId, int status) { 20456 notifyStatusChanged(moveId, status, -1); 20457 } 20458 20459 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20460 Slog.v(TAG, "Move " + moveId + " status " + status); 20461 20462 final SomeArgs args = SomeArgs.obtain(); 20463 args.argi1 = moveId; 20464 args.argi2 = status; 20465 args.arg3 = estMillis; 20466 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20467 20468 synchronized (mLastStatus) { 20469 mLastStatus.put(moveId, status); 20470 } 20471 } 20472 } 20473 20474 private final static class OnPermissionChangeListeners extends Handler { 20475 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20476 20477 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20478 new RemoteCallbackList<>(); 20479 20480 public OnPermissionChangeListeners(Looper looper) { 20481 super(looper); 20482 } 20483 20484 @Override 20485 public void handleMessage(Message msg) { 20486 switch (msg.what) { 20487 case MSG_ON_PERMISSIONS_CHANGED: { 20488 final int uid = msg.arg1; 20489 handleOnPermissionsChanged(uid); 20490 } break; 20491 } 20492 } 20493 20494 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20495 mPermissionListeners.register(listener); 20496 20497 } 20498 20499 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20500 mPermissionListeners.unregister(listener); 20501 } 20502 20503 public void onPermissionsChanged(int uid) { 20504 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20505 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20506 } 20507 } 20508 20509 private void handleOnPermissionsChanged(int uid) { 20510 final int count = mPermissionListeners.beginBroadcast(); 20511 try { 20512 for (int i = 0; i < count; i++) { 20513 IOnPermissionsChangeListener callback = mPermissionListeners 20514 .getBroadcastItem(i); 20515 try { 20516 callback.onPermissionsChanged(uid); 20517 } catch (RemoteException e) { 20518 Log.e(TAG, "Permission listener is dead", e); 20519 } 20520 } 20521 } finally { 20522 mPermissionListeners.finishBroadcast(); 20523 } 20524 } 20525 } 20526 20527 private class PackageManagerInternalImpl extends PackageManagerInternal { 20528 @Override 20529 public void setLocationPackagesProvider(PackagesProvider provider) { 20530 synchronized (mPackages) { 20531 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20532 } 20533 } 20534 20535 @Override 20536 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20537 synchronized (mPackages) { 20538 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20539 } 20540 } 20541 20542 @Override 20543 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20544 synchronized (mPackages) { 20545 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20546 } 20547 } 20548 20549 @Override 20550 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20551 synchronized (mPackages) { 20552 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20553 } 20554 } 20555 20556 @Override 20557 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20558 synchronized (mPackages) { 20559 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20560 } 20561 } 20562 20563 @Override 20564 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20565 synchronized (mPackages) { 20566 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20567 } 20568 } 20569 20570 @Override 20571 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20572 synchronized (mPackages) { 20573 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20574 packageName, userId); 20575 } 20576 } 20577 20578 @Override 20579 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20580 synchronized (mPackages) { 20581 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20582 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20583 packageName, userId); 20584 } 20585 } 20586 20587 @Override 20588 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20589 synchronized (mPackages) { 20590 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20591 packageName, userId); 20592 } 20593 } 20594 20595 @Override 20596 public void setKeepUninstalledPackages(final List<String> packageList) { 20597 Preconditions.checkNotNull(packageList); 20598 List<String> removedFromList = null; 20599 synchronized (mPackages) { 20600 if (mKeepUninstalledPackages != null) { 20601 final int packagesCount = mKeepUninstalledPackages.size(); 20602 for (int i = 0; i < packagesCount; i++) { 20603 String oldPackage = mKeepUninstalledPackages.get(i); 20604 if (packageList != null && packageList.contains(oldPackage)) { 20605 continue; 20606 } 20607 if (removedFromList == null) { 20608 removedFromList = new ArrayList<>(); 20609 } 20610 removedFromList.add(oldPackage); 20611 } 20612 } 20613 mKeepUninstalledPackages = new ArrayList<>(packageList); 20614 if (removedFromList != null) { 20615 final int removedCount = removedFromList.size(); 20616 for (int i = 0; i < removedCount; i++) { 20617 deletePackageIfUnusedLPr(removedFromList.get(i)); 20618 } 20619 } 20620 } 20621 } 20622 20623 @Override 20624 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20625 synchronized (mPackages) { 20626 // If we do not support permission review, done. 20627 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20628 return false; 20629 } 20630 20631 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20632 if (packageSetting == null) { 20633 return false; 20634 } 20635 20636 // Permission review applies only to apps not supporting the new permission model. 20637 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20638 return false; 20639 } 20640 20641 // Legacy apps have the permission and get user consent on launch. 20642 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20643 return permissionsState.isPermissionReviewRequired(userId); 20644 } 20645 } 20646 20647 @Override 20648 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20649 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20650 } 20651 20652 @Override 20653 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20654 int userId) { 20655 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20656 } 20657 } 20658 20659 @Override 20660 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20661 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20662 synchronized (mPackages) { 20663 final long identity = Binder.clearCallingIdentity(); 20664 try { 20665 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20666 packageNames, userId); 20667 } finally { 20668 Binder.restoreCallingIdentity(identity); 20669 } 20670 } 20671 } 20672 20673 private static void enforceSystemOrPhoneCaller(String tag) { 20674 int callingUid = Binder.getCallingUid(); 20675 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20676 throw new SecurityException( 20677 "Cannot call " + tag + " from UID " + callingUid); 20678 } 20679 } 20680 20681 boolean isHistoricalPackageUsageAvailable() { 20682 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20683 } 20684 20685 /** 20686 * Return a <b>copy</b> of the collection of packages known to the package manager. 20687 * @return A copy of the values of mPackages. 20688 */ 20689 Collection<PackageParser.Package> getPackages() { 20690 synchronized (mPackages) { 20691 return new ArrayList<>(mPackages.values()); 20692 } 20693 } 20694 20695 /** 20696 * Logs process start information (including base APK hash) to the security log. 20697 * @hide 20698 */ 20699 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20700 String apkFile, int pid) { 20701 if (!SecurityLog.isLoggingEnabled()) { 20702 return; 20703 } 20704 Bundle data = new Bundle(); 20705 data.putLong("startTimestamp", System.currentTimeMillis()); 20706 data.putString("processName", processName); 20707 data.putInt("uid", uid); 20708 data.putString("seinfo", seinfo); 20709 data.putString("apkFile", apkFile); 20710 data.putInt("pid", pid); 20711 Message msg = mProcessLoggingHandler.obtainMessage( 20712 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20713 msg.setData(data); 20714 mProcessLoggingHandler.sendMessage(msg); 20715 } 20716} 20717