PackageManagerService.java revision d4041db120d7500e73e0132b03dfeffb84d402f5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.app.usage.UsageStatsManager; 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.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.util.ArrayUtils; 233import com.android.internal.util.FastPrintWriter; 234import com.android.internal.util.FastXmlSerializer; 235import com.android.internal.util.IndentingPrintWriter; 236import com.android.internal.util.Preconditions; 237import com.android.internal.util.XmlUtils; 238import com.android.server.EventLogTags; 239import com.android.server.FgThread; 240import com.android.server.IntentResolver; 241import com.android.server.LocalServices; 242import com.android.server.ServiceThread; 243import com.android.server.SystemConfig; 244import com.android.server.Watchdog; 245import com.android.server.pm.PermissionsState.PermissionState; 246import com.android.server.pm.Settings.DatabaseVersion; 247import com.android.server.pm.Settings.VersionInfo; 248import com.android.server.storage.DeviceStorageMonitorInternal; 249 250import dalvik.system.CloseGuard; 251import dalvik.system.DexFile; 252import dalvik.system.VMRuntime; 253 254import libcore.io.IoUtils; 255import libcore.util.EmptyArray; 256 257import org.xmlpull.v1.XmlPullParser; 258import org.xmlpull.v1.XmlPullParserException; 259import org.xmlpull.v1.XmlSerializer; 260 261import java.io.BufferedInputStream; 262import java.io.BufferedOutputStream; 263import java.io.BufferedReader; 264import java.io.ByteArrayInputStream; 265import java.io.ByteArrayOutputStream; 266import java.io.File; 267import java.io.FileDescriptor; 268import java.io.FileNotFoundException; 269import java.io.FileOutputStream; 270import java.io.FileReader; 271import java.io.FilenameFilter; 272import java.io.IOException; 273import java.io.InputStream; 274import java.io.PrintWriter; 275import java.nio.charset.StandardCharsets; 276import java.security.MessageDigest; 277import java.security.NoSuchAlgorithmException; 278import java.security.PublicKey; 279import java.security.cert.Certificate; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those APKs everywhere. 303 * <p> 304 * Internally there are two important locks: 305 * <ul> 306 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 307 * and other related state. It is a fine-grained lock that should only be held 308 * momentarily, as it's one of the most contended locks in the system. 309 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 310 * operations typically involve heavy lifting of application data on disk. Since 311 * {@code installd} is single-threaded, and it's operations can often be slow, 312 * this lock should never be acquired while already holding {@link #mPackages}. 313 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 314 * holding {@link #mInstallLock}. 315 * </ul> 316 * Many internal methods rely on the caller to hold the appropriate locks, and 317 * this contract is expressed through method name suffixes: 318 * <ul> 319 * <li>fooLI(): the caller must hold {@link #mInstallLock} 320 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 321 * being modified must be frozen 322 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 323 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 324 * </ul> 325 * <p> 326 * Because this class is very central to the platform's security; please run all 327 * CTS and unit tests whenever making modifications: 328 * 329 * <pre> 330 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 331 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 332 * </pre> 333 */ 334public class PackageManagerService extends IPackageManager.Stub { 335 static final String TAG = "PackageManager"; 336 static final boolean DEBUG_SETTINGS = false; 337 static final boolean DEBUG_PREFERRED = false; 338 static final boolean DEBUG_UPGRADE = false; 339 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 340 private static final boolean DEBUG_BACKUP = false; 341 private static final boolean DEBUG_INSTALL = false; 342 private static final boolean DEBUG_REMOVE = false; 343 private static final boolean DEBUG_BROADCASTS = false; 344 private static final boolean DEBUG_SHOW_INFO = false; 345 private static final boolean DEBUG_PACKAGE_INFO = false; 346 private static final boolean DEBUG_INTENT_MATCHING = false; 347 private static final boolean DEBUG_PACKAGE_SCANNING = false; 348 private static final boolean DEBUG_VERIFY = false; 349 private static final boolean DEBUG_FILTERS = false; 350 351 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 352 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 353 // user, but by default initialize to this. 354 static final boolean DEBUG_DEXOPT = false; 355 356 private static final boolean DEBUG_ABI_SELECTION = false; 357 private static final boolean DEBUG_EPHEMERAL = false; 358 private static final boolean DEBUG_TRIAGED_MISSING = false; 359 private static final boolean DEBUG_APP_DATA = false; 360 361 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 362 363 private static final boolean DISABLE_EPHEMERAL_APPS = true; 364 365 private static final int RADIO_UID = Process.PHONE_UID; 366 private static final int LOG_UID = Process.LOG_UID; 367 private static final int NFC_UID = Process.NFC_UID; 368 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 369 private static final int SHELL_UID = Process.SHELL_UID; 370 371 // Cap the size of permission trees that 3rd party apps can define 372 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 373 374 // Suffix used during package installation when copying/moving 375 // package apks to install directory. 376 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 377 378 static final int SCAN_NO_DEX = 1<<1; 379 static final int SCAN_FORCE_DEX = 1<<2; 380 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 381 static final int SCAN_NEW_INSTALL = 1<<4; 382 static final int SCAN_NO_PATHS = 1<<5; 383 static final int SCAN_UPDATE_TIME = 1<<6; 384 static final int SCAN_DEFER_DEX = 1<<7; 385 static final int SCAN_BOOTING = 1<<8; 386 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 387 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 388 static final int SCAN_REPLACING = 1<<11; 389 static final int SCAN_REQUIRE_KNOWN = 1<<12; 390 static final int SCAN_MOVE = 1<<13; 391 static final int SCAN_INITIAL = 1<<14; 392 static final int SCAN_CHECK_ONLY = 1<<15; 393 static final int SCAN_DONT_KILL_APP = 1<<17; 394 static final int SCAN_IGNORE_FROZEN = 1<<18; 395 396 static final int REMOVE_CHATTY = 1<<16; 397 398 private static final int[] EMPTY_INT_ARRAY = new int[0]; 399 400 /** 401 * Timeout (in milliseconds) after which the watchdog should declare that 402 * our handler thread is wedged. The usual default for such things is one 403 * minute but we sometimes do very lengthy I/O operations on this thread, 404 * such as installing multi-gigabyte applications, so ours needs to be longer. 405 */ 406 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 407 408 /** 409 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 410 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 411 * settings entry if available, otherwise we use the hardcoded default. If it's been 412 * more than this long since the last fstrim, we force one during the boot sequence. 413 * 414 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 415 * one gets run at the next available charging+idle time. This final mandatory 416 * no-fstrim check kicks in only of the other scheduling criteria is never met. 417 */ 418 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 419 420 /** 421 * Whether verification is enabled by default. 422 */ 423 private static final boolean DEFAULT_VERIFY_ENABLE = true; 424 425 /** 426 * The default maximum time to wait for the verification agent to return in 427 * milliseconds. 428 */ 429 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 430 431 /** 432 * The default response for package verification timeout. 433 * 434 * This can be either PackageManager.VERIFICATION_ALLOW or 435 * PackageManager.VERIFICATION_REJECT. 436 */ 437 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 438 439 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 440 441 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 442 DEFAULT_CONTAINER_PACKAGE, 443 "com.android.defcontainer.DefaultContainerService"); 444 445 private static final String KILL_APP_REASON_GIDS_CHANGED = 446 "permission grant or revoke changed gids"; 447 448 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 449 "permissions revoked"; 450 451 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 452 453 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 454 455 /** Permission grant: not grant the permission. */ 456 private static final int GRANT_DENIED = 1; 457 458 /** Permission grant: grant the permission as an install permission. */ 459 private static final int GRANT_INSTALL = 2; 460 461 /** Permission grant: grant the permission as a runtime one. */ 462 private static final int GRANT_RUNTIME = 3; 463 464 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 465 private static final int GRANT_UPGRADE = 4; 466 467 /** Canonical intent used to identify what counts as a "web browser" app */ 468 private static final Intent sBrowserIntent; 469 static { 470 sBrowserIntent = new Intent(); 471 sBrowserIntent.setAction(Intent.ACTION_VIEW); 472 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 473 sBrowserIntent.setData(Uri.parse("http:")); 474 } 475 476 /** 477 * The set of all protected actions [i.e. those actions for which a high priority 478 * intent filter is disallowed]. 479 */ 480 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 481 static { 482 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 483 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 485 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 486 } 487 488 // Compilation reasons. 489 public static final int REASON_FIRST_BOOT = 0; 490 public static final int REASON_BOOT = 1; 491 public static final int REASON_INSTALL = 2; 492 public static final int REASON_BACKGROUND_DEXOPT = 3; 493 public static final int REASON_AB_OTA = 4; 494 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 495 public static final int REASON_SHARED_APK = 6; 496 public static final int REASON_FORCED_DEXOPT = 7; 497 498 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 499 500 final ServiceThread mHandlerThread; 501 502 final PackageHandler mHandler; 503 504 private final ProcessLoggingHandler mProcessLoggingHandler; 505 506 /** 507 * Messages for {@link #mHandler} that need to wait for system ready before 508 * being dispatched. 509 */ 510 private ArrayList<Message> mPostSystemReadyMessages; 511 512 final int mSdkVersion = Build.VERSION.SDK_INT; 513 514 final Context mContext; 515 final boolean mFactoryTest; 516 final boolean mOnlyCore; 517 final DisplayMetrics mMetrics; 518 final int mDefParseFlags; 519 final String[] mSeparateProcesses; 520 final boolean mIsUpgrade; 521 final boolean mIsPreNUpgrade; 522 523 /** The location for ASEC container files on internal storage. */ 524 final String mAsecInternalPath; 525 526 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 527 // LOCK HELD. Can be called with mInstallLock held. 528 @GuardedBy("mInstallLock") 529 final Installer mInstaller; 530 531 /** Directory where installed third-party apps stored */ 532 final File mAppInstallDir; 533 final File mEphemeralInstallDir; 534 535 /** 536 * Directory to which applications installed internally have their 537 * 32 bit native libraries copied. 538 */ 539 private File mAppLib32InstallDir; 540 541 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 542 // apps. 543 final File mDrmAppPrivateInstallDir; 544 545 // ---------------------------------------------------------------- 546 547 // Lock for state used when installing and doing other long running 548 // operations. Methods that must be called with this lock held have 549 // the suffix "LI". 550 final Object mInstallLock = new Object(); 551 552 // ---------------------------------------------------------------- 553 554 // Keys are String (package name), values are Package. This also serves 555 // as the lock for the global state. Methods that must be called with 556 // this lock held have the prefix "LP". 557 @GuardedBy("mPackages") 558 final ArrayMap<String, PackageParser.Package> mPackages = 559 new ArrayMap<String, PackageParser.Package>(); 560 561 final ArrayMap<String, Set<String>> mKnownCodebase = 562 new ArrayMap<String, Set<String>>(); 563 564 // Tracks available target package names -> overlay package paths. 565 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 566 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 567 568 /** 569 * Tracks new system packages [received in an OTA] that we expect to 570 * find updated user-installed versions. Keys are package name, values 571 * are package location. 572 */ 573 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 574 /** 575 * Tracks high priority intent filters for protected actions. During boot, certain 576 * filter actions are protected and should never be allowed to have a high priority 577 * intent filter for them. However, there is one, and only one exception -- the 578 * setup wizard. It must be able to define a high priority intent filter for these 579 * actions to ensure there are no escapes from the wizard. We need to delay processing 580 * of these during boot as we need to look at all of the system packages in order 581 * to know which component is the setup wizard. 582 */ 583 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 584 /** 585 * Whether or not processing protected filters should be deferred. 586 */ 587 private boolean mDeferProtectedFilters = true; 588 589 /** 590 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 591 */ 592 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 593 /** 594 * Whether or not system app permissions should be promoted from install to runtime. 595 */ 596 boolean mPromoteSystemApps; 597 598 @GuardedBy("mPackages") 599 final Settings mSettings; 600 601 /** 602 * Set of package names that are currently "frozen", which means active 603 * surgery is being done on the code/data for that package. The platform 604 * will refuse to launch frozen packages to avoid race conditions. 605 * 606 * @see PackageFreezer 607 */ 608 @GuardedBy("mPackages") 609 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 610 611 boolean mRestoredSettings; 612 613 // System configuration read by SystemConfig. 614 final int[] mGlobalGids; 615 final SparseArray<ArraySet<String>> mSystemPermissions; 616 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 617 618 // If mac_permissions.xml was found for seinfo labeling. 619 boolean mFoundPolicyFile; 620 621 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 622 623 public static final class SharedLibraryEntry { 624 public final String path; 625 public final String apk; 626 627 SharedLibraryEntry(String _path, String _apk) { 628 path = _path; 629 apk = _apk; 630 } 631 } 632 633 // Currently known shared libraries. 634 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 635 new ArrayMap<String, SharedLibraryEntry>(); 636 637 // All available activities, for your resolving pleasure. 638 final ActivityIntentResolver mActivities = 639 new ActivityIntentResolver(); 640 641 // All available receivers, for your resolving pleasure. 642 final ActivityIntentResolver mReceivers = 643 new ActivityIntentResolver(); 644 645 // All available services, for your resolving pleasure. 646 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 647 648 // All available providers, for your resolving pleasure. 649 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 650 651 // Mapping from provider base names (first directory in content URI codePath) 652 // to the provider information. 653 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 654 new ArrayMap<String, PackageParser.Provider>(); 655 656 // Mapping from instrumentation class names to info about them. 657 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 658 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 659 660 // Mapping from permission names to info about them. 661 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 662 new ArrayMap<String, PackageParser.PermissionGroup>(); 663 664 // Packages whose data we have transfered into another package, thus 665 // should no longer exist. 666 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 667 668 // Broadcast actions that are only available to the system. 669 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 670 671 /** List of packages waiting for verification. */ 672 final SparseArray<PackageVerificationState> mPendingVerification 673 = new SparseArray<PackageVerificationState>(); 674 675 /** Set of packages associated with each app op permission. */ 676 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 677 678 final PackageInstallerService mInstallerService; 679 680 private final PackageDexOptimizer mPackageDexOptimizer; 681 682 private AtomicInteger mNextMoveId = new AtomicInteger(); 683 private final MoveCallbacks mMoveCallbacks; 684 685 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 686 687 // Cache of users who need badging. 688 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 689 690 /** Token for keys in mPendingVerification. */ 691 private int mPendingVerificationToken = 0; 692 693 volatile boolean mSystemReady; 694 volatile boolean mSafeMode; 695 volatile boolean mHasSystemUidErrors; 696 697 ApplicationInfo mAndroidApplication; 698 final ActivityInfo mResolveActivity = new ActivityInfo(); 699 final ResolveInfo mResolveInfo = new ResolveInfo(); 700 ComponentName mResolveComponentName; 701 PackageParser.Package mPlatformPackage; 702 ComponentName mCustomResolverComponentName; 703 704 boolean mResolverReplaced = false; 705 706 private final @Nullable ComponentName mIntentFilterVerifierComponent; 707 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 708 709 private int mIntentFilterVerificationToken = 0; 710 711 /** Component that knows whether or not an ephemeral application exists */ 712 final ComponentName mEphemeralResolverComponent; 713 /** The service connection to the ephemeral resolver */ 714 final EphemeralResolverConnection mEphemeralResolverConnection; 715 716 /** Component used to install ephemeral applications */ 717 final ComponentName mEphemeralInstallerComponent; 718 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 719 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 720 721 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 722 = new SparseArray<IntentFilterVerificationState>(); 723 724 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 725 new DefaultPermissionGrantPolicy(this); 726 727 // List of packages names to keep cached, even if they are uninstalled for all users 728 private List<String> mKeepUninstalledPackages; 729 730 private static class IFVerificationParams { 731 PackageParser.Package pkg; 732 boolean replacing; 733 int userId; 734 int verifierUid; 735 736 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 737 int _userId, int _verifierUid) { 738 pkg = _pkg; 739 replacing = _replacing; 740 userId = _userId; 741 replacing = _replacing; 742 verifierUid = _verifierUid; 743 } 744 } 745 746 private interface IntentFilterVerifier<T extends IntentFilter> { 747 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 748 T filter, String packageName); 749 void startVerifications(int userId); 750 void receiveVerificationResponse(int verificationId); 751 } 752 753 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 754 private Context mContext; 755 private ComponentName mIntentFilterVerifierComponent; 756 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 757 758 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 759 mContext = context; 760 mIntentFilterVerifierComponent = verifierComponent; 761 } 762 763 private String getDefaultScheme() { 764 return IntentFilter.SCHEME_HTTPS; 765 } 766 767 @Override 768 public void startVerifications(int userId) { 769 // Launch verifications requests 770 int count = mCurrentIntentFilterVerifications.size(); 771 for (int n=0; n<count; n++) { 772 int verificationId = mCurrentIntentFilterVerifications.get(n); 773 final IntentFilterVerificationState ivs = 774 mIntentFilterVerificationStates.get(verificationId); 775 776 String packageName = ivs.getPackageName(); 777 778 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 779 final int filterCount = filters.size(); 780 ArraySet<String> domainsSet = new ArraySet<>(); 781 for (int m=0; m<filterCount; m++) { 782 PackageParser.ActivityIntentInfo filter = filters.get(m); 783 domainsSet.addAll(filter.getHostsList()); 784 } 785 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 786 synchronized (mPackages) { 787 if (mSettings.createIntentFilterVerificationIfNeededLPw( 788 packageName, domainsList) != null) { 789 scheduleWriteSettingsLocked(); 790 } 791 } 792 sendVerificationRequest(userId, verificationId, ivs); 793 } 794 mCurrentIntentFilterVerifications.clear(); 795 } 796 797 private void sendVerificationRequest(int userId, int verificationId, 798 IntentFilterVerificationState ivs) { 799 800 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 801 verificationIntent.putExtra( 802 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 803 verificationId); 804 verificationIntent.putExtra( 805 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 806 getDefaultScheme()); 807 verificationIntent.putExtra( 808 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 809 ivs.getHostsString()); 810 verificationIntent.putExtra( 811 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 812 ivs.getPackageName()); 813 verificationIntent.setComponent(mIntentFilterVerifierComponent); 814 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 815 816 UserHandle user = new UserHandle(userId); 817 mContext.sendBroadcastAsUser(verificationIntent, user); 818 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 819 "Sending IntentFilter verification broadcast"); 820 } 821 822 public void receiveVerificationResponse(int verificationId) { 823 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 824 825 final boolean verified = ivs.isVerified(); 826 827 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 828 final int count = filters.size(); 829 if (DEBUG_DOMAIN_VERIFICATION) { 830 Slog.i(TAG, "Received verification response " + verificationId 831 + " for " + count + " filters, verified=" + verified); 832 } 833 for (int n=0; n<count; n++) { 834 PackageParser.ActivityIntentInfo filter = filters.get(n); 835 filter.setVerified(verified); 836 837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 838 + " verified with result:" + verified + " and hosts:" 839 + ivs.getHostsString()); 840 } 841 842 mIntentFilterVerificationStates.remove(verificationId); 843 844 final String packageName = ivs.getPackageName(); 845 IntentFilterVerificationInfo ivi = null; 846 847 synchronized (mPackages) { 848 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 849 } 850 if (ivi == null) { 851 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 852 + verificationId + " packageName:" + packageName); 853 return; 854 } 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Updating IntentFilterVerificationInfo for package " + packageName 857 +" verificationId:" + verificationId); 858 859 synchronized (mPackages) { 860 if (verified) { 861 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 862 } else { 863 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 864 } 865 scheduleWriteSettingsLocked(); 866 867 final int userId = ivs.getUserId(); 868 if (userId != UserHandle.USER_ALL) { 869 final int userStatus = 870 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 871 872 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 873 boolean needUpdate = false; 874 875 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 876 // already been set by the User thru the Disambiguation dialog 877 switch (userStatus) { 878 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 879 if (verified) { 880 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 881 } else { 882 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 883 } 884 needUpdate = true; 885 break; 886 887 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 888 if (verified) { 889 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 890 needUpdate = true; 891 } 892 break; 893 894 default: 895 // Nothing to do 896 } 897 898 if (needUpdate) { 899 mSettings.updateIntentFilterVerificationStatusLPw( 900 packageName, updatedStatus, userId); 901 scheduleWritePackageRestrictionsLocked(userId); 902 } 903 } 904 } 905 } 906 907 @Override 908 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 909 ActivityIntentInfo filter, String packageName) { 910 if (!hasValidDomains(filter)) { 911 return false; 912 } 913 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 914 if (ivs == null) { 915 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 916 packageName); 917 } 918 if (DEBUG_DOMAIN_VERIFICATION) { 919 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 920 } 921 ivs.addFilter(filter); 922 return true; 923 } 924 925 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 926 int userId, int verificationId, String packageName) { 927 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 928 verifierUid, userId, packageName); 929 ivs.setPendingState(); 930 synchronized (mPackages) { 931 mIntentFilterVerificationStates.append(verificationId, ivs); 932 mCurrentIntentFilterVerifications.add(verificationId); 933 } 934 return ivs; 935 } 936 } 937 938 private static boolean hasValidDomains(ActivityIntentInfo filter) { 939 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 940 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 941 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 942 } 943 944 // Set of pending broadcasts for aggregating enable/disable of components. 945 static class PendingPackageBroadcasts { 946 // for each user id, a map of <package name -> components within that package> 947 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 948 949 public PendingPackageBroadcasts() { 950 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 951 } 952 953 public ArrayList<String> get(int userId, String packageName) { 954 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 955 return packages.get(packageName); 956 } 957 958 public void put(int userId, String packageName, ArrayList<String> components) { 959 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 960 packages.put(packageName, components); 961 } 962 963 public void remove(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 965 if (packages != null) { 966 packages.remove(packageName); 967 } 968 } 969 970 public void remove(int userId) { 971 mUidMap.remove(userId); 972 } 973 974 public int userIdCount() { 975 return mUidMap.size(); 976 } 977 978 public int userIdAt(int n) { 979 return mUidMap.keyAt(n); 980 } 981 982 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 983 return mUidMap.get(userId); 984 } 985 986 public int size() { 987 // total number of pending broadcast entries across all userIds 988 int num = 0; 989 for (int i = 0; i< mUidMap.size(); i++) { 990 num += mUidMap.valueAt(i).size(); 991 } 992 return num; 993 } 994 995 public void clear() { 996 mUidMap.clear(); 997 } 998 999 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1000 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1001 if (map == null) { 1002 map = new ArrayMap<String, ArrayList<String>>(); 1003 mUidMap.put(userId, map); 1004 } 1005 return map; 1006 } 1007 } 1008 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1009 1010 // Service Connection to remote media container service to copy 1011 // package uri's from external media onto secure containers 1012 // or internal storage. 1013 private IMediaContainerService mContainerService = null; 1014 1015 static final int SEND_PENDING_BROADCAST = 1; 1016 static final int MCS_BOUND = 3; 1017 static final int END_COPY = 4; 1018 static final int INIT_COPY = 5; 1019 static final int MCS_UNBIND = 6; 1020 static final int START_CLEANING_PACKAGE = 7; 1021 static final int FIND_INSTALL_LOC = 8; 1022 static final int POST_INSTALL = 9; 1023 static final int MCS_RECONNECT = 10; 1024 static final int MCS_GIVE_UP = 11; 1025 static final int UPDATED_MEDIA_STATUS = 12; 1026 static final int WRITE_SETTINGS = 13; 1027 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1028 static final int PACKAGE_VERIFIED = 15; 1029 static final int CHECK_PENDING_VERIFICATION = 16; 1030 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1031 static final int INTENT_FILTER_VERIFIED = 18; 1032 1033 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1034 1035 // Delay time in millisecs 1036 static final int BROADCAST_DELAY = 10 * 1000; 1037 1038 static UserManagerService sUserManager; 1039 1040 // Stores a list of users whose package restrictions file needs to be updated 1041 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1042 1043 final private DefaultContainerConnection mDefContainerConn = 1044 new DefaultContainerConnection(); 1045 class DefaultContainerConnection implements ServiceConnection { 1046 public void onServiceConnected(ComponentName name, IBinder service) { 1047 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1048 IMediaContainerService imcs = 1049 IMediaContainerService.Stub.asInterface(service); 1050 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1051 } 1052 1053 public void onServiceDisconnected(ComponentName name) { 1054 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1055 } 1056 } 1057 1058 // Recordkeeping of restore-after-install operations that are currently in flight 1059 // between the Package Manager and the Backup Manager 1060 static class PostInstallData { 1061 public InstallArgs args; 1062 public PackageInstalledInfo res; 1063 1064 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1065 args = _a; 1066 res = _r; 1067 } 1068 } 1069 1070 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1071 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1072 1073 // XML tags for backup/restore of various bits of state 1074 private static final String TAG_PREFERRED_BACKUP = "pa"; 1075 private static final String TAG_DEFAULT_APPS = "da"; 1076 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1077 1078 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1079 private static final String TAG_ALL_GRANTS = "rt-grants"; 1080 private static final String TAG_GRANT = "grant"; 1081 private static final String ATTR_PACKAGE_NAME = "pkg"; 1082 1083 private static final String TAG_PERMISSION = "perm"; 1084 private static final String ATTR_PERMISSION_NAME = "name"; 1085 private static final String ATTR_IS_GRANTED = "g"; 1086 private static final String ATTR_USER_SET = "set"; 1087 private static final String ATTR_USER_FIXED = "fixed"; 1088 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1089 1090 // System/policy permission grants are not backed up 1091 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1092 FLAG_PERMISSION_POLICY_FIXED 1093 | FLAG_PERMISSION_SYSTEM_FIXED 1094 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1095 1096 // And we back up these user-adjusted states 1097 private static final int USER_RUNTIME_GRANT_MASK = 1098 FLAG_PERMISSION_USER_SET 1099 | FLAG_PERMISSION_USER_FIXED 1100 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1101 1102 final @Nullable String mRequiredVerifierPackage; 1103 final @NonNull String mRequiredInstallerPackage; 1104 final @Nullable String mSetupWizardPackage; 1105 final @NonNull String mServicesSystemSharedLibraryPackageName; 1106 1107 private final PackageUsage mPackageUsage = new PackageUsage(); 1108 1109 private class PackageUsage { 1110 private static final int WRITE_INTERVAL 1111 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1112 1113 private final Object mFileLock = new Object(); 1114 private final AtomicLong mLastWritten = new AtomicLong(0); 1115 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1116 1117 private boolean mIsHistoricalPackageUsageAvailable = true; 1118 1119 boolean isHistoricalPackageUsageAvailable() { 1120 return mIsHistoricalPackageUsageAvailable; 1121 } 1122 1123 void write(boolean force) { 1124 if (force) { 1125 writeInternal(); 1126 return; 1127 } 1128 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1129 && !DEBUG_DEXOPT) { 1130 return; 1131 } 1132 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1133 new Thread("PackageUsage_DiskWriter") { 1134 @Override 1135 public void run() { 1136 try { 1137 writeInternal(); 1138 } finally { 1139 mBackgroundWriteRunning.set(false); 1140 } 1141 } 1142 }.start(); 1143 } 1144 } 1145 1146 private void writeInternal() { 1147 synchronized (mPackages) { 1148 synchronized (mFileLock) { 1149 AtomicFile file = getFile(); 1150 FileOutputStream f = null; 1151 try { 1152 f = file.startWrite(); 1153 BufferedOutputStream out = new BufferedOutputStream(f); 1154 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1155 StringBuilder sb = new StringBuilder(); 1156 for (PackageParser.Package pkg : mPackages.values()) { 1157 if (pkg.mLastPackageUsageTimeInMills == 0) { 1158 continue; 1159 } 1160 sb.setLength(0); 1161 sb.append(pkg.packageName); 1162 sb.append(' '); 1163 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1164 sb.append('\n'); 1165 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1166 } 1167 out.flush(); 1168 file.finishWrite(f); 1169 } catch (IOException e) { 1170 if (f != null) { 1171 file.failWrite(f); 1172 } 1173 Log.e(TAG, "Failed to write package usage times", e); 1174 } 1175 } 1176 } 1177 mLastWritten.set(SystemClock.elapsedRealtime()); 1178 } 1179 1180 void readLP() { 1181 synchronized (mFileLock) { 1182 AtomicFile file = getFile(); 1183 BufferedInputStream in = null; 1184 try { 1185 in = new BufferedInputStream(file.openRead()); 1186 StringBuffer sb = new StringBuffer(); 1187 while (true) { 1188 String packageName = readToken(in, sb, ' '); 1189 if (packageName == null) { 1190 break; 1191 } 1192 String timeInMillisString = readToken(in, sb, '\n'); 1193 if (timeInMillisString == null) { 1194 throw new IOException("Failed to find last usage time for package " 1195 + packageName); 1196 } 1197 PackageParser.Package pkg = mPackages.get(packageName); 1198 if (pkg == null) { 1199 continue; 1200 } 1201 long timeInMillis; 1202 try { 1203 timeInMillis = Long.parseLong(timeInMillisString); 1204 } catch (NumberFormatException e) { 1205 throw new IOException("Failed to parse " + timeInMillisString 1206 + " as a long.", e); 1207 } 1208 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1209 } 1210 } catch (FileNotFoundException expected) { 1211 mIsHistoricalPackageUsageAvailable = false; 1212 } catch (IOException e) { 1213 Log.w(TAG, "Failed to read package usage times", e); 1214 } finally { 1215 IoUtils.closeQuietly(in); 1216 } 1217 } 1218 mLastWritten.set(SystemClock.elapsedRealtime()); 1219 } 1220 1221 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1222 throws IOException { 1223 sb.setLength(0); 1224 while (true) { 1225 int ch = in.read(); 1226 if (ch == -1) { 1227 if (sb.length() == 0) { 1228 return null; 1229 } 1230 throw new IOException("Unexpected EOF"); 1231 } 1232 if (ch == endOfToken) { 1233 return sb.toString(); 1234 } 1235 sb.append((char)ch); 1236 } 1237 } 1238 1239 private AtomicFile getFile() { 1240 File dataDir = Environment.getDataDirectory(); 1241 File systemDir = new File(dataDir, "system"); 1242 File fname = new File(systemDir, "package-usage.list"); 1243 return new AtomicFile(fname); 1244 } 1245 } 1246 1247 class PackageHandler extends Handler { 1248 private boolean mBound = false; 1249 final ArrayList<HandlerParams> mPendingInstalls = 1250 new ArrayList<HandlerParams>(); 1251 1252 private boolean connectToService() { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1254 " DefaultContainerService"); 1255 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1256 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1257 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1258 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 mBound = true; 1261 return true; 1262 } 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 return false; 1265 } 1266 1267 private void disconnectService() { 1268 mContainerService = null; 1269 mBound = false; 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 mContext.unbindService(mDefContainerConn); 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 } 1274 1275 PackageHandler(Looper looper) { 1276 super(looper); 1277 } 1278 1279 public void handleMessage(Message msg) { 1280 try { 1281 doHandleMessage(msg); 1282 } finally { 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1284 } 1285 } 1286 1287 void doHandleMessage(Message msg) { 1288 switch (msg.what) { 1289 case INIT_COPY: { 1290 HandlerParams params = (HandlerParams) msg.obj; 1291 int idx = mPendingInstalls.size(); 1292 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1293 // If a bind was already initiated we dont really 1294 // need to do anything. The pending install 1295 // will be processed later on. 1296 if (!mBound) { 1297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1298 System.identityHashCode(mHandler)); 1299 // If this is the only one pending we might 1300 // have to bind to the service again. 1301 if (!connectToService()) { 1302 Slog.e(TAG, "Failed to bind to media container service"); 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1308 params.traceCookie); 1309 } 1310 return; 1311 } else { 1312 // Once we bind to the service, the first 1313 // pending request will be processed. 1314 mPendingInstalls.add(idx, params); 1315 } 1316 } else { 1317 mPendingInstalls.add(idx, params); 1318 // Already bound to the service. Just make 1319 // sure we trigger off processing the first request. 1320 if (idx == 0) { 1321 mHandler.sendEmptyMessage(MCS_BOUND); 1322 } 1323 } 1324 break; 1325 } 1326 case MCS_BOUND: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1328 if (msg.obj != null) { 1329 mContainerService = (IMediaContainerService) msg.obj; 1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1331 System.identityHashCode(mHandler)); 1332 } 1333 if (mContainerService == null) { 1334 if (!mBound) { 1335 // Something seriously wrong since we are not bound and we are not 1336 // waiting for connection. Bail out. 1337 Slog.e(TAG, "Cannot bind to media container service"); 1338 for (HandlerParams params : mPendingInstalls) { 1339 // Indicate service bind error 1340 params.serviceError(); 1341 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1342 System.identityHashCode(params)); 1343 if (params.traceMethod != null) { 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1345 params.traceMethod, params.traceCookie); 1346 } 1347 return; 1348 } 1349 mPendingInstalls.clear(); 1350 } else { 1351 Slog.w(TAG, "Waiting to connect to media container service"); 1352 } 1353 } else if (mPendingInstalls.size() > 0) { 1354 HandlerParams params = mPendingInstalls.get(0); 1355 if (params != null) { 1356 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1357 System.identityHashCode(params)); 1358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1359 if (params.startCopy()) { 1360 // We are done... look for more work or to 1361 // go idle. 1362 if (DEBUG_SD_INSTALL) Log.i(TAG, 1363 "Checking for more work or unbind..."); 1364 // Delete pending install 1365 if (mPendingInstalls.size() > 0) { 1366 mPendingInstalls.remove(0); 1367 } 1368 if (mPendingInstalls.size() == 0) { 1369 if (mBound) { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, 1371 "Posting delayed MCS_UNBIND"); 1372 removeMessages(MCS_UNBIND); 1373 Message ubmsg = obtainMessage(MCS_UNBIND); 1374 // Unbind after a little delay, to avoid 1375 // continual thrashing. 1376 sendMessageDelayed(ubmsg, 10000); 1377 } 1378 } else { 1379 // There are more pending requests in queue. 1380 // Just post MCS_BOUND message to trigger processing 1381 // of next pending install. 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, 1383 "Posting MCS_BOUND for next work"); 1384 mHandler.sendEmptyMessage(MCS_BOUND); 1385 } 1386 } 1387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1388 } 1389 } else { 1390 // Should never happen ideally. 1391 Slog.w(TAG, "Empty queue"); 1392 } 1393 break; 1394 } 1395 case MCS_RECONNECT: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1397 if (mPendingInstalls.size() > 0) { 1398 if (mBound) { 1399 disconnectService(); 1400 } 1401 if (!connectToService()) { 1402 Slog.e(TAG, "Failed to bind to media container service"); 1403 for (HandlerParams params : mPendingInstalls) { 1404 // Indicate service bind error 1405 params.serviceError(); 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1407 System.identityHashCode(params)); 1408 } 1409 mPendingInstalls.clear(); 1410 } 1411 } 1412 break; 1413 } 1414 case MCS_UNBIND: { 1415 // If there is no actual work left, then time to unbind. 1416 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1417 1418 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1419 if (mBound) { 1420 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1421 1422 disconnectService(); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 // There are more pending requests in queue. 1426 // Just post MCS_BOUND message to trigger processing 1427 // of next pending install. 1428 mHandler.sendEmptyMessage(MCS_BOUND); 1429 } 1430 1431 break; 1432 } 1433 case MCS_GIVE_UP: { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1435 HandlerParams params = mPendingInstalls.remove(0); 1436 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1437 System.identityHashCode(params)); 1438 break; 1439 } 1440 case SEND_PENDING_BROADCAST: { 1441 String packages[]; 1442 ArrayList<String> components[]; 1443 int size = 0; 1444 int uids[]; 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 if (mPendingBroadcasts == null) { 1448 return; 1449 } 1450 size = mPendingBroadcasts.size(); 1451 if (size <= 0) { 1452 // Nothing to be done. Just return 1453 return; 1454 } 1455 packages = new String[size]; 1456 components = new ArrayList[size]; 1457 uids = new int[size]; 1458 int i = 0; // filling out the above arrays 1459 1460 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1461 int packageUserId = mPendingBroadcasts.userIdAt(n); 1462 Iterator<Map.Entry<String, ArrayList<String>>> it 1463 = mPendingBroadcasts.packagesForUserId(packageUserId) 1464 .entrySet().iterator(); 1465 while (it.hasNext() && i < size) { 1466 Map.Entry<String, ArrayList<String>> ent = it.next(); 1467 packages[i] = ent.getKey(); 1468 components[i] = ent.getValue(); 1469 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1470 uids[i] = (ps != null) 1471 ? UserHandle.getUid(packageUserId, ps.appId) 1472 : -1; 1473 i++; 1474 } 1475 } 1476 size = i; 1477 mPendingBroadcasts.clear(); 1478 } 1479 // Send broadcasts 1480 for (int i = 0; i < size; i++) { 1481 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 break; 1485 } 1486 case START_CLEANING_PACKAGE: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 final String packageName = (String)msg.obj; 1489 final int userId = msg.arg1; 1490 final boolean andCode = msg.arg2 != 0; 1491 synchronized (mPackages) { 1492 if (userId == UserHandle.USER_ALL) { 1493 int[] users = sUserManager.getUserIds(); 1494 for (int user : users) { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(user, packageName, andCode)); 1497 } 1498 } else { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(userId, packageName, andCode)); 1501 } 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 startCleaningPackages(); 1505 } break; 1506 case POST_INSTALL: { 1507 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1508 1509 PostInstallData data = mRunningInstalls.get(msg.arg1); 1510 mRunningInstalls.delete(msg.arg1); 1511 1512 if (data != null) { 1513 InstallArgs args = data.args; 1514 PackageInstalledInfo parentRes = data.res; 1515 1516 final boolean grantPermissions = (args.installFlags 1517 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1518 final boolean killApp = (args.installFlags 1519 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1520 final String[] grantedPermissions = args.installGrantPermissions; 1521 1522 // Handle the parent package 1523 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1524 grantedPermissions, args.observer); 1525 1526 // Handle the child packages 1527 final int childCount = (parentRes.addedChildPackages != null) 1528 ? parentRes.addedChildPackages.size() : 0; 1529 for (int i = 0; i < childCount; i++) { 1530 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1531 handlePackagePostInstall(childRes, grantPermissions, killApp, 1532 grantedPermissions, args.observer); 1533 } 1534 1535 // Log tracing if needed 1536 if (args.traceMethod != null) { 1537 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1538 args.traceCookie); 1539 } 1540 } else { 1541 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1542 } 1543 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1545 } break; 1546 case UPDATED_MEDIA_STATUS: { 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1548 boolean reportStatus = msg.arg1 == 1; 1549 boolean doGc = msg.arg2 == 1; 1550 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1551 if (doGc) { 1552 // Force a gc to clear up stale containers. 1553 Runtime.getRuntime().gc(); 1554 } 1555 if (msg.obj != null) { 1556 @SuppressWarnings("unchecked") 1557 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1559 // Unload containers 1560 unloadAllContainers(args); 1561 } 1562 if (reportStatus) { 1563 try { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1565 PackageHelper.getMountService().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "MountService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case CHECK_PENDING_VERIFICATION: { 1593 final int verificationId = msg.arg1; 1594 final PackageVerificationState state = mPendingVerification.get(verificationId); 1595 1596 if ((state != null) && !state.timeoutExtended()) { 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 Slog.i(TAG, "Verification timed out for " + originUri); 1601 mPendingVerification.remove(verificationId); 1602 1603 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1604 1605 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1606 Slog.i(TAG, "Continuing with installation of " + originUri); 1607 state.setVerifierResponse(Binder.getCallingUid(), 1608 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1609 broadcastPackageVerified(verificationId, originUri, 1610 PackageManager.VERIFICATION_ALLOW, 1611 state.getInstallArgs().getUser()); 1612 try { 1613 ret = args.copyApk(mContainerService, true); 1614 } catch (RemoteException e) { 1615 Slog.e(TAG, "Could not contact the ContainerService"); 1616 } 1617 } else { 1618 broadcastPackageVerified(verificationId, originUri, 1619 PackageManager.VERIFICATION_REJECT, 1620 state.getInstallArgs().getUser()); 1621 } 1622 1623 Trace.asyncTraceEnd( 1624 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1625 1626 processPendingInstall(args, ret); 1627 mHandler.sendEmptyMessage(MCS_UNBIND); 1628 } 1629 break; 1630 } 1631 case PACKAGE_VERIFIED: { 1632 final int verificationId = msg.arg1; 1633 1634 final PackageVerificationState state = mPendingVerification.get(verificationId); 1635 if (state == null) { 1636 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1637 break; 1638 } 1639 1640 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1641 1642 state.setVerifierResponse(response.callerUid, response.code); 1643 1644 if (state.isVerificationComplete()) { 1645 mPendingVerification.remove(verificationId); 1646 1647 final InstallArgs args = state.getInstallArgs(); 1648 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1649 1650 int ret; 1651 if (state.isInstallAllowed()) { 1652 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1653 broadcastPackageVerified(verificationId, originUri, 1654 response.code, state.getInstallArgs().getUser()); 1655 try { 1656 ret = args.copyApk(mContainerService, true); 1657 } catch (RemoteException e) { 1658 Slog.e(TAG, "Could not contact the ContainerService"); 1659 } 1660 } else { 1661 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1662 } 1663 1664 Trace.asyncTraceEnd( 1665 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1666 1667 processPendingInstall(args, ret); 1668 mHandler.sendEmptyMessage(MCS_UNBIND); 1669 } 1670 1671 break; 1672 } 1673 case START_INTENT_FILTER_VERIFICATIONS: { 1674 IFVerificationParams params = (IFVerificationParams) msg.obj; 1675 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1676 params.replacing, params.pkg); 1677 break; 1678 } 1679 case INTENT_FILTER_VERIFIED: { 1680 final int verificationId = msg.arg1; 1681 1682 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1683 verificationId); 1684 if (state == null) { 1685 Slog.w(TAG, "Invalid IntentFilter verification token " 1686 + verificationId + " received"); 1687 break; 1688 } 1689 1690 final int userId = state.getUserId(); 1691 1692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1693 "Processing IntentFilter verification with token:" 1694 + verificationId + " and userId:" + userId); 1695 1696 final IntentFilterVerificationResponse response = 1697 (IntentFilterVerificationResponse) msg.obj; 1698 1699 state.setVerifierResponse(response.callerUid, response.code); 1700 1701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1702 "IntentFilter verification with token:" + verificationId 1703 + " and userId:" + userId 1704 + " is settings verifier response with response code:" 1705 + response.code); 1706 1707 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1709 + response.getFailedDomainsString()); 1710 } 1711 1712 if (state.isVerificationComplete()) { 1713 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1714 } else { 1715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1716 "IntentFilter verification with token:" + verificationId 1717 + " was not said to be complete"); 1718 } 1719 1720 break; 1721 } 1722 } 1723 } 1724 } 1725 1726 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1727 boolean killApp, String[] grantedPermissions, 1728 IPackageInstallObserver2 installObserver) { 1729 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1730 // Send the removed broadcasts 1731 if (res.removedInfo != null) { 1732 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1733 } 1734 1735 // Now that we successfully installed the package, grant runtime 1736 // permissions if requested before broadcasting the install. 1737 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1738 >= Build.VERSION_CODES.M) { 1739 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1740 } 1741 1742 final boolean update = res.removedInfo != null 1743 && res.removedInfo.removedPackage != null; 1744 1745 // If this is the first time we have child packages for a disabled privileged 1746 // app that had no children, we grant requested runtime permissions to the new 1747 // children if the parent on the system image had them already granted. 1748 if (res.pkg.parentPackage != null) { 1749 synchronized (mPackages) { 1750 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1751 } 1752 } 1753 1754 synchronized (mPackages) { 1755 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1756 } 1757 1758 final String packageName = res.pkg.applicationInfo.packageName; 1759 Bundle extras = new Bundle(1); 1760 extras.putInt(Intent.EXTRA_UID, res.uid); 1761 1762 // Determine the set of users who are adding this package for 1763 // the first time vs. those who are seeing an update. 1764 int[] firstUsers = EMPTY_INT_ARRAY; 1765 int[] updateUsers = EMPTY_INT_ARRAY; 1766 if (res.origUsers == null || res.origUsers.length == 0) { 1767 firstUsers = res.newUsers; 1768 } else { 1769 for (int newUser : res.newUsers) { 1770 boolean isNew = true; 1771 for (int origUser : res.origUsers) { 1772 if (origUser == newUser) { 1773 isNew = false; 1774 break; 1775 } 1776 } 1777 if (isNew) { 1778 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1779 } else { 1780 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1781 } 1782 } 1783 } 1784 1785 // Send installed broadcasts if the install/update is not ephemeral 1786 if (!isEphemeral(res.pkg)) { 1787 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1788 1789 // Send added for users that see the package for the first time 1790 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1791 extras, 0 /*flags*/, null /*targetPackage*/, 1792 null /*finishedReceiver*/, firstUsers); 1793 1794 // Send added for users that don't see the package for the first time 1795 if (update) { 1796 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1797 } 1798 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1799 extras, 0 /*flags*/, null /*targetPackage*/, 1800 null /*finishedReceiver*/, updateUsers); 1801 1802 // Send replaced for users that don't see the package for the first time 1803 if (update) { 1804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1805 packageName, extras, 0 /*flags*/, 1806 null /*targetPackage*/, null /*finishedReceiver*/, 1807 updateUsers); 1808 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1809 null /*package*/, null /*extras*/, 0 /*flags*/, 1810 packageName /*targetPackage*/, 1811 null /*finishedReceiver*/, updateUsers); 1812 } 1813 1814 // Send broadcast package appeared if forward locked/external for all users 1815 // treat asec-hosted packages like removable media on upgrade 1816 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1817 if (DEBUG_INSTALL) { 1818 Slog.i(TAG, "upgrading pkg " + res.pkg 1819 + " is ASEC-hosted -> AVAILABLE"); 1820 } 1821 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1822 ArrayList<String> pkgList = new ArrayList<>(1); 1823 pkgList.add(packageName); 1824 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1825 } 1826 } 1827 1828 // Work that needs to happen on first install within each user 1829 if (firstUsers != null && firstUsers.length > 0) { 1830 synchronized (mPackages) { 1831 for (int userId : firstUsers) { 1832 // If this app is a browser and it's newly-installed for some 1833 // users, clear any default-browser state in those users. The 1834 // app's nature doesn't depend on the user, so we can just check 1835 // its browser nature in any user and generalize. 1836 if (packageIsBrowser(packageName, userId)) { 1837 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1838 } 1839 1840 // We may also need to apply pending (restored) runtime 1841 // permission grants within these users. 1842 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1843 } 1844 } 1845 } 1846 1847 // Log current value of "unknown sources" setting 1848 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1849 getUnknownSourcesSettings()); 1850 1851 // Force a gc to clear up things 1852 Runtime.getRuntime().gc(); 1853 1854 // Remove the replaced package's older resources safely now 1855 // We delete after a gc for applications on sdcard. 1856 if (res.removedInfo != null && res.removedInfo.args != null) { 1857 synchronized (mInstallLock) { 1858 res.removedInfo.args.doPostDeleteLI(true); 1859 } 1860 } 1861 } 1862 1863 // If someone is watching installs - notify them 1864 if (installObserver != null) { 1865 try { 1866 Bundle extras = extrasForInstallResult(res); 1867 installObserver.onPackageInstalled(res.name, res.returnCode, 1868 res.returnMsg, extras); 1869 } catch (RemoteException e) { 1870 Slog.i(TAG, "Observer no longer exists."); 1871 } 1872 } 1873 } 1874 1875 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1876 PackageParser.Package pkg) { 1877 if (pkg.parentPackage == null) { 1878 return; 1879 } 1880 if (pkg.requestedPermissions == null) { 1881 return; 1882 } 1883 final PackageSetting disabledSysParentPs = mSettings 1884 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1885 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1886 || !disabledSysParentPs.isPrivileged() 1887 || (disabledSysParentPs.childPackageNames != null 1888 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1889 return; 1890 } 1891 final int[] allUserIds = sUserManager.getUserIds(); 1892 final int permCount = pkg.requestedPermissions.size(); 1893 for (int i = 0; i < permCount; i++) { 1894 String permission = pkg.requestedPermissions.get(i); 1895 BasePermission bp = mSettings.mPermissions.get(permission); 1896 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1897 continue; 1898 } 1899 for (int userId : allUserIds) { 1900 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1901 permission, userId)) { 1902 grantRuntimePermission(pkg.packageName, permission, userId); 1903 } 1904 } 1905 } 1906 } 1907 1908 private StorageEventListener mStorageListener = new StorageEventListener() { 1909 @Override 1910 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1911 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1912 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1913 final String volumeUuid = vol.getFsUuid(); 1914 1915 // Clean up any users or apps that were removed or recreated 1916 // while this volume was missing 1917 reconcileUsers(volumeUuid); 1918 reconcileApps(volumeUuid); 1919 1920 // Clean up any install sessions that expired or were 1921 // cancelled while this volume was missing 1922 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1923 1924 loadPrivatePackages(vol); 1925 1926 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1927 unloadPrivatePackages(vol); 1928 } 1929 } 1930 1931 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1932 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1933 updateExternalMediaStatus(true, false); 1934 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1935 updateExternalMediaStatus(false, false); 1936 } 1937 } 1938 } 1939 1940 @Override 1941 public void onVolumeForgotten(String fsUuid) { 1942 if (TextUtils.isEmpty(fsUuid)) { 1943 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1944 return; 1945 } 1946 1947 // Remove any apps installed on the forgotten volume 1948 synchronized (mPackages) { 1949 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1950 for (PackageSetting ps : packages) { 1951 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1952 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1953 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1954 } 1955 1956 mSettings.onVolumeForgotten(fsUuid); 1957 mSettings.writeLPr(); 1958 } 1959 } 1960 }; 1961 1962 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1963 String[] grantedPermissions) { 1964 for (int userId : userIds) { 1965 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1966 } 1967 1968 // We could have touched GID membership, so flush out packages.list 1969 synchronized (mPackages) { 1970 mSettings.writePackageListLPr(); 1971 } 1972 } 1973 1974 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1975 String[] grantedPermissions) { 1976 SettingBase sb = (SettingBase) pkg.mExtras; 1977 if (sb == null) { 1978 return; 1979 } 1980 1981 PermissionsState permissionsState = sb.getPermissionsState(); 1982 1983 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1984 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1985 1986 synchronized (mPackages) { 1987 for (String permission : pkg.requestedPermissions) { 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1990 && (grantedPermissions == null 1991 || ArrayUtils.contains(grantedPermissions, permission))) { 1992 final int flags = permissionsState.getPermissionFlags(permission, userId); 1993 // Installer cannot change immutable permissions. 1994 if ((flags & immutableFlags) == 0) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 } 2001 2002 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2003 Bundle extras = null; 2004 switch (res.returnCode) { 2005 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2006 extras = new Bundle(); 2007 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2008 res.origPermission); 2009 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2010 res.origPackage); 2011 break; 2012 } 2013 case PackageManager.INSTALL_SUCCEEDED: { 2014 extras = new Bundle(); 2015 extras.putBoolean(Intent.EXTRA_REPLACING, 2016 res.removedInfo != null && res.removedInfo.removedPackage != null); 2017 break; 2018 } 2019 } 2020 return extras; 2021 } 2022 2023 void scheduleWriteSettingsLocked() { 2024 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2025 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2026 } 2027 } 2028 2029 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2030 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2031 scheduleWritePackageRestrictionsLocked(userId); 2032 } 2033 2034 void scheduleWritePackageRestrictionsLocked(int userId) { 2035 final int[] userIds = (userId == UserHandle.USER_ALL) 2036 ? sUserManager.getUserIds() : new int[]{userId}; 2037 for (int nextUserId : userIds) { 2038 if (!sUserManager.exists(nextUserId)) return; 2039 mDirtyUsers.add(nextUserId); 2040 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2041 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2042 } 2043 } 2044 } 2045 2046 public static PackageManagerService main(Context context, Installer installer, 2047 boolean factoryTest, boolean onlyCore) { 2048 // Self-check for initial settings. 2049 PackageManagerServiceCompilerMapping.checkProperties(); 2050 2051 PackageManagerService m = new PackageManagerService(context, installer, 2052 factoryTest, onlyCore); 2053 m.enableSystemUserPackages(); 2054 ServiceManager.addService("package", m); 2055 return m; 2056 } 2057 2058 private void enableSystemUserPackages() { 2059 if (!UserManager.isSplitSystemUser()) { 2060 return; 2061 } 2062 // For system user, enable apps based on the following conditions: 2063 // - app is whitelisted or belong to one of these groups: 2064 // -- system app which has no launcher icons 2065 // -- system app which has INTERACT_ACROSS_USERS permission 2066 // -- system IME app 2067 // - app is not in the blacklist 2068 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2069 Set<String> enableApps = new ArraySet<>(); 2070 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2071 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2072 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2073 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2074 enableApps.addAll(wlApps); 2075 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2076 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2077 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2078 enableApps.removeAll(blApps); 2079 Log.i(TAG, "Applications installed for system user: " + enableApps); 2080 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2081 UserHandle.SYSTEM); 2082 final int allAppsSize = allAps.size(); 2083 synchronized (mPackages) { 2084 for (int i = 0; i < allAppsSize; i++) { 2085 String pName = allAps.get(i); 2086 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2087 // Should not happen, but we shouldn't be failing if it does 2088 if (pkgSetting == null) { 2089 continue; 2090 } 2091 boolean install = enableApps.contains(pName); 2092 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2093 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2094 + " for system user"); 2095 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2096 } 2097 } 2098 } 2099 } 2100 2101 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2102 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2103 Context.DISPLAY_SERVICE); 2104 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2105 } 2106 2107 public PackageManagerService(Context context, Installer installer, 2108 boolean factoryTest, boolean onlyCore) { 2109 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2110 SystemClock.uptimeMillis()); 2111 2112 if (mSdkVersion <= 0) { 2113 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2114 } 2115 2116 mContext = context; 2117 mFactoryTest = factoryTest; 2118 mOnlyCore = onlyCore; 2119 mMetrics = new DisplayMetrics(); 2120 mSettings = new Settings(mPackages); 2121 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2122 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2123 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2124 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2125 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2126 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2127 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2128 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2129 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2130 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2131 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2132 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2133 2134 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2135 if (separateProcesses != null && separateProcesses.length() > 0) { 2136 if ("*".equals(separateProcesses)) { 2137 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2138 mSeparateProcesses = null; 2139 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2140 } else { 2141 mDefParseFlags = 0; 2142 mSeparateProcesses = separateProcesses.split(","); 2143 Slog.w(TAG, "Running with debug.separate_processes: " 2144 + separateProcesses); 2145 } 2146 } else { 2147 mDefParseFlags = 0; 2148 mSeparateProcesses = null; 2149 } 2150 2151 mInstaller = installer; 2152 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2153 "*dexopt*"); 2154 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2155 2156 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2157 FgThread.get().getLooper()); 2158 2159 getDefaultDisplayMetrics(context, mMetrics); 2160 2161 SystemConfig systemConfig = SystemConfig.getInstance(); 2162 mGlobalGids = systemConfig.getGlobalGids(); 2163 mSystemPermissions = systemConfig.getSystemPermissions(); 2164 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2165 2166 synchronized (mInstallLock) { 2167 // writer 2168 synchronized (mPackages) { 2169 mHandlerThread = new ServiceThread(TAG, 2170 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2171 mHandlerThread.start(); 2172 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2173 mProcessLoggingHandler = new ProcessLoggingHandler(); 2174 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2175 2176 File dataDir = Environment.getDataDirectory(); 2177 mAppInstallDir = new File(dataDir, "app"); 2178 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2179 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2180 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2181 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2182 2183 sUserManager = new UserManagerService(context, this, mPackages); 2184 2185 // Propagate permission configuration in to package manager. 2186 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2187 = systemConfig.getPermissions(); 2188 for (int i=0; i<permConfig.size(); i++) { 2189 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2190 BasePermission bp = mSettings.mPermissions.get(perm.name); 2191 if (bp == null) { 2192 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2193 mSettings.mPermissions.put(perm.name, bp); 2194 } 2195 if (perm.gids != null) { 2196 bp.setGids(perm.gids, perm.perUser); 2197 } 2198 } 2199 2200 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2201 for (int i=0; i<libConfig.size(); i++) { 2202 mSharedLibraries.put(libConfig.keyAt(i), 2203 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2204 } 2205 2206 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2207 2208 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2209 2210 String customResolverActivity = Resources.getSystem().getString( 2211 R.string.config_customResolverActivity); 2212 if (TextUtils.isEmpty(customResolverActivity)) { 2213 customResolverActivity = null; 2214 } else { 2215 mCustomResolverComponentName = ComponentName.unflattenFromString( 2216 customResolverActivity); 2217 } 2218 2219 long startTime = SystemClock.uptimeMillis(); 2220 2221 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2222 startTime); 2223 2224 // Set flag to monitor and not change apk file paths when 2225 // scanning install directories. 2226 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2227 2228 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2229 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2230 2231 if (bootClassPath == null) { 2232 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2233 } 2234 2235 if (systemServerClassPath == null) { 2236 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2237 } 2238 2239 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2240 final String[] dexCodeInstructionSets = 2241 getDexCodeInstructionSets( 2242 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2243 2244 /** 2245 * Ensure all external libraries have had dexopt run on them. 2246 */ 2247 if (mSharedLibraries.size() > 0) { 2248 // NOTE: For now, we're compiling these system "shared libraries" 2249 // (and framework jars) into all available architectures. It's possible 2250 // to compile them only when we come across an app that uses them (there's 2251 // already logic for that in scanPackageLI) but that adds some complexity. 2252 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2253 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2254 final String lib = libEntry.path; 2255 if (lib == null) { 2256 continue; 2257 } 2258 2259 try { 2260 // Shared libraries do not have profiles so we perform a full 2261 // AOT compilation (if needed). 2262 int dexoptNeeded = DexFile.getDexOptNeeded( 2263 lib, dexCodeInstructionSet, 2264 getCompilerFilterForReason(REASON_SHARED_APK), 2265 false /* newProfile */); 2266 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2267 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2268 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2269 getCompilerFilterForReason(REASON_SHARED_APK), 2270 StorageManager.UUID_PRIVATE_INTERNAL); 2271 } 2272 } catch (FileNotFoundException e) { 2273 Slog.w(TAG, "Library not found: " + lib); 2274 } catch (IOException | InstallerException e) { 2275 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2276 + e.getMessage()); 2277 } 2278 } 2279 } 2280 } 2281 2282 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2283 2284 final VersionInfo ver = mSettings.getInternalVersion(); 2285 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2286 2287 // when upgrading from pre-M, promote system app permissions from install to runtime 2288 mPromoteSystemApps = 2289 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2290 2291 // save off the names of pre-existing system packages prior to scanning; we don't 2292 // want to automatically grant runtime permissions for new system apps 2293 if (mPromoteSystemApps) { 2294 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2295 while (pkgSettingIter.hasNext()) { 2296 PackageSetting ps = pkgSettingIter.next(); 2297 if (isSystemApp(ps)) { 2298 mExistingSystemPackages.add(ps.name); 2299 } 2300 } 2301 } 2302 2303 // When upgrading from pre-N, we need to handle package extraction like first boot, 2304 // as there is no profiling data available. 2305 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2306 mSettings.setNWorkDone(); 2307 2308 // Collect vendor overlay packages. 2309 // (Do this before scanning any apps.) 2310 // For security and version matching reason, only consider 2311 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2312 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2313 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2314 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2315 2316 // Find base frameworks (resource packages without code). 2317 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR 2319 | PackageParser.PARSE_IS_PRIVILEGED, 2320 scanFlags | SCAN_NO_DEX, 0); 2321 2322 // Collected privileged system packages. 2323 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2324 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR 2326 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2327 2328 // Collect ordinary system packages. 2329 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2330 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2332 2333 // Collect all vendor packages. 2334 File vendorAppDir = new File("/vendor/app"); 2335 try { 2336 vendorAppDir = vendorAppDir.getCanonicalFile(); 2337 } catch (IOException e) { 2338 // failed to look up canonical path, continue with original one 2339 } 2340 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2341 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2342 2343 // Collect all OEM packages. 2344 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2345 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2346 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2347 2348 // Prune any system packages that no longer exist. 2349 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2350 if (!mOnlyCore) { 2351 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2352 while (psit.hasNext()) { 2353 PackageSetting ps = psit.next(); 2354 2355 /* 2356 * If this is not a system app, it can't be a 2357 * disable system app. 2358 */ 2359 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2360 continue; 2361 } 2362 2363 /* 2364 * If the package is scanned, it's not erased. 2365 */ 2366 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2367 if (scannedPkg != null) { 2368 /* 2369 * If the system app is both scanned and in the 2370 * disabled packages list, then it must have been 2371 * added via OTA. Remove it from the currently 2372 * scanned package so the previously user-installed 2373 * application can be scanned. 2374 */ 2375 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2376 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2377 + ps.name + "; removing system app. Last known codePath=" 2378 + ps.codePathString + ", installStatus=" + ps.installStatus 2379 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2380 + scannedPkg.mVersionCode); 2381 removePackageLI(scannedPkg, true); 2382 mExpectingBetter.put(ps.name, ps.codePath); 2383 } 2384 2385 continue; 2386 } 2387 2388 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2389 psit.remove(); 2390 logCriticalInfo(Log.WARN, "System package " + ps.name 2391 + " no longer exists; wiping its data"); 2392 // No apps are running this early, so no need to freeze 2393 removeDataDirsLIF(null, ps.name); 2394 } else { 2395 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2396 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2397 possiblyDeletedUpdatedSystemApps.add(ps.name); 2398 } 2399 } 2400 } 2401 } 2402 2403 //look for any incomplete package installations 2404 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2405 for (int i = 0; i < deletePkgsList.size(); i++) { 2406 // No apps are running this early, so no need to freeze 2407 cleanupInstallFailedPackageLIF(deletePkgsList.get(i)); 2408 } 2409 2410 //delete tmp files 2411 deleteTempPackageFiles(); 2412 2413 // Remove any shared userIDs that have no associated packages 2414 mSettings.pruneSharedUsersLPw(); 2415 2416 if (!mOnlyCore) { 2417 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2418 SystemClock.uptimeMillis()); 2419 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2420 2421 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2422 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2423 2424 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2425 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2426 2427 /** 2428 * Remove disable package settings for any updated system 2429 * apps that were removed via an OTA. If they're not a 2430 * previously-updated app, remove them completely. 2431 * Otherwise, just revoke their system-level permissions. 2432 */ 2433 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2434 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2435 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2436 2437 String msg; 2438 if (deletedPkg == null) { 2439 msg = "Updated system package " + deletedAppName 2440 + " no longer exists; wiping its data"; 2441 // No apps are running this early, so no need to freeze 2442 removeDataDirsLIF(null, deletedAppName); 2443 } else { 2444 msg = "Updated system app + " + deletedAppName 2445 + " no longer present; removing system privileges for " 2446 + deletedAppName; 2447 2448 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2449 2450 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2451 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2452 } 2453 logCriticalInfo(Log.WARN, msg); 2454 } 2455 2456 /** 2457 * Make sure all system apps that we expected to appear on 2458 * the userdata partition actually showed up. If they never 2459 * appeared, crawl back and revive the system version. 2460 */ 2461 for (int i = 0; i < mExpectingBetter.size(); i++) { 2462 final String packageName = mExpectingBetter.keyAt(i); 2463 if (!mPackages.containsKey(packageName)) { 2464 final File scanFile = mExpectingBetter.valueAt(i); 2465 2466 logCriticalInfo(Log.WARN, "Expected better " + packageName 2467 + " but never showed up; reverting to system"); 2468 2469 final int reparseFlags; 2470 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2471 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2472 | PackageParser.PARSE_IS_SYSTEM_DIR 2473 | PackageParser.PARSE_IS_PRIVILEGED; 2474 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2475 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2476 | PackageParser.PARSE_IS_SYSTEM_DIR; 2477 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2478 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2479 | PackageParser.PARSE_IS_SYSTEM_DIR; 2480 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2481 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2482 | PackageParser.PARSE_IS_SYSTEM_DIR; 2483 } else { 2484 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2485 continue; 2486 } 2487 2488 mSettings.enableSystemPackageLPw(packageName); 2489 2490 try { 2491 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2492 } catch (PackageManagerException e) { 2493 Slog.e(TAG, "Failed to parse original system package: " 2494 + e.getMessage()); 2495 } 2496 } 2497 } 2498 } 2499 mExpectingBetter.clear(); 2500 2501 // Resolve protected action filters. Only the setup wizard is allowed to 2502 // have a high priority filter for these actions. 2503 mSetupWizardPackage = getSetupWizardPackageName(); 2504 if (mProtectedFilters.size() > 0) { 2505 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2506 Slog.i(TAG, "No setup wizard;" 2507 + " All protected intents capped to priority 0"); 2508 } 2509 for (ActivityIntentInfo filter : mProtectedFilters) { 2510 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2511 if (DEBUG_FILTERS) { 2512 Slog.i(TAG, "Found setup wizard;" 2513 + " allow priority " + filter.getPriority() + ";" 2514 + " package: " + filter.activity.info.packageName 2515 + " activity: " + filter.activity.className 2516 + " priority: " + filter.getPriority()); 2517 } 2518 // skip setup wizard; allow it to keep the high priority filter 2519 continue; 2520 } 2521 Slog.w(TAG, "Protected action; cap priority to 0;" 2522 + " package: " + filter.activity.info.packageName 2523 + " activity: " + filter.activity.className 2524 + " origPrio: " + filter.getPriority()); 2525 filter.setPriority(0); 2526 } 2527 } 2528 mDeferProtectedFilters = false; 2529 mProtectedFilters.clear(); 2530 2531 // Now that we know all of the shared libraries, update all clients to have 2532 // the correct library paths. 2533 updateAllSharedLibrariesLPw(); 2534 2535 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2536 // NOTE: We ignore potential failures here during a system scan (like 2537 // the rest of the commands above) because there's precious little we 2538 // can do about it. A settings error is reported, though. 2539 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2540 false /* boot complete */); 2541 } 2542 2543 // Now that we know all the packages we are keeping, 2544 // read and update their last usage times. 2545 mPackageUsage.readLP(); 2546 2547 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2548 SystemClock.uptimeMillis()); 2549 Slog.i(TAG, "Time to scan packages: " 2550 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2551 + " seconds"); 2552 2553 // If the platform SDK has changed since the last time we booted, 2554 // we need to re-grant app permission to catch any new ones that 2555 // appear. This is really a hack, and means that apps can in some 2556 // cases get permissions that the user didn't initially explicitly 2557 // allow... it would be nice to have some better way to handle 2558 // this situation. 2559 int updateFlags = UPDATE_PERMISSIONS_ALL; 2560 if (ver.sdkVersion != mSdkVersion) { 2561 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2562 + mSdkVersion + "; regranting permissions for internal storage"); 2563 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2564 } 2565 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2566 ver.sdkVersion = mSdkVersion; 2567 2568 // If this is the first boot or an update from pre-M, and it is a normal 2569 // boot, then we need to initialize the default preferred apps across 2570 // all defined users. 2571 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2572 for (UserInfo user : sUserManager.getUsers(true)) { 2573 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2574 applyFactoryDefaultBrowserLPw(user.id); 2575 primeDomainVerificationsLPw(user.id); 2576 } 2577 } 2578 2579 // Prepare storage for system user really early during boot, 2580 // since core system apps like SettingsProvider and SystemUI 2581 // can't wait for user to start 2582 final int storageFlags; 2583 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2584 storageFlags = StorageManager.FLAG_STORAGE_DE; 2585 } else { 2586 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2587 } 2588 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2589 storageFlags); 2590 2591 // If this is first boot after an OTA, and a normal boot, then 2592 // we need to clear code cache directories. 2593 if (mIsUpgrade && !onlyCore) { 2594 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2595 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2596 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2597 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2598 // No apps are running this early, so no need to freeze 2599 deleteCodeCacheDirsLIF(ps.volumeUuid, ps.name); 2600 } 2601 } 2602 ver.fingerprint = Build.FINGERPRINT; 2603 } 2604 2605 checkDefaultBrowser(); 2606 2607 // clear only after permissions and other defaults have been updated 2608 mExistingSystemPackages.clear(); 2609 mPromoteSystemApps = false; 2610 2611 // All the changes are done during package scanning. 2612 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2613 2614 // can downgrade to reader 2615 mSettings.writeLPr(); 2616 2617 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2618 SystemClock.uptimeMillis()); 2619 2620 if (!mOnlyCore) { 2621 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2622 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2623 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2624 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2625 mIntentFilterVerifierComponent); 2626 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2627 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2628 getRequiredSharedLibraryLPr( 2629 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2630 } else { 2631 mRequiredVerifierPackage = null; 2632 mRequiredInstallerPackage = null; 2633 mIntentFilterVerifierComponent = null; 2634 mIntentFilterVerifier = null; 2635 mServicesSystemSharedLibraryPackageName = null; 2636 } 2637 2638 mInstallerService = new PackageInstallerService(context, this); 2639 2640 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2641 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2642 // both the installer and resolver must be present to enable ephemeral 2643 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2644 if (DEBUG_EPHEMERAL) { 2645 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2646 + " installer:" + ephemeralInstallerComponent); 2647 } 2648 mEphemeralResolverComponent = ephemeralResolverComponent; 2649 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2650 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2651 mEphemeralResolverConnection = 2652 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2653 } else { 2654 if (DEBUG_EPHEMERAL) { 2655 final String missingComponent = 2656 (ephemeralResolverComponent == null) 2657 ? (ephemeralInstallerComponent == null) 2658 ? "resolver and installer" 2659 : "resolver" 2660 : "installer"; 2661 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2662 } 2663 mEphemeralResolverComponent = null; 2664 mEphemeralInstallerComponent = null; 2665 mEphemeralResolverConnection = null; 2666 } 2667 2668 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2669 } // synchronized (mPackages) 2670 } // synchronized (mInstallLock) 2671 2672 // Now after opening every single application zip, make sure they 2673 // are all flushed. Not really needed, but keeps things nice and 2674 // tidy. 2675 Runtime.getRuntime().gc(); 2676 2677 // The initial scanning above does many calls into installd while 2678 // holding the mPackages lock, but we're mostly interested in yelling 2679 // once we have a booted system. 2680 mInstaller.setWarnIfHeld(mPackages); 2681 2682 // Expose private service for system components to use. 2683 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2684 } 2685 2686 @Override 2687 public boolean isFirstBoot() { 2688 return !mRestoredSettings; 2689 } 2690 2691 @Override 2692 public boolean isOnlyCoreApps() { 2693 return mOnlyCore; 2694 } 2695 2696 @Override 2697 public boolean isUpgrade() { 2698 return mIsUpgrade; 2699 } 2700 2701 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2702 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2703 2704 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2705 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2706 UserHandle.USER_SYSTEM); 2707 if (matches.size() == 1) { 2708 return matches.get(0).getComponentInfo().packageName; 2709 } else { 2710 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2711 return null; 2712 } 2713 } 2714 2715 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2716 synchronized (mPackages) { 2717 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2718 if (libraryEntry == null) { 2719 throw new IllegalStateException("Missing required shared library:" + libraryName); 2720 } 2721 return libraryEntry.apk; 2722 } 2723 } 2724 2725 private @NonNull String getRequiredInstallerLPr() { 2726 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2727 intent.addCategory(Intent.CATEGORY_DEFAULT); 2728 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2729 2730 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2731 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2732 UserHandle.USER_SYSTEM); 2733 if (matches.size() == 1) { 2734 ResolveInfo resolveInfo = matches.get(0); 2735 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2736 throw new RuntimeException("The installer must be a privileged app"); 2737 } 2738 return matches.get(0).getComponentInfo().packageName; 2739 } else { 2740 throw new RuntimeException("There must be exactly one installer; found " + matches); 2741 } 2742 } 2743 2744 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2745 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2746 2747 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2748 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2749 UserHandle.USER_SYSTEM); 2750 ResolveInfo best = null; 2751 final int N = matches.size(); 2752 for (int i = 0; i < N; i++) { 2753 final ResolveInfo cur = matches.get(i); 2754 final String packageName = cur.getComponentInfo().packageName; 2755 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2756 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2757 continue; 2758 } 2759 2760 if (best == null || cur.priority > best.priority) { 2761 best = cur; 2762 } 2763 } 2764 2765 if (best != null) { 2766 return best.getComponentInfo().getComponentName(); 2767 } else { 2768 throw new RuntimeException("There must be at least one intent filter verifier"); 2769 } 2770 } 2771 2772 private @Nullable ComponentName getEphemeralResolverLPr() { 2773 final String[] packageArray = 2774 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2775 if (packageArray.length == 0) { 2776 if (DEBUG_EPHEMERAL) { 2777 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2778 } 2779 return null; 2780 } 2781 2782 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2783 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2784 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2785 UserHandle.USER_SYSTEM); 2786 2787 final int N = resolvers.size(); 2788 if (N == 0) { 2789 if (DEBUG_EPHEMERAL) { 2790 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2791 } 2792 return null; 2793 } 2794 2795 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2796 for (int i = 0; i < N; i++) { 2797 final ResolveInfo info = resolvers.get(i); 2798 2799 if (info.serviceInfo == null) { 2800 continue; 2801 } 2802 2803 final String packageName = info.serviceInfo.packageName; 2804 if (!possiblePackages.contains(packageName)) { 2805 if (DEBUG_EPHEMERAL) { 2806 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2807 + " pkg: " + packageName + ", info:" + info); 2808 } 2809 continue; 2810 } 2811 2812 if (DEBUG_EPHEMERAL) { 2813 Slog.v(TAG, "Ephemeral resolver found;" 2814 + " pkg: " + packageName + ", info:" + info); 2815 } 2816 return new ComponentName(packageName, info.serviceInfo.name); 2817 } 2818 if (DEBUG_EPHEMERAL) { 2819 Slog.v(TAG, "Ephemeral resolver NOT found"); 2820 } 2821 return null; 2822 } 2823 2824 private @Nullable ComponentName getEphemeralInstallerLPr() { 2825 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2826 intent.addCategory(Intent.CATEGORY_DEFAULT); 2827 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2828 2829 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2830 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2831 UserHandle.USER_SYSTEM); 2832 if (matches.size() == 0) { 2833 return null; 2834 } else if (matches.size() == 1) { 2835 return matches.get(0).getComponentInfo().getComponentName(); 2836 } else { 2837 throw new RuntimeException( 2838 "There must be at most one ephemeral installer; found " + matches); 2839 } 2840 } 2841 2842 private void primeDomainVerificationsLPw(int userId) { 2843 if (DEBUG_DOMAIN_VERIFICATION) { 2844 Slog.d(TAG, "Priming domain verifications in user " + userId); 2845 } 2846 2847 SystemConfig systemConfig = SystemConfig.getInstance(); 2848 ArraySet<String> packages = systemConfig.getLinkedApps(); 2849 ArraySet<String> domains = new ArraySet<String>(); 2850 2851 for (String packageName : packages) { 2852 PackageParser.Package pkg = mPackages.get(packageName); 2853 if (pkg != null) { 2854 if (!pkg.isSystemApp()) { 2855 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2856 continue; 2857 } 2858 2859 domains.clear(); 2860 for (PackageParser.Activity a : pkg.activities) { 2861 for (ActivityIntentInfo filter : a.intents) { 2862 if (hasValidDomains(filter)) { 2863 domains.addAll(filter.getHostsList()); 2864 } 2865 } 2866 } 2867 2868 if (domains.size() > 0) { 2869 if (DEBUG_DOMAIN_VERIFICATION) { 2870 Slog.v(TAG, " + " + packageName); 2871 } 2872 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2873 // state w.r.t. the formal app-linkage "no verification attempted" state; 2874 // and then 'always' in the per-user state actually used for intent resolution. 2875 final IntentFilterVerificationInfo ivi; 2876 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2877 new ArrayList<String>(domains)); 2878 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2879 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2880 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2881 } else { 2882 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2883 + "' does not handle web links"); 2884 } 2885 } else { 2886 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2887 } 2888 } 2889 2890 scheduleWritePackageRestrictionsLocked(userId); 2891 scheduleWriteSettingsLocked(); 2892 } 2893 2894 private void applyFactoryDefaultBrowserLPw(int userId) { 2895 // The default browser app's package name is stored in a string resource, 2896 // with a product-specific overlay used for vendor customization. 2897 String browserPkg = mContext.getResources().getString( 2898 com.android.internal.R.string.default_browser); 2899 if (!TextUtils.isEmpty(browserPkg)) { 2900 // non-empty string => required to be a known package 2901 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2902 if (ps == null) { 2903 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2904 browserPkg = null; 2905 } else { 2906 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2907 } 2908 } 2909 2910 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2911 // default. If there's more than one, just leave everything alone. 2912 if (browserPkg == null) { 2913 calculateDefaultBrowserLPw(userId); 2914 } 2915 } 2916 2917 private void calculateDefaultBrowserLPw(int userId) { 2918 List<String> allBrowsers = resolveAllBrowserApps(userId); 2919 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2920 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2921 } 2922 2923 private List<String> resolveAllBrowserApps(int userId) { 2924 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2925 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2926 PackageManager.MATCH_ALL, userId); 2927 2928 final int count = list.size(); 2929 List<String> result = new ArrayList<String>(count); 2930 for (int i=0; i<count; i++) { 2931 ResolveInfo info = list.get(i); 2932 if (info.activityInfo == null 2933 || !info.handleAllWebDataURI 2934 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2935 || result.contains(info.activityInfo.packageName)) { 2936 continue; 2937 } 2938 result.add(info.activityInfo.packageName); 2939 } 2940 2941 return result; 2942 } 2943 2944 private boolean packageIsBrowser(String packageName, int userId) { 2945 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2946 PackageManager.MATCH_ALL, userId); 2947 final int N = list.size(); 2948 for (int i = 0; i < N; i++) { 2949 ResolveInfo info = list.get(i); 2950 if (packageName.equals(info.activityInfo.packageName)) { 2951 return true; 2952 } 2953 } 2954 return false; 2955 } 2956 2957 private void checkDefaultBrowser() { 2958 final int myUserId = UserHandle.myUserId(); 2959 final String packageName = getDefaultBrowserPackageName(myUserId); 2960 if (packageName != null) { 2961 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2962 if (info == null) { 2963 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2964 synchronized (mPackages) { 2965 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2966 } 2967 } 2968 } 2969 } 2970 2971 @Override 2972 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2973 throws RemoteException { 2974 try { 2975 return super.onTransact(code, data, reply, flags); 2976 } catch (RuntimeException e) { 2977 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2978 Slog.wtf(TAG, "Package Manager Crash", e); 2979 } 2980 throw e; 2981 } 2982 } 2983 2984 void cleanupInstallFailedPackageLIF(PackageSetting ps) { 2985 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2986 2987 removeDataDirsLIF(ps.volumeUuid, ps.name); 2988 if (ps.codePath != null) { 2989 removeCodePathLI(ps.codePath); 2990 } 2991 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2992 if (ps.resourcePath.isDirectory()) { 2993 FileUtils.deleteContents(ps.resourcePath); 2994 } 2995 ps.resourcePath.delete(); 2996 } 2997 synchronized (mPackages) { 2998 mSettings.removePackageLPw(ps.name); 2999 } 3000 } 3001 3002 static int[] appendInts(int[] cur, int[] add) { 3003 if (add == null) return cur; 3004 if (cur == null) return add; 3005 final int N = add.length; 3006 for (int i=0; i<N; i++) { 3007 cur = appendInt(cur, add[i]); 3008 } 3009 return cur; 3010 } 3011 3012 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3013 if (!sUserManager.exists(userId)) return null; 3014 if (ps == null) { 3015 return null; 3016 } 3017 final PackageParser.Package p = ps.pkg; 3018 if (p == null) { 3019 return null; 3020 } 3021 3022 final PermissionsState permissionsState = ps.getPermissionsState(); 3023 3024 final int[] gids = permissionsState.computeGids(userId); 3025 final Set<String> permissions = permissionsState.getPermissions(userId); 3026 final PackageUserState state = ps.readUserState(userId); 3027 3028 return PackageParser.generatePackageInfo(p, gids, flags, 3029 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3030 } 3031 3032 @Override 3033 public void checkPackageStartable(String packageName, int userId) { 3034 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3035 3036 synchronized (mPackages) { 3037 final PackageSetting ps = mSettings.mPackages.get(packageName); 3038 if (ps == null) { 3039 throw new SecurityException("Package " + packageName + " was not found!"); 3040 } 3041 3042 if (!ps.getInstalled(userId)) { 3043 throw new SecurityException( 3044 "Package " + packageName + " was not installed for user " + userId + "!"); 3045 } 3046 3047 if (mSafeMode && !ps.isSystem()) { 3048 throw new SecurityException("Package " + packageName + " not a system app!"); 3049 } 3050 3051 if (mFrozenPackages.contains(packageName)) { 3052 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3053 } 3054 3055 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3056 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3057 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3058 } 3059 } 3060 } 3061 3062 @Override 3063 public boolean isPackageAvailable(String packageName, int userId) { 3064 if (!sUserManager.exists(userId)) return false; 3065 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3066 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3067 synchronized (mPackages) { 3068 PackageParser.Package p = mPackages.get(packageName); 3069 if (p != null) { 3070 final PackageSetting ps = (PackageSetting) p.mExtras; 3071 if (ps != null) { 3072 final PackageUserState state = ps.readUserState(userId); 3073 if (state != null) { 3074 return PackageParser.isAvailable(state); 3075 } 3076 } 3077 } 3078 } 3079 return false; 3080 } 3081 3082 @Override 3083 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return null; 3085 flags = updateFlagsForPackage(flags, userId, packageName); 3086 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3087 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3088 // reader 3089 synchronized (mPackages) { 3090 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3091 PackageParser.Package p = null; 3092 if (matchFactoryOnly) { 3093 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3094 if (ps != null) { 3095 return generatePackageInfo(ps, flags, userId); 3096 } 3097 } 3098 if (p == null) { 3099 p = mPackages.get(packageName); 3100 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3101 return null; 3102 } 3103 } 3104 if (DEBUG_PACKAGE_INFO) 3105 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3106 if (p != null) { 3107 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3108 } 3109 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3110 final PackageSetting ps = mSettings.mPackages.get(packageName); 3111 return generatePackageInfo(ps, flags, userId); 3112 } 3113 } 3114 return null; 3115 } 3116 3117 @Override 3118 public String[] currentToCanonicalPackageNames(String[] names) { 3119 String[] out = new String[names.length]; 3120 // reader 3121 synchronized (mPackages) { 3122 for (int i=names.length-1; i>=0; i--) { 3123 PackageSetting ps = mSettings.mPackages.get(names[i]); 3124 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3125 } 3126 } 3127 return out; 3128 } 3129 3130 @Override 3131 public String[] canonicalToCurrentPackageNames(String[] names) { 3132 String[] out = new String[names.length]; 3133 // reader 3134 synchronized (mPackages) { 3135 for (int i=names.length-1; i>=0; i--) { 3136 String cur = mSettings.mRenamedPackages.get(names[i]); 3137 out[i] = cur != null ? cur : names[i]; 3138 } 3139 } 3140 return out; 3141 } 3142 3143 @Override 3144 public int getPackageUid(String packageName, int flags, int userId) { 3145 if (!sUserManager.exists(userId)) return -1; 3146 flags = updateFlagsForPackage(flags, userId, packageName); 3147 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3148 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3149 3150 // reader 3151 synchronized (mPackages) { 3152 final PackageParser.Package p = mPackages.get(packageName); 3153 if (p != null && p.isMatch(flags)) { 3154 return UserHandle.getUid(userId, p.applicationInfo.uid); 3155 } 3156 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3157 final PackageSetting ps = mSettings.mPackages.get(packageName); 3158 if (ps != null && ps.isMatch(flags)) { 3159 return UserHandle.getUid(userId, ps.appId); 3160 } 3161 } 3162 } 3163 3164 return -1; 3165 } 3166 3167 @Override 3168 public int[] getPackageGids(String packageName, int flags, int userId) { 3169 if (!sUserManager.exists(userId)) return null; 3170 flags = updateFlagsForPackage(flags, userId, packageName); 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3172 false /* requireFullPermission */, false /* checkShell */, 3173 "getPackageGids"); 3174 3175 // reader 3176 synchronized (mPackages) { 3177 final PackageParser.Package p = mPackages.get(packageName); 3178 if (p != null && p.isMatch(flags)) { 3179 PackageSetting ps = (PackageSetting) p.mExtras; 3180 return ps.getPermissionsState().computeGids(userId); 3181 } 3182 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3183 final PackageSetting ps = mSettings.mPackages.get(packageName); 3184 if (ps != null && ps.isMatch(flags)) { 3185 return ps.getPermissionsState().computeGids(userId); 3186 } 3187 } 3188 } 3189 3190 return null; 3191 } 3192 3193 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3194 if (bp.perm != null) { 3195 return PackageParser.generatePermissionInfo(bp.perm, flags); 3196 } 3197 PermissionInfo pi = new PermissionInfo(); 3198 pi.name = bp.name; 3199 pi.packageName = bp.sourcePackage; 3200 pi.nonLocalizedLabel = bp.name; 3201 pi.protectionLevel = bp.protectionLevel; 3202 return pi; 3203 } 3204 3205 @Override 3206 public PermissionInfo getPermissionInfo(String name, int flags) { 3207 // reader 3208 synchronized (mPackages) { 3209 final BasePermission p = mSettings.mPermissions.get(name); 3210 if (p != null) { 3211 return generatePermissionInfo(p, flags); 3212 } 3213 return null; 3214 } 3215 } 3216 3217 @Override 3218 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3219 int flags) { 3220 // reader 3221 synchronized (mPackages) { 3222 if (group != null && !mPermissionGroups.containsKey(group)) { 3223 // This is thrown as NameNotFoundException 3224 return null; 3225 } 3226 3227 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3228 for (BasePermission p : mSettings.mPermissions.values()) { 3229 if (group == null) { 3230 if (p.perm == null || p.perm.info.group == null) { 3231 out.add(generatePermissionInfo(p, flags)); 3232 } 3233 } else { 3234 if (p.perm != null && group.equals(p.perm.info.group)) { 3235 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3236 } 3237 } 3238 } 3239 return new ParceledListSlice<>(out); 3240 } 3241 } 3242 3243 @Override 3244 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3245 // reader 3246 synchronized (mPackages) { 3247 return PackageParser.generatePermissionGroupInfo( 3248 mPermissionGroups.get(name), flags); 3249 } 3250 } 3251 3252 @Override 3253 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3254 // reader 3255 synchronized (mPackages) { 3256 final int N = mPermissionGroups.size(); 3257 ArrayList<PermissionGroupInfo> out 3258 = new ArrayList<PermissionGroupInfo>(N); 3259 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3260 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3261 } 3262 return new ParceledListSlice<>(out); 3263 } 3264 } 3265 3266 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3267 int userId) { 3268 if (!sUserManager.exists(userId)) return null; 3269 PackageSetting ps = mSettings.mPackages.get(packageName); 3270 if (ps != null) { 3271 if (ps.pkg == null) { 3272 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3273 if (pInfo != null) { 3274 return pInfo.applicationInfo; 3275 } 3276 return null; 3277 } 3278 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3279 ps.readUserState(userId), userId); 3280 } 3281 return null; 3282 } 3283 3284 @Override 3285 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3286 if (!sUserManager.exists(userId)) return null; 3287 flags = updateFlagsForApplication(flags, userId, packageName); 3288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3289 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3290 // writer 3291 synchronized (mPackages) { 3292 PackageParser.Package p = mPackages.get(packageName); 3293 if (DEBUG_PACKAGE_INFO) Log.v( 3294 TAG, "getApplicationInfo " + packageName 3295 + ": " + p); 3296 if (p != null) { 3297 PackageSetting ps = mSettings.mPackages.get(packageName); 3298 if (ps == null) return null; 3299 // Note: isEnabledLP() does not apply here - always return info 3300 return PackageParser.generateApplicationInfo( 3301 p, flags, ps.readUserState(userId), userId); 3302 } 3303 if ("android".equals(packageName)||"system".equals(packageName)) { 3304 return mAndroidApplication; 3305 } 3306 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3307 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3308 } 3309 } 3310 return null; 3311 } 3312 3313 @Override 3314 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3315 final IPackageDataObserver observer) { 3316 mContext.enforceCallingOrSelfPermission( 3317 android.Manifest.permission.CLEAR_APP_CACHE, null); 3318 // Queue up an async operation since clearing cache may take a little while. 3319 mHandler.post(new Runnable() { 3320 public void run() { 3321 mHandler.removeCallbacks(this); 3322 boolean success = true; 3323 synchronized (mInstallLock) { 3324 try { 3325 mInstaller.freeCache(volumeUuid, freeStorageSize); 3326 } catch (InstallerException e) { 3327 Slog.w(TAG, "Couldn't clear application caches: " + e); 3328 success = false; 3329 } 3330 } 3331 if (observer != null) { 3332 try { 3333 observer.onRemoveCompleted(null, success); 3334 } catch (RemoteException e) { 3335 Slog.w(TAG, "RemoveException when invoking call back"); 3336 } 3337 } 3338 } 3339 }); 3340 } 3341 3342 @Override 3343 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3344 final IntentSender pi) { 3345 mContext.enforceCallingOrSelfPermission( 3346 android.Manifest.permission.CLEAR_APP_CACHE, null); 3347 // Queue up an async operation since clearing cache may take a little while. 3348 mHandler.post(new Runnable() { 3349 public void run() { 3350 mHandler.removeCallbacks(this); 3351 boolean success = true; 3352 synchronized (mInstallLock) { 3353 try { 3354 mInstaller.freeCache(volumeUuid, freeStorageSize); 3355 } catch (InstallerException e) { 3356 Slog.w(TAG, "Couldn't clear application caches: " + e); 3357 success = false; 3358 } 3359 } 3360 if(pi != null) { 3361 try { 3362 // Callback via pending intent 3363 int code = success ? 1 : 0; 3364 pi.sendIntent(null, code, null, 3365 null, null); 3366 } catch (SendIntentException e1) { 3367 Slog.i(TAG, "Failed to send pending intent"); 3368 } 3369 } 3370 } 3371 }); 3372 } 3373 3374 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3375 synchronized (mInstallLock) { 3376 try { 3377 mInstaller.freeCache(volumeUuid, freeStorageSize); 3378 } catch (InstallerException e) { 3379 throw new IOException("Failed to free enough space", e); 3380 } 3381 } 3382 } 3383 3384 /** 3385 * Return if the user key is currently unlocked. 3386 */ 3387 private boolean isUserKeyUnlocked(int userId) { 3388 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3389 final IMountService mount = IMountService.Stub 3390 .asInterface(ServiceManager.getService("mount")); 3391 if (mount == null) { 3392 Slog.w(TAG, "Early during boot, assuming locked"); 3393 return false; 3394 } 3395 final long token = Binder.clearCallingIdentity(); 3396 try { 3397 return mount.isUserKeyUnlocked(userId); 3398 } catch (RemoteException e) { 3399 throw e.rethrowAsRuntimeException(); 3400 } finally { 3401 Binder.restoreCallingIdentity(token); 3402 } 3403 } else { 3404 return true; 3405 } 3406 } 3407 3408 /** 3409 * Update given flags based on encryption status of current user. 3410 */ 3411 private int updateFlags(int flags, int userId) { 3412 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3413 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3414 // Caller expressed an explicit opinion about what encryption 3415 // aware/unaware components they want to see, so fall through and 3416 // give them what they want 3417 } else { 3418 // Caller expressed no opinion, so match based on user state 3419 if (isUserKeyUnlocked(userId)) { 3420 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3421 } else { 3422 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3423 } 3424 } 3425 return flags; 3426 } 3427 3428 /** 3429 * Update given flags when being used to request {@link PackageInfo}. 3430 */ 3431 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3432 boolean triaged = true; 3433 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3434 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3435 // Caller is asking for component details, so they'd better be 3436 // asking for specific encryption matching behavior, or be triaged 3437 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3438 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3439 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3440 triaged = false; 3441 } 3442 } 3443 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3444 | PackageManager.MATCH_SYSTEM_ONLY 3445 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3446 triaged = false; 3447 } 3448 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3449 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3450 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3451 } 3452 return updateFlags(flags, userId); 3453 } 3454 3455 /** 3456 * Update given flags when being used to request {@link ApplicationInfo}. 3457 */ 3458 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3459 return updateFlagsForPackage(flags, userId, cookie); 3460 } 3461 3462 /** 3463 * Update given flags when being used to request {@link ComponentInfo}. 3464 */ 3465 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3466 if (cookie instanceof Intent) { 3467 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3468 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3469 } 3470 } 3471 3472 boolean triaged = true; 3473 // Caller is asking for component details, so they'd better be 3474 // asking for specific encryption matching behavior, or be triaged 3475 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3476 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3477 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3478 triaged = false; 3479 } 3480 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3481 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3482 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3483 } 3484 3485 return updateFlags(flags, userId); 3486 } 3487 3488 /** 3489 * Update given flags when being used to request {@link ResolveInfo}. 3490 */ 3491 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3492 // Safe mode means we shouldn't match any third-party components 3493 if (mSafeMode) { 3494 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3495 } 3496 3497 return updateFlagsForComponent(flags, userId, cookie); 3498 } 3499 3500 @Override 3501 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3502 if (!sUserManager.exists(userId)) return null; 3503 flags = updateFlagsForComponent(flags, userId, component); 3504 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3505 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3506 synchronized (mPackages) { 3507 PackageParser.Activity a = mActivities.mActivities.get(component); 3508 3509 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3510 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3511 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3512 if (ps == null) return null; 3513 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3514 userId); 3515 } 3516 if (mResolveComponentName.equals(component)) { 3517 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3518 new PackageUserState(), userId); 3519 } 3520 } 3521 return null; 3522 } 3523 3524 @Override 3525 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3526 String resolvedType) { 3527 synchronized (mPackages) { 3528 if (component.equals(mResolveComponentName)) { 3529 // The resolver supports EVERYTHING! 3530 return true; 3531 } 3532 PackageParser.Activity a = mActivities.mActivities.get(component); 3533 if (a == null) { 3534 return false; 3535 } 3536 for (int i=0; i<a.intents.size(); i++) { 3537 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3538 intent.getData(), intent.getCategories(), TAG) >= 0) { 3539 return true; 3540 } 3541 } 3542 return false; 3543 } 3544 } 3545 3546 @Override 3547 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3548 if (!sUserManager.exists(userId)) return null; 3549 flags = updateFlagsForComponent(flags, userId, component); 3550 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3551 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3552 synchronized (mPackages) { 3553 PackageParser.Activity a = mReceivers.mActivities.get(component); 3554 if (DEBUG_PACKAGE_INFO) Log.v( 3555 TAG, "getReceiverInfo " + component + ": " + a); 3556 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3557 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3558 if (ps == null) return null; 3559 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3560 userId); 3561 } 3562 } 3563 return null; 3564 } 3565 3566 @Override 3567 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3568 if (!sUserManager.exists(userId)) return null; 3569 flags = updateFlagsForComponent(flags, userId, component); 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3571 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3572 synchronized (mPackages) { 3573 PackageParser.Service s = mServices.mServices.get(component); 3574 if (DEBUG_PACKAGE_INFO) Log.v( 3575 TAG, "getServiceInfo " + component + ": " + s); 3576 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3577 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3578 if (ps == null) return null; 3579 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3580 userId); 3581 } 3582 } 3583 return null; 3584 } 3585 3586 @Override 3587 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3588 if (!sUserManager.exists(userId)) return null; 3589 flags = updateFlagsForComponent(flags, userId, component); 3590 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3591 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3592 synchronized (mPackages) { 3593 PackageParser.Provider p = mProviders.mProviders.get(component); 3594 if (DEBUG_PACKAGE_INFO) Log.v( 3595 TAG, "getProviderInfo " + component + ": " + p); 3596 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3597 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3598 if (ps == null) return null; 3599 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3600 userId); 3601 } 3602 } 3603 return null; 3604 } 3605 3606 @Override 3607 public String[] getSystemSharedLibraryNames() { 3608 Set<String> libSet; 3609 synchronized (mPackages) { 3610 libSet = mSharedLibraries.keySet(); 3611 int size = libSet.size(); 3612 if (size > 0) { 3613 String[] libs = new String[size]; 3614 libSet.toArray(libs); 3615 return libs; 3616 } 3617 } 3618 return null; 3619 } 3620 3621 @Override 3622 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3623 synchronized (mPackages) { 3624 return mServicesSystemSharedLibraryPackageName; 3625 } 3626 } 3627 3628 @Override 3629 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3630 synchronized (mPackages) { 3631 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3632 3633 final FeatureInfo fi = new FeatureInfo(); 3634 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3635 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3636 res.add(fi); 3637 3638 return new ParceledListSlice<>(res); 3639 } 3640 } 3641 3642 @Override 3643 public boolean hasSystemFeature(String name, int version) { 3644 synchronized (mPackages) { 3645 final FeatureInfo feat = mAvailableFeatures.get(name); 3646 if (feat == null) { 3647 return false; 3648 } else { 3649 return feat.version >= version; 3650 } 3651 } 3652 } 3653 3654 @Override 3655 public int checkPermission(String permName, String pkgName, int userId) { 3656 if (!sUserManager.exists(userId)) { 3657 return PackageManager.PERMISSION_DENIED; 3658 } 3659 3660 synchronized (mPackages) { 3661 final PackageParser.Package p = mPackages.get(pkgName); 3662 if (p != null && p.mExtras != null) { 3663 final PackageSetting ps = (PackageSetting) p.mExtras; 3664 final PermissionsState permissionsState = ps.getPermissionsState(); 3665 if (permissionsState.hasPermission(permName, userId)) { 3666 return PackageManager.PERMISSION_GRANTED; 3667 } 3668 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3669 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3670 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3671 return PackageManager.PERMISSION_GRANTED; 3672 } 3673 } 3674 } 3675 3676 return PackageManager.PERMISSION_DENIED; 3677 } 3678 3679 @Override 3680 public int checkUidPermission(String permName, int uid) { 3681 final int userId = UserHandle.getUserId(uid); 3682 3683 if (!sUserManager.exists(userId)) { 3684 return PackageManager.PERMISSION_DENIED; 3685 } 3686 3687 synchronized (mPackages) { 3688 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3689 if (obj != null) { 3690 final SettingBase ps = (SettingBase) obj; 3691 final PermissionsState permissionsState = ps.getPermissionsState(); 3692 if (permissionsState.hasPermission(permName, userId)) { 3693 return PackageManager.PERMISSION_GRANTED; 3694 } 3695 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3696 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3697 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3698 return PackageManager.PERMISSION_GRANTED; 3699 } 3700 } else { 3701 ArraySet<String> perms = mSystemPermissions.get(uid); 3702 if (perms != null) { 3703 if (perms.contains(permName)) { 3704 return PackageManager.PERMISSION_GRANTED; 3705 } 3706 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3707 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3708 return PackageManager.PERMISSION_GRANTED; 3709 } 3710 } 3711 } 3712 } 3713 3714 return PackageManager.PERMISSION_DENIED; 3715 } 3716 3717 @Override 3718 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3719 if (UserHandle.getCallingUserId() != userId) { 3720 mContext.enforceCallingPermission( 3721 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3722 "isPermissionRevokedByPolicy for user " + userId); 3723 } 3724 3725 if (checkPermission(permission, packageName, userId) 3726 == PackageManager.PERMISSION_GRANTED) { 3727 return false; 3728 } 3729 3730 final long identity = Binder.clearCallingIdentity(); 3731 try { 3732 final int flags = getPermissionFlags(permission, packageName, userId); 3733 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3734 } finally { 3735 Binder.restoreCallingIdentity(identity); 3736 } 3737 } 3738 3739 @Override 3740 public String getPermissionControllerPackageName() { 3741 synchronized (mPackages) { 3742 return mRequiredInstallerPackage; 3743 } 3744 } 3745 3746 /** 3747 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3748 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3749 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3750 * @param message the message to log on security exception 3751 */ 3752 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3753 boolean checkShell, String message) { 3754 if (userId < 0) { 3755 throw new IllegalArgumentException("Invalid userId " + userId); 3756 } 3757 if (checkShell) { 3758 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3759 } 3760 if (userId == UserHandle.getUserId(callingUid)) return; 3761 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3762 if (requireFullPermission) { 3763 mContext.enforceCallingOrSelfPermission( 3764 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3765 } else { 3766 try { 3767 mContext.enforceCallingOrSelfPermission( 3768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3769 } catch (SecurityException se) { 3770 mContext.enforceCallingOrSelfPermission( 3771 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3772 } 3773 } 3774 } 3775 } 3776 3777 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3778 if (callingUid == Process.SHELL_UID) { 3779 if (userHandle >= 0 3780 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3781 throw new SecurityException("Shell does not have permission to access user " 3782 + userHandle); 3783 } else if (userHandle < 0) { 3784 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3785 + Debug.getCallers(3)); 3786 } 3787 } 3788 } 3789 3790 private BasePermission findPermissionTreeLP(String permName) { 3791 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3792 if (permName.startsWith(bp.name) && 3793 permName.length() > bp.name.length() && 3794 permName.charAt(bp.name.length()) == '.') { 3795 return bp; 3796 } 3797 } 3798 return null; 3799 } 3800 3801 private BasePermission checkPermissionTreeLP(String permName) { 3802 if (permName != null) { 3803 BasePermission bp = findPermissionTreeLP(permName); 3804 if (bp != null) { 3805 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3806 return bp; 3807 } 3808 throw new SecurityException("Calling uid " 3809 + Binder.getCallingUid() 3810 + " is not allowed to add to permission tree " 3811 + bp.name + " owned by uid " + bp.uid); 3812 } 3813 } 3814 throw new SecurityException("No permission tree found for " + permName); 3815 } 3816 3817 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3818 if (s1 == null) { 3819 return s2 == null; 3820 } 3821 if (s2 == null) { 3822 return false; 3823 } 3824 if (s1.getClass() != s2.getClass()) { 3825 return false; 3826 } 3827 return s1.equals(s2); 3828 } 3829 3830 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3831 if (pi1.icon != pi2.icon) return false; 3832 if (pi1.logo != pi2.logo) return false; 3833 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3834 if (!compareStrings(pi1.name, pi2.name)) return false; 3835 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3836 // We'll take care of setting this one. 3837 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3838 // These are not currently stored in settings. 3839 //if (!compareStrings(pi1.group, pi2.group)) return false; 3840 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3841 //if (pi1.labelRes != pi2.labelRes) return false; 3842 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3843 return true; 3844 } 3845 3846 int permissionInfoFootprint(PermissionInfo info) { 3847 int size = info.name.length(); 3848 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3849 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3850 return size; 3851 } 3852 3853 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3854 int size = 0; 3855 for (BasePermission perm : mSettings.mPermissions.values()) { 3856 if (perm.uid == tree.uid) { 3857 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3858 } 3859 } 3860 return size; 3861 } 3862 3863 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3864 // We calculate the max size of permissions defined by this uid and throw 3865 // if that plus the size of 'info' would exceed our stated maximum. 3866 if (tree.uid != Process.SYSTEM_UID) { 3867 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3868 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3869 throw new SecurityException("Permission tree size cap exceeded"); 3870 } 3871 } 3872 } 3873 3874 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3875 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3876 throw new SecurityException("Label must be specified in permission"); 3877 } 3878 BasePermission tree = checkPermissionTreeLP(info.name); 3879 BasePermission bp = mSettings.mPermissions.get(info.name); 3880 boolean added = bp == null; 3881 boolean changed = true; 3882 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3883 if (added) { 3884 enforcePermissionCapLocked(info, tree); 3885 bp = new BasePermission(info.name, tree.sourcePackage, 3886 BasePermission.TYPE_DYNAMIC); 3887 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3888 throw new SecurityException( 3889 "Not allowed to modify non-dynamic permission " 3890 + info.name); 3891 } else { 3892 if (bp.protectionLevel == fixedLevel 3893 && bp.perm.owner.equals(tree.perm.owner) 3894 && bp.uid == tree.uid 3895 && comparePermissionInfos(bp.perm.info, info)) { 3896 changed = false; 3897 } 3898 } 3899 bp.protectionLevel = fixedLevel; 3900 info = new PermissionInfo(info); 3901 info.protectionLevel = fixedLevel; 3902 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3903 bp.perm.info.packageName = tree.perm.info.packageName; 3904 bp.uid = tree.uid; 3905 if (added) { 3906 mSettings.mPermissions.put(info.name, bp); 3907 } 3908 if (changed) { 3909 if (!async) { 3910 mSettings.writeLPr(); 3911 } else { 3912 scheduleWriteSettingsLocked(); 3913 } 3914 } 3915 return added; 3916 } 3917 3918 @Override 3919 public boolean addPermission(PermissionInfo info) { 3920 synchronized (mPackages) { 3921 return addPermissionLocked(info, false); 3922 } 3923 } 3924 3925 @Override 3926 public boolean addPermissionAsync(PermissionInfo info) { 3927 synchronized (mPackages) { 3928 return addPermissionLocked(info, true); 3929 } 3930 } 3931 3932 @Override 3933 public void removePermission(String name) { 3934 synchronized (mPackages) { 3935 checkPermissionTreeLP(name); 3936 BasePermission bp = mSettings.mPermissions.get(name); 3937 if (bp != null) { 3938 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3939 throw new SecurityException( 3940 "Not allowed to modify non-dynamic permission " 3941 + name); 3942 } 3943 mSettings.mPermissions.remove(name); 3944 mSettings.writeLPr(); 3945 } 3946 } 3947 } 3948 3949 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3950 BasePermission bp) { 3951 int index = pkg.requestedPermissions.indexOf(bp.name); 3952 if (index == -1) { 3953 throw new SecurityException("Package " + pkg.packageName 3954 + " has not requested permission " + bp.name); 3955 } 3956 if (!bp.isRuntime() && !bp.isDevelopment()) { 3957 throw new SecurityException("Permission " + bp.name 3958 + " is not a changeable permission type"); 3959 } 3960 } 3961 3962 @Override 3963 public void grantRuntimePermission(String packageName, String name, final int userId) { 3964 if (!sUserManager.exists(userId)) { 3965 Log.e(TAG, "No such user:" + userId); 3966 return; 3967 } 3968 3969 mContext.enforceCallingOrSelfPermission( 3970 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3971 "grantRuntimePermission"); 3972 3973 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3974 true /* requireFullPermission */, true /* checkShell */, 3975 "grantRuntimePermission"); 3976 3977 final int uid; 3978 final SettingBase sb; 3979 3980 synchronized (mPackages) { 3981 final PackageParser.Package pkg = mPackages.get(packageName); 3982 if (pkg == null) { 3983 throw new IllegalArgumentException("Unknown package: " + packageName); 3984 } 3985 3986 final BasePermission bp = mSettings.mPermissions.get(name); 3987 if (bp == null) { 3988 throw new IllegalArgumentException("Unknown permission: " + name); 3989 } 3990 3991 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3992 3993 // If a permission review is required for legacy apps we represent 3994 // their permissions as always granted runtime ones since we need 3995 // to keep the review required permission flag per user while an 3996 // install permission's state is shared across all users. 3997 if (Build.PERMISSIONS_REVIEW_REQUIRED 3998 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3999 && bp.isRuntime()) { 4000 return; 4001 } 4002 4003 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4004 sb = (SettingBase) pkg.mExtras; 4005 if (sb == null) { 4006 throw new IllegalArgumentException("Unknown package: " + packageName); 4007 } 4008 4009 final PermissionsState permissionsState = sb.getPermissionsState(); 4010 4011 final int flags = permissionsState.getPermissionFlags(name, userId); 4012 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4013 throw new SecurityException("Cannot grant system fixed permission " 4014 + name + " for package " + packageName); 4015 } 4016 4017 if (bp.isDevelopment()) { 4018 // Development permissions must be handled specially, since they are not 4019 // normal runtime permissions. For now they apply to all users. 4020 if (permissionsState.grantInstallPermission(bp) != 4021 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4022 scheduleWriteSettingsLocked(); 4023 } 4024 return; 4025 } 4026 4027 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4028 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4029 return; 4030 } 4031 4032 final int result = permissionsState.grantRuntimePermission(bp, userId); 4033 switch (result) { 4034 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4035 return; 4036 } 4037 4038 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4039 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4040 mHandler.post(new Runnable() { 4041 @Override 4042 public void run() { 4043 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4044 } 4045 }); 4046 } 4047 break; 4048 } 4049 4050 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4051 4052 // Not critical if that is lost - app has to request again. 4053 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4054 } 4055 4056 // Only need to do this if user is initialized. Otherwise it's a new user 4057 // and there are no processes running as the user yet and there's no need 4058 // to make an expensive call to remount processes for the changed permissions. 4059 if (READ_EXTERNAL_STORAGE.equals(name) 4060 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4061 final long token = Binder.clearCallingIdentity(); 4062 try { 4063 if (sUserManager.isInitialized(userId)) { 4064 MountServiceInternal mountServiceInternal = LocalServices.getService( 4065 MountServiceInternal.class); 4066 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4067 } 4068 } finally { 4069 Binder.restoreCallingIdentity(token); 4070 } 4071 } 4072 } 4073 4074 @Override 4075 public void revokeRuntimePermission(String packageName, String name, int userId) { 4076 if (!sUserManager.exists(userId)) { 4077 Log.e(TAG, "No such user:" + userId); 4078 return; 4079 } 4080 4081 mContext.enforceCallingOrSelfPermission( 4082 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4083 "revokeRuntimePermission"); 4084 4085 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4086 true /* requireFullPermission */, true /* checkShell */, 4087 "revokeRuntimePermission"); 4088 4089 final int appId; 4090 4091 synchronized (mPackages) { 4092 final PackageParser.Package pkg = mPackages.get(packageName); 4093 if (pkg == null) { 4094 throw new IllegalArgumentException("Unknown package: " + packageName); 4095 } 4096 4097 final BasePermission bp = mSettings.mPermissions.get(name); 4098 if (bp == null) { 4099 throw new IllegalArgumentException("Unknown permission: " + name); 4100 } 4101 4102 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4103 4104 // If a permission review is required for legacy apps we represent 4105 // their permissions as always granted runtime ones since we need 4106 // to keep the review required permission flag per user while an 4107 // install permission's state is shared across all users. 4108 if (Build.PERMISSIONS_REVIEW_REQUIRED 4109 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4110 && bp.isRuntime()) { 4111 return; 4112 } 4113 4114 SettingBase sb = (SettingBase) pkg.mExtras; 4115 if (sb == null) { 4116 throw new IllegalArgumentException("Unknown package: " + packageName); 4117 } 4118 4119 final PermissionsState permissionsState = sb.getPermissionsState(); 4120 4121 final int flags = permissionsState.getPermissionFlags(name, userId); 4122 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4123 throw new SecurityException("Cannot revoke system fixed permission " 4124 + name + " for package " + packageName); 4125 } 4126 4127 if (bp.isDevelopment()) { 4128 // Development permissions must be handled specially, since they are not 4129 // normal runtime permissions. For now they apply to all users. 4130 if (permissionsState.revokeInstallPermission(bp) != 4131 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4132 scheduleWriteSettingsLocked(); 4133 } 4134 return; 4135 } 4136 4137 if (permissionsState.revokeRuntimePermission(bp, userId) == 4138 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4139 return; 4140 } 4141 4142 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4143 4144 // Critical, after this call app should never have the permission. 4145 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4146 4147 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4148 } 4149 4150 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4151 } 4152 4153 @Override 4154 public void resetRuntimePermissions() { 4155 mContext.enforceCallingOrSelfPermission( 4156 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4157 "revokeRuntimePermission"); 4158 4159 int callingUid = Binder.getCallingUid(); 4160 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4161 mContext.enforceCallingOrSelfPermission( 4162 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4163 "resetRuntimePermissions"); 4164 } 4165 4166 synchronized (mPackages) { 4167 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4168 for (int userId : UserManagerService.getInstance().getUserIds()) { 4169 final int packageCount = mPackages.size(); 4170 for (int i = 0; i < packageCount; i++) { 4171 PackageParser.Package pkg = mPackages.valueAt(i); 4172 if (!(pkg.mExtras instanceof PackageSetting)) { 4173 continue; 4174 } 4175 PackageSetting ps = (PackageSetting) pkg.mExtras; 4176 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4177 } 4178 } 4179 } 4180 } 4181 4182 @Override 4183 public int getPermissionFlags(String name, String packageName, int userId) { 4184 if (!sUserManager.exists(userId)) { 4185 return 0; 4186 } 4187 4188 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4189 4190 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4191 true /* requireFullPermission */, false /* checkShell */, 4192 "getPermissionFlags"); 4193 4194 synchronized (mPackages) { 4195 final PackageParser.Package pkg = mPackages.get(packageName); 4196 if (pkg == null) { 4197 throw new IllegalArgumentException("Unknown package: " + packageName); 4198 } 4199 4200 final BasePermission bp = mSettings.mPermissions.get(name); 4201 if (bp == null) { 4202 throw new IllegalArgumentException("Unknown permission: " + name); 4203 } 4204 4205 SettingBase sb = (SettingBase) pkg.mExtras; 4206 if (sb == null) { 4207 throw new IllegalArgumentException("Unknown package: " + packageName); 4208 } 4209 4210 PermissionsState permissionsState = sb.getPermissionsState(); 4211 return permissionsState.getPermissionFlags(name, userId); 4212 } 4213 } 4214 4215 @Override 4216 public void updatePermissionFlags(String name, String packageName, int flagMask, 4217 int flagValues, int userId) { 4218 if (!sUserManager.exists(userId)) { 4219 return; 4220 } 4221 4222 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4223 4224 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4225 true /* requireFullPermission */, true /* checkShell */, 4226 "updatePermissionFlags"); 4227 4228 // Only the system can change these flags and nothing else. 4229 if (getCallingUid() != Process.SYSTEM_UID) { 4230 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4231 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4232 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4233 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4234 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4235 } 4236 4237 synchronized (mPackages) { 4238 final PackageParser.Package pkg = mPackages.get(packageName); 4239 if (pkg == null) { 4240 throw new IllegalArgumentException("Unknown package: " + packageName); 4241 } 4242 4243 final BasePermission bp = mSettings.mPermissions.get(name); 4244 if (bp == null) { 4245 throw new IllegalArgumentException("Unknown permission: " + name); 4246 } 4247 4248 SettingBase sb = (SettingBase) pkg.mExtras; 4249 if (sb == null) { 4250 throw new IllegalArgumentException("Unknown package: " + packageName); 4251 } 4252 4253 PermissionsState permissionsState = sb.getPermissionsState(); 4254 4255 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4256 4257 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4258 // Install and runtime permissions are stored in different places, 4259 // so figure out what permission changed and persist the change. 4260 if (permissionsState.getInstallPermissionState(name) != null) { 4261 scheduleWriteSettingsLocked(); 4262 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4263 || hadState) { 4264 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4265 } 4266 } 4267 } 4268 } 4269 4270 /** 4271 * Update the permission flags for all packages and runtime permissions of a user in order 4272 * to allow device or profile owner to remove POLICY_FIXED. 4273 */ 4274 @Override 4275 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4276 if (!sUserManager.exists(userId)) { 4277 return; 4278 } 4279 4280 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4281 4282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4283 true /* requireFullPermission */, true /* checkShell */, 4284 "updatePermissionFlagsForAllApps"); 4285 4286 // Only the system can change system fixed flags. 4287 if (getCallingUid() != Process.SYSTEM_UID) { 4288 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4289 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4290 } 4291 4292 synchronized (mPackages) { 4293 boolean changed = false; 4294 final int packageCount = mPackages.size(); 4295 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4296 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4297 SettingBase sb = (SettingBase) pkg.mExtras; 4298 if (sb == null) { 4299 continue; 4300 } 4301 PermissionsState permissionsState = sb.getPermissionsState(); 4302 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4303 userId, flagMask, flagValues); 4304 } 4305 if (changed) { 4306 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4307 } 4308 } 4309 } 4310 4311 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4312 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4313 != PackageManager.PERMISSION_GRANTED 4314 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4315 != PackageManager.PERMISSION_GRANTED) { 4316 throw new SecurityException(message + " requires " 4317 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4318 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4319 } 4320 } 4321 4322 @Override 4323 public boolean shouldShowRequestPermissionRationale(String permissionName, 4324 String packageName, int userId) { 4325 if (UserHandle.getCallingUserId() != userId) { 4326 mContext.enforceCallingPermission( 4327 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4328 "canShowRequestPermissionRationale for user " + userId); 4329 } 4330 4331 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4332 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4333 return false; 4334 } 4335 4336 if (checkPermission(permissionName, packageName, userId) 4337 == PackageManager.PERMISSION_GRANTED) { 4338 return false; 4339 } 4340 4341 final int flags; 4342 4343 final long identity = Binder.clearCallingIdentity(); 4344 try { 4345 flags = getPermissionFlags(permissionName, 4346 packageName, userId); 4347 } finally { 4348 Binder.restoreCallingIdentity(identity); 4349 } 4350 4351 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4352 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4353 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4354 4355 if ((flags & fixedFlags) != 0) { 4356 return false; 4357 } 4358 4359 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4360 } 4361 4362 @Override 4363 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4364 mContext.enforceCallingOrSelfPermission( 4365 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4366 "addOnPermissionsChangeListener"); 4367 4368 synchronized (mPackages) { 4369 mOnPermissionChangeListeners.addListenerLocked(listener); 4370 } 4371 } 4372 4373 @Override 4374 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4375 synchronized (mPackages) { 4376 mOnPermissionChangeListeners.removeListenerLocked(listener); 4377 } 4378 } 4379 4380 @Override 4381 public boolean isProtectedBroadcast(String actionName) { 4382 synchronized (mPackages) { 4383 if (mProtectedBroadcasts.contains(actionName)) { 4384 return true; 4385 } else if (actionName != null) { 4386 // TODO: remove these terrible hacks 4387 if (actionName.startsWith("android.net.netmon.lingerExpired") 4388 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4389 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4390 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4391 return true; 4392 } 4393 } 4394 } 4395 return false; 4396 } 4397 4398 @Override 4399 public int checkSignatures(String pkg1, String pkg2) { 4400 synchronized (mPackages) { 4401 final PackageParser.Package p1 = mPackages.get(pkg1); 4402 final PackageParser.Package p2 = mPackages.get(pkg2); 4403 if (p1 == null || p1.mExtras == null 4404 || p2 == null || p2.mExtras == null) { 4405 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4406 } 4407 return compareSignatures(p1.mSignatures, p2.mSignatures); 4408 } 4409 } 4410 4411 @Override 4412 public int checkUidSignatures(int uid1, int uid2) { 4413 // Map to base uids. 4414 uid1 = UserHandle.getAppId(uid1); 4415 uid2 = UserHandle.getAppId(uid2); 4416 // reader 4417 synchronized (mPackages) { 4418 Signature[] s1; 4419 Signature[] s2; 4420 Object obj = mSettings.getUserIdLPr(uid1); 4421 if (obj != null) { 4422 if (obj instanceof SharedUserSetting) { 4423 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4424 } else if (obj instanceof PackageSetting) { 4425 s1 = ((PackageSetting)obj).signatures.mSignatures; 4426 } else { 4427 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4428 } 4429 } else { 4430 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4431 } 4432 obj = mSettings.getUserIdLPr(uid2); 4433 if (obj != null) { 4434 if (obj instanceof SharedUserSetting) { 4435 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4436 } else if (obj instanceof PackageSetting) { 4437 s2 = ((PackageSetting)obj).signatures.mSignatures; 4438 } else { 4439 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4440 } 4441 } else { 4442 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4443 } 4444 return compareSignatures(s1, s2); 4445 } 4446 } 4447 4448 /** 4449 * This method should typically only be used when granting or revoking 4450 * permissions, since the app may immediately restart after this call. 4451 * <p> 4452 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4453 * guard your work against the app being relaunched. 4454 */ 4455 private void killUid(int appId, int userId, String reason) { 4456 final long identity = Binder.clearCallingIdentity(); 4457 try { 4458 IActivityManager am = ActivityManagerNative.getDefault(); 4459 if (am != null) { 4460 try { 4461 am.killUid(appId, userId, reason); 4462 } catch (RemoteException e) { 4463 /* ignore - same process */ 4464 } 4465 } 4466 } finally { 4467 Binder.restoreCallingIdentity(identity); 4468 } 4469 } 4470 4471 /** 4472 * Compares two sets of signatures. Returns: 4473 * <br /> 4474 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4475 * <br /> 4476 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4477 * <br /> 4478 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4479 * <br /> 4480 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4481 * <br /> 4482 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4483 */ 4484 static int compareSignatures(Signature[] s1, Signature[] s2) { 4485 if (s1 == null) { 4486 return s2 == null 4487 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4488 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4489 } 4490 4491 if (s2 == null) { 4492 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4493 } 4494 4495 if (s1.length != s2.length) { 4496 return PackageManager.SIGNATURE_NO_MATCH; 4497 } 4498 4499 // Since both signature sets are of size 1, we can compare without HashSets. 4500 if (s1.length == 1) { 4501 return s1[0].equals(s2[0]) ? 4502 PackageManager.SIGNATURE_MATCH : 4503 PackageManager.SIGNATURE_NO_MATCH; 4504 } 4505 4506 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4507 for (Signature sig : s1) { 4508 set1.add(sig); 4509 } 4510 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4511 for (Signature sig : s2) { 4512 set2.add(sig); 4513 } 4514 // Make sure s2 contains all signatures in s1. 4515 if (set1.equals(set2)) { 4516 return PackageManager.SIGNATURE_MATCH; 4517 } 4518 return PackageManager.SIGNATURE_NO_MATCH; 4519 } 4520 4521 /** 4522 * If the database version for this type of package (internal storage or 4523 * external storage) is less than the version where package signatures 4524 * were updated, return true. 4525 */ 4526 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4527 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4528 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4529 } 4530 4531 /** 4532 * Used for backward compatibility to make sure any packages with 4533 * certificate chains get upgraded to the new style. {@code existingSigs} 4534 * will be in the old format (since they were stored on disk from before the 4535 * system upgrade) and {@code scannedSigs} will be in the newer format. 4536 */ 4537 private int compareSignaturesCompat(PackageSignatures existingSigs, 4538 PackageParser.Package scannedPkg) { 4539 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4540 return PackageManager.SIGNATURE_NO_MATCH; 4541 } 4542 4543 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4544 for (Signature sig : existingSigs.mSignatures) { 4545 existingSet.add(sig); 4546 } 4547 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4548 for (Signature sig : scannedPkg.mSignatures) { 4549 try { 4550 Signature[] chainSignatures = sig.getChainSignatures(); 4551 for (Signature chainSig : chainSignatures) { 4552 scannedCompatSet.add(chainSig); 4553 } 4554 } catch (CertificateEncodingException e) { 4555 scannedCompatSet.add(sig); 4556 } 4557 } 4558 /* 4559 * Make sure the expanded scanned set contains all signatures in the 4560 * existing one. 4561 */ 4562 if (scannedCompatSet.equals(existingSet)) { 4563 // Migrate the old signatures to the new scheme. 4564 existingSigs.assignSignatures(scannedPkg.mSignatures); 4565 // The new KeySets will be re-added later in the scanning process. 4566 synchronized (mPackages) { 4567 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4568 } 4569 return PackageManager.SIGNATURE_MATCH; 4570 } 4571 return PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4575 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4576 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4577 } 4578 4579 private int compareSignaturesRecover(PackageSignatures existingSigs, 4580 PackageParser.Package scannedPkg) { 4581 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4582 return PackageManager.SIGNATURE_NO_MATCH; 4583 } 4584 4585 String msg = null; 4586 try { 4587 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4588 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4589 + scannedPkg.packageName); 4590 return PackageManager.SIGNATURE_MATCH; 4591 } 4592 } catch (CertificateException e) { 4593 msg = e.getMessage(); 4594 } 4595 4596 logCriticalInfo(Log.INFO, 4597 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4598 return PackageManager.SIGNATURE_NO_MATCH; 4599 } 4600 4601 @Override 4602 public List<String> getAllPackages() { 4603 synchronized (mPackages) { 4604 return new ArrayList<String>(mPackages.keySet()); 4605 } 4606 } 4607 4608 @Override 4609 public String[] getPackagesForUid(int uid) { 4610 uid = UserHandle.getAppId(uid); 4611 // reader 4612 synchronized (mPackages) { 4613 Object obj = mSettings.getUserIdLPr(uid); 4614 if (obj instanceof SharedUserSetting) { 4615 final SharedUserSetting sus = (SharedUserSetting) obj; 4616 final int N = sus.packages.size(); 4617 final String[] res = new String[N]; 4618 final Iterator<PackageSetting> it = sus.packages.iterator(); 4619 int i = 0; 4620 while (it.hasNext()) { 4621 res[i++] = it.next().name; 4622 } 4623 return res; 4624 } else if (obj instanceof PackageSetting) { 4625 final PackageSetting ps = (PackageSetting) obj; 4626 return new String[] { ps.name }; 4627 } 4628 } 4629 return null; 4630 } 4631 4632 @Override 4633 public String getNameForUid(int uid) { 4634 // reader 4635 synchronized (mPackages) { 4636 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4637 if (obj instanceof SharedUserSetting) { 4638 final SharedUserSetting sus = (SharedUserSetting) obj; 4639 return sus.name + ":" + sus.userId; 4640 } else if (obj instanceof PackageSetting) { 4641 final PackageSetting ps = (PackageSetting) obj; 4642 return ps.name; 4643 } 4644 } 4645 return null; 4646 } 4647 4648 @Override 4649 public int getUidForSharedUser(String sharedUserName) { 4650 if(sharedUserName == null) { 4651 return -1; 4652 } 4653 // reader 4654 synchronized (mPackages) { 4655 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4656 if (suid == null) { 4657 return -1; 4658 } 4659 return suid.userId; 4660 } 4661 } 4662 4663 @Override 4664 public int getFlagsForUid(int uid) { 4665 synchronized (mPackages) { 4666 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4667 if (obj instanceof SharedUserSetting) { 4668 final SharedUserSetting sus = (SharedUserSetting) obj; 4669 return sus.pkgFlags; 4670 } else if (obj instanceof PackageSetting) { 4671 final PackageSetting ps = (PackageSetting) obj; 4672 return ps.pkgFlags; 4673 } 4674 } 4675 return 0; 4676 } 4677 4678 @Override 4679 public int getPrivateFlagsForUid(int uid) { 4680 synchronized (mPackages) { 4681 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4682 if (obj instanceof SharedUserSetting) { 4683 final SharedUserSetting sus = (SharedUserSetting) obj; 4684 return sus.pkgPrivateFlags; 4685 } else if (obj instanceof PackageSetting) { 4686 final PackageSetting ps = (PackageSetting) obj; 4687 return ps.pkgPrivateFlags; 4688 } 4689 } 4690 return 0; 4691 } 4692 4693 @Override 4694 public boolean isUidPrivileged(int uid) { 4695 uid = UserHandle.getAppId(uid); 4696 // reader 4697 synchronized (mPackages) { 4698 Object obj = mSettings.getUserIdLPr(uid); 4699 if (obj instanceof SharedUserSetting) { 4700 final SharedUserSetting sus = (SharedUserSetting) obj; 4701 final Iterator<PackageSetting> it = sus.packages.iterator(); 4702 while (it.hasNext()) { 4703 if (it.next().isPrivileged()) { 4704 return true; 4705 } 4706 } 4707 } else if (obj instanceof PackageSetting) { 4708 final PackageSetting ps = (PackageSetting) obj; 4709 return ps.isPrivileged(); 4710 } 4711 } 4712 return false; 4713 } 4714 4715 @Override 4716 public String[] getAppOpPermissionPackages(String permissionName) { 4717 synchronized (mPackages) { 4718 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4719 if (pkgs == null) { 4720 return null; 4721 } 4722 return pkgs.toArray(new String[pkgs.size()]); 4723 } 4724 } 4725 4726 @Override 4727 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4728 int flags, int userId) { 4729 if (!sUserManager.exists(userId)) return null; 4730 flags = updateFlagsForResolve(flags, userId, intent); 4731 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4732 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4733 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4734 userId); 4735 final ResolveInfo bestChoice = 4736 chooseBestActivity(intent, resolvedType, flags, query, userId); 4737 4738 if (isEphemeralAllowed(intent, query, userId)) { 4739 final EphemeralResolveInfo ai = 4740 getEphemeralResolveInfo(intent, resolvedType, userId); 4741 if (ai != null) { 4742 if (DEBUG_EPHEMERAL) { 4743 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4744 } 4745 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4746 bestChoice.ephemeralResolveInfo = ai; 4747 } 4748 } 4749 return bestChoice; 4750 } 4751 4752 @Override 4753 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4754 IntentFilter filter, int match, ComponentName activity) { 4755 final int userId = UserHandle.getCallingUserId(); 4756 if (DEBUG_PREFERRED) { 4757 Log.v(TAG, "setLastChosenActivity intent=" + intent 4758 + " resolvedType=" + resolvedType 4759 + " flags=" + flags 4760 + " filter=" + filter 4761 + " match=" + match 4762 + " activity=" + activity); 4763 filter.dump(new PrintStreamPrinter(System.out), " "); 4764 } 4765 intent.setComponent(null); 4766 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4767 userId); 4768 // Find any earlier preferred or last chosen entries and nuke them 4769 findPreferredActivity(intent, resolvedType, 4770 flags, query, 0, false, true, false, userId); 4771 // Add the new activity as the last chosen for this filter 4772 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4773 "Setting last chosen"); 4774 } 4775 4776 @Override 4777 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4778 final int userId = UserHandle.getCallingUserId(); 4779 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4780 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4781 userId); 4782 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4783 false, false, false, userId); 4784 } 4785 4786 4787 private boolean isEphemeralAllowed( 4788 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4789 // Short circuit and return early if possible. 4790 if (DISABLE_EPHEMERAL_APPS) { 4791 return false; 4792 } 4793 final int callingUser = UserHandle.getCallingUserId(); 4794 if (callingUser != UserHandle.USER_SYSTEM) { 4795 return false; 4796 } 4797 if (mEphemeralResolverConnection == null) { 4798 return false; 4799 } 4800 if (intent.getComponent() != null) { 4801 return false; 4802 } 4803 if (intent.getPackage() != null) { 4804 return false; 4805 } 4806 final boolean isWebUri = hasWebURI(intent); 4807 if (!isWebUri) { 4808 return false; 4809 } 4810 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4811 synchronized (mPackages) { 4812 final int count = resolvedActivites.size(); 4813 for (int n = 0; n < count; n++) { 4814 ResolveInfo info = resolvedActivites.get(n); 4815 String packageName = info.activityInfo.packageName; 4816 PackageSetting ps = mSettings.mPackages.get(packageName); 4817 if (ps != null) { 4818 // Try to get the status from User settings first 4819 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4820 int status = (int) (packedStatus >> 32); 4821 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4822 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4823 if (DEBUG_EPHEMERAL) { 4824 Slog.v(TAG, "DENY ephemeral apps;" 4825 + " pkg: " + packageName + ", status: " + status); 4826 } 4827 return false; 4828 } 4829 } 4830 } 4831 } 4832 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4833 return true; 4834 } 4835 4836 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4837 int userId) { 4838 MessageDigest digest = null; 4839 try { 4840 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4841 } catch (NoSuchAlgorithmException e) { 4842 // If we can't create a digest, ignore ephemeral apps. 4843 return null; 4844 } 4845 4846 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4847 final byte[] digestBytes = digest.digest(hostBytes); 4848 int shaPrefix = 4849 digestBytes[0] << 24 4850 | digestBytes[1] << 16 4851 | digestBytes[2] << 8 4852 | digestBytes[3] << 0; 4853 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4854 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4855 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4856 // No hash prefix match; there are no ephemeral apps for this domain. 4857 return null; 4858 } 4859 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4860 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4861 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4862 continue; 4863 } 4864 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4865 // No filters; this should never happen. 4866 if (filters.isEmpty()) { 4867 continue; 4868 } 4869 // We have a domain match; resolve the filters to see if anything matches. 4870 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4871 for (int j = filters.size() - 1; j >= 0; --j) { 4872 final EphemeralResolveIntentInfo intentInfo = 4873 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4874 ephemeralResolver.addFilter(intentInfo); 4875 } 4876 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4877 intent, resolvedType, false /*defaultOnly*/, userId); 4878 if (!matchedResolveInfoList.isEmpty()) { 4879 return matchedResolveInfoList.get(0); 4880 } 4881 } 4882 // Hash or filter mis-match; no ephemeral apps for this domain. 4883 return null; 4884 } 4885 4886 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4887 int flags, List<ResolveInfo> query, int userId) { 4888 if (query != null) { 4889 final int N = query.size(); 4890 if (N == 1) { 4891 return query.get(0); 4892 } else if (N > 1) { 4893 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4894 // If there is more than one activity with the same priority, 4895 // then let the user decide between them. 4896 ResolveInfo r0 = query.get(0); 4897 ResolveInfo r1 = query.get(1); 4898 if (DEBUG_INTENT_MATCHING || debug) { 4899 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4900 + r1.activityInfo.name + "=" + r1.priority); 4901 } 4902 // If the first activity has a higher priority, or a different 4903 // default, then it is always desirable to pick it. 4904 if (r0.priority != r1.priority 4905 || r0.preferredOrder != r1.preferredOrder 4906 || r0.isDefault != r1.isDefault) { 4907 return query.get(0); 4908 } 4909 // If we have saved a preference for a preferred activity for 4910 // this Intent, use that. 4911 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4912 flags, query, r0.priority, true, false, debug, userId); 4913 if (ri != null) { 4914 return ri; 4915 } 4916 ri = new ResolveInfo(mResolveInfo); 4917 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4918 ri.activityInfo.applicationInfo = new ApplicationInfo( 4919 ri.activityInfo.applicationInfo); 4920 if (userId != 0) { 4921 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4922 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4923 } 4924 // Make sure that the resolver is displayable in car mode 4925 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4926 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4927 return ri; 4928 } 4929 } 4930 return null; 4931 } 4932 4933 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4934 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4935 final int N = query.size(); 4936 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4937 .get(userId); 4938 // Get the list of persistent preferred activities that handle the intent 4939 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4940 List<PersistentPreferredActivity> pprefs = ppir != null 4941 ? ppir.queryIntent(intent, resolvedType, 4942 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4943 : null; 4944 if (pprefs != null && pprefs.size() > 0) { 4945 final int M = pprefs.size(); 4946 for (int i=0; i<M; i++) { 4947 final PersistentPreferredActivity ppa = pprefs.get(i); 4948 if (DEBUG_PREFERRED || debug) { 4949 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4950 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4951 + "\n component=" + ppa.mComponent); 4952 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4953 } 4954 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4955 flags | MATCH_DISABLED_COMPONENTS, userId); 4956 if (DEBUG_PREFERRED || debug) { 4957 Slog.v(TAG, "Found persistent preferred activity:"); 4958 if (ai != null) { 4959 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4960 } else { 4961 Slog.v(TAG, " null"); 4962 } 4963 } 4964 if (ai == null) { 4965 // This previously registered persistent preferred activity 4966 // component is no longer known. Ignore it and do NOT remove it. 4967 continue; 4968 } 4969 for (int j=0; j<N; j++) { 4970 final ResolveInfo ri = query.get(j); 4971 if (!ri.activityInfo.applicationInfo.packageName 4972 .equals(ai.applicationInfo.packageName)) { 4973 continue; 4974 } 4975 if (!ri.activityInfo.name.equals(ai.name)) { 4976 continue; 4977 } 4978 // Found a persistent preference that can handle the intent. 4979 if (DEBUG_PREFERRED || debug) { 4980 Slog.v(TAG, "Returning persistent preferred activity: " + 4981 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4982 } 4983 return ri; 4984 } 4985 } 4986 } 4987 return null; 4988 } 4989 4990 // TODO: handle preferred activities missing while user has amnesia 4991 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4992 List<ResolveInfo> query, int priority, boolean always, 4993 boolean removeMatches, boolean debug, int userId) { 4994 if (!sUserManager.exists(userId)) return null; 4995 flags = updateFlagsForResolve(flags, userId, intent); 4996 // writer 4997 synchronized (mPackages) { 4998 if (intent.getSelector() != null) { 4999 intent = intent.getSelector(); 5000 } 5001 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5002 5003 // Try to find a matching persistent preferred activity. 5004 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5005 debug, userId); 5006 5007 // If a persistent preferred activity matched, use it. 5008 if (pri != null) { 5009 return pri; 5010 } 5011 5012 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5013 // Get the list of preferred activities that handle the intent 5014 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5015 List<PreferredActivity> prefs = pir != null 5016 ? pir.queryIntent(intent, resolvedType, 5017 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5018 : null; 5019 if (prefs != null && prefs.size() > 0) { 5020 boolean changed = false; 5021 try { 5022 // First figure out how good the original match set is. 5023 // We will only allow preferred activities that came 5024 // from the same match quality. 5025 int match = 0; 5026 5027 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5028 5029 final int N = query.size(); 5030 for (int j=0; j<N; j++) { 5031 final ResolveInfo ri = query.get(j); 5032 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5033 + ": 0x" + Integer.toHexString(match)); 5034 if (ri.match > match) { 5035 match = ri.match; 5036 } 5037 } 5038 5039 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5040 + Integer.toHexString(match)); 5041 5042 match &= IntentFilter.MATCH_CATEGORY_MASK; 5043 final int M = prefs.size(); 5044 for (int i=0; i<M; i++) { 5045 final PreferredActivity pa = prefs.get(i); 5046 if (DEBUG_PREFERRED || debug) { 5047 Slog.v(TAG, "Checking PreferredActivity ds=" 5048 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5049 + "\n component=" + pa.mPref.mComponent); 5050 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5051 } 5052 if (pa.mPref.mMatch != match) { 5053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5054 + Integer.toHexString(pa.mPref.mMatch)); 5055 continue; 5056 } 5057 // If it's not an "always" type preferred activity and that's what we're 5058 // looking for, skip it. 5059 if (always && !pa.mPref.mAlways) { 5060 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5061 continue; 5062 } 5063 final ActivityInfo ai = getActivityInfo( 5064 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5065 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5066 userId); 5067 if (DEBUG_PREFERRED || debug) { 5068 Slog.v(TAG, "Found preferred activity:"); 5069 if (ai != null) { 5070 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5071 } else { 5072 Slog.v(TAG, " null"); 5073 } 5074 } 5075 if (ai == null) { 5076 // This previously registered preferred activity 5077 // component is no longer known. Most likely an update 5078 // to the app was installed and in the new version this 5079 // component no longer exists. Clean it up by removing 5080 // it from the preferred activities list, and skip it. 5081 Slog.w(TAG, "Removing dangling preferred activity: " 5082 + pa.mPref.mComponent); 5083 pir.removeFilter(pa); 5084 changed = true; 5085 continue; 5086 } 5087 for (int j=0; j<N; j++) { 5088 final ResolveInfo ri = query.get(j); 5089 if (!ri.activityInfo.applicationInfo.packageName 5090 .equals(ai.applicationInfo.packageName)) { 5091 continue; 5092 } 5093 if (!ri.activityInfo.name.equals(ai.name)) { 5094 continue; 5095 } 5096 5097 if (removeMatches) { 5098 pir.removeFilter(pa); 5099 changed = true; 5100 if (DEBUG_PREFERRED) { 5101 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5102 } 5103 break; 5104 } 5105 5106 // Okay we found a previously set preferred or last chosen app. 5107 // If the result set is different from when this 5108 // was created, we need to clear it and re-ask the 5109 // user their preference, if we're looking for an "always" type entry. 5110 if (always && !pa.mPref.sameSet(query)) { 5111 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5112 + intent + " type " + resolvedType); 5113 if (DEBUG_PREFERRED) { 5114 Slog.v(TAG, "Removing preferred activity since set changed " 5115 + pa.mPref.mComponent); 5116 } 5117 pir.removeFilter(pa); 5118 // Re-add the filter as a "last chosen" entry (!always) 5119 PreferredActivity lastChosen = new PreferredActivity( 5120 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5121 pir.addFilter(lastChosen); 5122 changed = true; 5123 return null; 5124 } 5125 5126 // Yay! Either the set matched or we're looking for the last chosen 5127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5128 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5129 return ri; 5130 } 5131 } 5132 } finally { 5133 if (changed) { 5134 if (DEBUG_PREFERRED) { 5135 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5136 } 5137 scheduleWritePackageRestrictionsLocked(userId); 5138 } 5139 } 5140 } 5141 } 5142 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5143 return null; 5144 } 5145 5146 /* 5147 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5148 */ 5149 @Override 5150 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5151 int targetUserId) { 5152 mContext.enforceCallingOrSelfPermission( 5153 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5154 List<CrossProfileIntentFilter> matches = 5155 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5156 if (matches != null) { 5157 int size = matches.size(); 5158 for (int i = 0; i < size; i++) { 5159 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5160 } 5161 } 5162 if (hasWebURI(intent)) { 5163 // cross-profile app linking works only towards the parent. 5164 final UserInfo parent = getProfileParent(sourceUserId); 5165 synchronized(mPackages) { 5166 int flags = updateFlagsForResolve(0, parent.id, intent); 5167 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5168 intent, resolvedType, flags, sourceUserId, parent.id); 5169 return xpDomainInfo != null; 5170 } 5171 } 5172 return false; 5173 } 5174 5175 private UserInfo getProfileParent(int userId) { 5176 final long identity = Binder.clearCallingIdentity(); 5177 try { 5178 return sUserManager.getProfileParent(userId); 5179 } finally { 5180 Binder.restoreCallingIdentity(identity); 5181 } 5182 } 5183 5184 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5185 String resolvedType, int userId) { 5186 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5187 if (resolver != null) { 5188 return resolver.queryIntent(intent, resolvedType, false, userId); 5189 } 5190 return null; 5191 } 5192 5193 @Override 5194 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5195 String resolvedType, int flags, int userId) { 5196 return new ParceledListSlice<>( 5197 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5198 } 5199 5200 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5201 String resolvedType, int flags, int userId) { 5202 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5203 flags = updateFlagsForResolve(flags, userId, intent); 5204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5205 false /* requireFullPermission */, false /* checkShell */, 5206 "query intent activities"); 5207 ComponentName comp = intent.getComponent(); 5208 if (comp == null) { 5209 if (intent.getSelector() != null) { 5210 intent = intent.getSelector(); 5211 comp = intent.getComponent(); 5212 } 5213 } 5214 5215 if (comp != null) { 5216 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5217 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5218 if (ai != null) { 5219 final ResolveInfo ri = new ResolveInfo(); 5220 ri.activityInfo = ai; 5221 list.add(ri); 5222 } 5223 return list; 5224 } 5225 5226 // reader 5227 synchronized (mPackages) { 5228 final String pkgName = intent.getPackage(); 5229 if (pkgName == null) { 5230 List<CrossProfileIntentFilter> matchingFilters = 5231 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5232 // Check for results that need to skip the current profile. 5233 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5234 resolvedType, flags, userId); 5235 if (xpResolveInfo != null) { 5236 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5237 result.add(xpResolveInfo); 5238 return filterIfNotSystemUser(result, userId); 5239 } 5240 5241 // Check for results in the current profile. 5242 List<ResolveInfo> result = mActivities.queryIntent( 5243 intent, resolvedType, flags, userId); 5244 result = filterIfNotSystemUser(result, userId); 5245 5246 // Check for cross profile results. 5247 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5248 xpResolveInfo = queryCrossProfileIntents( 5249 matchingFilters, intent, resolvedType, flags, userId, 5250 hasNonNegativePriorityResult); 5251 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5252 boolean isVisibleToUser = filterIfNotSystemUser( 5253 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5254 if (isVisibleToUser) { 5255 result.add(xpResolveInfo); 5256 Collections.sort(result, mResolvePrioritySorter); 5257 } 5258 } 5259 if (hasWebURI(intent)) { 5260 CrossProfileDomainInfo xpDomainInfo = null; 5261 final UserInfo parent = getProfileParent(userId); 5262 if (parent != null) { 5263 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5264 flags, userId, parent.id); 5265 } 5266 if (xpDomainInfo != null) { 5267 if (xpResolveInfo != null) { 5268 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5269 // in the result. 5270 result.remove(xpResolveInfo); 5271 } 5272 if (result.size() == 0) { 5273 result.add(xpDomainInfo.resolveInfo); 5274 return result; 5275 } 5276 } else if (result.size() <= 1) { 5277 return result; 5278 } 5279 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5280 xpDomainInfo, userId); 5281 Collections.sort(result, mResolvePrioritySorter); 5282 } 5283 return result; 5284 } 5285 final PackageParser.Package pkg = mPackages.get(pkgName); 5286 if (pkg != null) { 5287 return filterIfNotSystemUser( 5288 mActivities.queryIntentForPackage( 5289 intent, resolvedType, flags, pkg.activities, userId), 5290 userId); 5291 } 5292 return new ArrayList<ResolveInfo>(); 5293 } 5294 } 5295 5296 private static class CrossProfileDomainInfo { 5297 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5298 ResolveInfo resolveInfo; 5299 /* Best domain verification status of the activities found in the other profile */ 5300 int bestDomainVerificationStatus; 5301 } 5302 5303 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5304 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5305 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5306 sourceUserId)) { 5307 return null; 5308 } 5309 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5310 resolvedType, flags, parentUserId); 5311 5312 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5313 return null; 5314 } 5315 CrossProfileDomainInfo result = null; 5316 int size = resultTargetUser.size(); 5317 for (int i = 0; i < size; i++) { 5318 ResolveInfo riTargetUser = resultTargetUser.get(i); 5319 // Intent filter verification is only for filters that specify a host. So don't return 5320 // those that handle all web uris. 5321 if (riTargetUser.handleAllWebDataURI) { 5322 continue; 5323 } 5324 String packageName = riTargetUser.activityInfo.packageName; 5325 PackageSetting ps = mSettings.mPackages.get(packageName); 5326 if (ps == null) { 5327 continue; 5328 } 5329 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5330 int status = (int)(verificationState >> 32); 5331 if (result == null) { 5332 result = new CrossProfileDomainInfo(); 5333 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5334 sourceUserId, parentUserId); 5335 result.bestDomainVerificationStatus = status; 5336 } else { 5337 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5338 result.bestDomainVerificationStatus); 5339 } 5340 } 5341 // Don't consider matches with status NEVER across profiles. 5342 if (result != null && result.bestDomainVerificationStatus 5343 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5344 return null; 5345 } 5346 return result; 5347 } 5348 5349 /** 5350 * Verification statuses are ordered from the worse to the best, except for 5351 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5352 */ 5353 private int bestDomainVerificationStatus(int status1, int status2) { 5354 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5355 return status2; 5356 } 5357 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5358 return status1; 5359 } 5360 return (int) MathUtils.max(status1, status2); 5361 } 5362 5363 private boolean isUserEnabled(int userId) { 5364 long callingId = Binder.clearCallingIdentity(); 5365 try { 5366 UserInfo userInfo = sUserManager.getUserInfo(userId); 5367 return userInfo != null && userInfo.isEnabled(); 5368 } finally { 5369 Binder.restoreCallingIdentity(callingId); 5370 } 5371 } 5372 5373 /** 5374 * Filter out activities with systemUserOnly flag set, when current user is not System. 5375 * 5376 * @return filtered list 5377 */ 5378 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5379 if (userId == UserHandle.USER_SYSTEM) { 5380 return resolveInfos; 5381 } 5382 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5383 ResolveInfo info = resolveInfos.get(i); 5384 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5385 resolveInfos.remove(i); 5386 } 5387 } 5388 return resolveInfos; 5389 } 5390 5391 /** 5392 * @param resolveInfos list of resolve infos in descending priority order 5393 * @return if the list contains a resolve info with non-negative priority 5394 */ 5395 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5396 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5397 } 5398 5399 private static boolean hasWebURI(Intent intent) { 5400 if (intent.getData() == null) { 5401 return false; 5402 } 5403 final String scheme = intent.getScheme(); 5404 if (TextUtils.isEmpty(scheme)) { 5405 return false; 5406 } 5407 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5408 } 5409 5410 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5411 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5412 int userId) { 5413 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5414 5415 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5416 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5417 candidates.size()); 5418 } 5419 5420 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5421 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5422 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5423 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5424 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5425 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5426 5427 synchronized (mPackages) { 5428 final int count = candidates.size(); 5429 // First, try to use linked apps. Partition the candidates into four lists: 5430 // one for the final results, one for the "do not use ever", one for "undefined status" 5431 // and finally one for "browser app type". 5432 for (int n=0; n<count; n++) { 5433 ResolveInfo info = candidates.get(n); 5434 String packageName = info.activityInfo.packageName; 5435 PackageSetting ps = mSettings.mPackages.get(packageName); 5436 if (ps != null) { 5437 // Add to the special match all list (Browser use case) 5438 if (info.handleAllWebDataURI) { 5439 matchAllList.add(info); 5440 continue; 5441 } 5442 // Try to get the status from User settings first 5443 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5444 int status = (int)(packedStatus >> 32); 5445 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5446 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5447 if (DEBUG_DOMAIN_VERIFICATION) { 5448 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5449 + " : linkgen=" + linkGeneration); 5450 } 5451 // Use link-enabled generation as preferredOrder, i.e. 5452 // prefer newly-enabled over earlier-enabled. 5453 info.preferredOrder = linkGeneration; 5454 alwaysList.add(info); 5455 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5456 if (DEBUG_DOMAIN_VERIFICATION) { 5457 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5458 } 5459 neverList.add(info); 5460 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5461 if (DEBUG_DOMAIN_VERIFICATION) { 5462 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5463 } 5464 alwaysAskList.add(info); 5465 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5466 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5467 if (DEBUG_DOMAIN_VERIFICATION) { 5468 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5469 } 5470 undefinedList.add(info); 5471 } 5472 } 5473 } 5474 5475 // We'll want to include browser possibilities in a few cases 5476 boolean includeBrowser = false; 5477 5478 // First try to add the "always" resolution(s) for the current user, if any 5479 if (alwaysList.size() > 0) { 5480 result.addAll(alwaysList); 5481 } else { 5482 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5483 result.addAll(undefinedList); 5484 // Maybe add one for the other profile. 5485 if (xpDomainInfo != null && ( 5486 xpDomainInfo.bestDomainVerificationStatus 5487 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5488 result.add(xpDomainInfo.resolveInfo); 5489 } 5490 includeBrowser = true; 5491 } 5492 5493 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5494 // If there were 'always' entries their preferred order has been set, so we also 5495 // back that off to make the alternatives equivalent 5496 if (alwaysAskList.size() > 0) { 5497 for (ResolveInfo i : result) { 5498 i.preferredOrder = 0; 5499 } 5500 result.addAll(alwaysAskList); 5501 includeBrowser = true; 5502 } 5503 5504 if (includeBrowser) { 5505 // Also add browsers (all of them or only the default one) 5506 if (DEBUG_DOMAIN_VERIFICATION) { 5507 Slog.v(TAG, " ...including browsers in candidate set"); 5508 } 5509 if ((matchFlags & MATCH_ALL) != 0) { 5510 result.addAll(matchAllList); 5511 } else { 5512 // Browser/generic handling case. If there's a default browser, go straight 5513 // to that (but only if there is no other higher-priority match). 5514 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5515 int maxMatchPrio = 0; 5516 ResolveInfo defaultBrowserMatch = null; 5517 final int numCandidates = matchAllList.size(); 5518 for (int n = 0; n < numCandidates; n++) { 5519 ResolveInfo info = matchAllList.get(n); 5520 // track the highest overall match priority... 5521 if (info.priority > maxMatchPrio) { 5522 maxMatchPrio = info.priority; 5523 } 5524 // ...and the highest-priority default browser match 5525 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5526 if (defaultBrowserMatch == null 5527 || (defaultBrowserMatch.priority < info.priority)) { 5528 if (debug) { 5529 Slog.v(TAG, "Considering default browser match " + info); 5530 } 5531 defaultBrowserMatch = info; 5532 } 5533 } 5534 } 5535 if (defaultBrowserMatch != null 5536 && defaultBrowserMatch.priority >= maxMatchPrio 5537 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5538 { 5539 if (debug) { 5540 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5541 } 5542 result.add(defaultBrowserMatch); 5543 } else { 5544 result.addAll(matchAllList); 5545 } 5546 } 5547 5548 // If there is nothing selected, add all candidates and remove the ones that the user 5549 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5550 if (result.size() == 0) { 5551 result.addAll(candidates); 5552 result.removeAll(neverList); 5553 } 5554 } 5555 } 5556 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5557 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5558 result.size()); 5559 for (ResolveInfo info : result) { 5560 Slog.v(TAG, " + " + info.activityInfo); 5561 } 5562 } 5563 return result; 5564 } 5565 5566 // Returns a packed value as a long: 5567 // 5568 // high 'int'-sized word: link status: undefined/ask/never/always. 5569 // low 'int'-sized word: relative priority among 'always' results. 5570 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5571 long result = ps.getDomainVerificationStatusForUser(userId); 5572 // if none available, get the master status 5573 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5574 if (ps.getIntentFilterVerificationInfo() != null) { 5575 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5576 } 5577 } 5578 return result; 5579 } 5580 5581 private ResolveInfo querySkipCurrentProfileIntents( 5582 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5583 int flags, int sourceUserId) { 5584 if (matchingFilters != null) { 5585 int size = matchingFilters.size(); 5586 for (int i = 0; i < size; i ++) { 5587 CrossProfileIntentFilter filter = matchingFilters.get(i); 5588 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5589 // Checking if there are activities in the target user that can handle the 5590 // intent. 5591 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5592 resolvedType, flags, sourceUserId); 5593 if (resolveInfo != null) { 5594 return resolveInfo; 5595 } 5596 } 5597 } 5598 } 5599 return null; 5600 } 5601 5602 // Return matching ResolveInfo in target user if any. 5603 private ResolveInfo queryCrossProfileIntents( 5604 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5605 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5606 if (matchingFilters != null) { 5607 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5608 // match the same intent. For performance reasons, it is better not to 5609 // run queryIntent twice for the same userId 5610 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5611 int size = matchingFilters.size(); 5612 for (int i = 0; i < size; i++) { 5613 CrossProfileIntentFilter filter = matchingFilters.get(i); 5614 int targetUserId = filter.getTargetUserId(); 5615 boolean skipCurrentProfile = 5616 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5617 boolean skipCurrentProfileIfNoMatchFound = 5618 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5619 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5620 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5621 // Checking if there are activities in the target user that can handle the 5622 // intent. 5623 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5624 resolvedType, flags, sourceUserId); 5625 if (resolveInfo != null) return resolveInfo; 5626 alreadyTriedUserIds.put(targetUserId, true); 5627 } 5628 } 5629 } 5630 return null; 5631 } 5632 5633 /** 5634 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5635 * will forward the intent to the filter's target user. 5636 * Otherwise, returns null. 5637 */ 5638 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5639 String resolvedType, int flags, int sourceUserId) { 5640 int targetUserId = filter.getTargetUserId(); 5641 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5642 resolvedType, flags, targetUserId); 5643 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5644 // If all the matches in the target profile are suspended, return null. 5645 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5646 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5647 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5648 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5649 targetUserId); 5650 } 5651 } 5652 } 5653 return null; 5654 } 5655 5656 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5657 int sourceUserId, int targetUserId) { 5658 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5659 long ident = Binder.clearCallingIdentity(); 5660 boolean targetIsProfile; 5661 try { 5662 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5663 } finally { 5664 Binder.restoreCallingIdentity(ident); 5665 } 5666 String className; 5667 if (targetIsProfile) { 5668 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5669 } else { 5670 className = FORWARD_INTENT_TO_PARENT; 5671 } 5672 ComponentName forwardingActivityComponentName = new ComponentName( 5673 mAndroidApplication.packageName, className); 5674 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5675 sourceUserId); 5676 if (!targetIsProfile) { 5677 forwardingActivityInfo.showUserIcon = targetUserId; 5678 forwardingResolveInfo.noResourceId = true; 5679 } 5680 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5681 forwardingResolveInfo.priority = 0; 5682 forwardingResolveInfo.preferredOrder = 0; 5683 forwardingResolveInfo.match = 0; 5684 forwardingResolveInfo.isDefault = true; 5685 forwardingResolveInfo.filter = filter; 5686 forwardingResolveInfo.targetUserId = targetUserId; 5687 return forwardingResolveInfo; 5688 } 5689 5690 @Override 5691 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5692 Intent[] specifics, String[] specificTypes, Intent intent, 5693 String resolvedType, int flags, int userId) { 5694 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5695 specificTypes, intent, resolvedType, flags, userId)); 5696 } 5697 5698 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5699 Intent[] specifics, String[] specificTypes, Intent intent, 5700 String resolvedType, int flags, int userId) { 5701 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5702 flags = updateFlagsForResolve(flags, userId, intent); 5703 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5704 false /* requireFullPermission */, false /* checkShell */, 5705 "query intent activity options"); 5706 final String resultsAction = intent.getAction(); 5707 5708 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5709 | PackageManager.GET_RESOLVED_FILTER, userId); 5710 5711 if (DEBUG_INTENT_MATCHING) { 5712 Log.v(TAG, "Query " + intent + ": " + results); 5713 } 5714 5715 int specificsPos = 0; 5716 int N; 5717 5718 // todo: note that the algorithm used here is O(N^2). This 5719 // isn't a problem in our current environment, but if we start running 5720 // into situations where we have more than 5 or 10 matches then this 5721 // should probably be changed to something smarter... 5722 5723 // First we go through and resolve each of the specific items 5724 // that were supplied, taking care of removing any corresponding 5725 // duplicate items in the generic resolve list. 5726 if (specifics != null) { 5727 for (int i=0; i<specifics.length; i++) { 5728 final Intent sintent = specifics[i]; 5729 if (sintent == null) { 5730 continue; 5731 } 5732 5733 if (DEBUG_INTENT_MATCHING) { 5734 Log.v(TAG, "Specific #" + i + ": " + sintent); 5735 } 5736 5737 String action = sintent.getAction(); 5738 if (resultsAction != null && resultsAction.equals(action)) { 5739 // If this action was explicitly requested, then don't 5740 // remove things that have it. 5741 action = null; 5742 } 5743 5744 ResolveInfo ri = null; 5745 ActivityInfo ai = null; 5746 5747 ComponentName comp = sintent.getComponent(); 5748 if (comp == null) { 5749 ri = resolveIntent( 5750 sintent, 5751 specificTypes != null ? specificTypes[i] : null, 5752 flags, userId); 5753 if (ri == null) { 5754 continue; 5755 } 5756 if (ri == mResolveInfo) { 5757 // ACK! Must do something better with this. 5758 } 5759 ai = ri.activityInfo; 5760 comp = new ComponentName(ai.applicationInfo.packageName, 5761 ai.name); 5762 } else { 5763 ai = getActivityInfo(comp, flags, userId); 5764 if (ai == null) { 5765 continue; 5766 } 5767 } 5768 5769 // Look for any generic query activities that are duplicates 5770 // of this specific one, and remove them from the results. 5771 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5772 N = results.size(); 5773 int j; 5774 for (j=specificsPos; j<N; j++) { 5775 ResolveInfo sri = results.get(j); 5776 if ((sri.activityInfo.name.equals(comp.getClassName()) 5777 && sri.activityInfo.applicationInfo.packageName.equals( 5778 comp.getPackageName())) 5779 || (action != null && sri.filter.matchAction(action))) { 5780 results.remove(j); 5781 if (DEBUG_INTENT_MATCHING) Log.v( 5782 TAG, "Removing duplicate item from " + j 5783 + " due to specific " + specificsPos); 5784 if (ri == null) { 5785 ri = sri; 5786 } 5787 j--; 5788 N--; 5789 } 5790 } 5791 5792 // Add this specific item to its proper place. 5793 if (ri == null) { 5794 ri = new ResolveInfo(); 5795 ri.activityInfo = ai; 5796 } 5797 results.add(specificsPos, ri); 5798 ri.specificIndex = i; 5799 specificsPos++; 5800 } 5801 } 5802 5803 // Now we go through the remaining generic results and remove any 5804 // duplicate actions that are found here. 5805 N = results.size(); 5806 for (int i=specificsPos; i<N-1; i++) { 5807 final ResolveInfo rii = results.get(i); 5808 if (rii.filter == null) { 5809 continue; 5810 } 5811 5812 // Iterate over all of the actions of this result's intent 5813 // filter... typically this should be just one. 5814 final Iterator<String> it = rii.filter.actionsIterator(); 5815 if (it == null) { 5816 continue; 5817 } 5818 while (it.hasNext()) { 5819 final String action = it.next(); 5820 if (resultsAction != null && resultsAction.equals(action)) { 5821 // If this action was explicitly requested, then don't 5822 // remove things that have it. 5823 continue; 5824 } 5825 for (int j=i+1; j<N; j++) { 5826 final ResolveInfo rij = results.get(j); 5827 if (rij.filter != null && rij.filter.hasAction(action)) { 5828 results.remove(j); 5829 if (DEBUG_INTENT_MATCHING) Log.v( 5830 TAG, "Removing duplicate item from " + j 5831 + " due to action " + action + " at " + i); 5832 j--; 5833 N--; 5834 } 5835 } 5836 } 5837 5838 // If the caller didn't request filter information, drop it now 5839 // so we don't have to marshall/unmarshall it. 5840 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5841 rii.filter = null; 5842 } 5843 } 5844 5845 // Filter out the caller activity if so requested. 5846 if (caller != null) { 5847 N = results.size(); 5848 for (int i=0; i<N; i++) { 5849 ActivityInfo ainfo = results.get(i).activityInfo; 5850 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5851 && caller.getClassName().equals(ainfo.name)) { 5852 results.remove(i); 5853 break; 5854 } 5855 } 5856 } 5857 5858 // If the caller didn't request filter information, 5859 // drop them now so we don't have to 5860 // marshall/unmarshall it. 5861 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5862 N = results.size(); 5863 for (int i=0; i<N; i++) { 5864 results.get(i).filter = null; 5865 } 5866 } 5867 5868 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5869 return results; 5870 } 5871 5872 @Override 5873 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5874 String resolvedType, int flags, int userId) { 5875 return new ParceledListSlice<>( 5876 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5877 } 5878 5879 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5880 String resolvedType, int flags, int userId) { 5881 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5882 flags = updateFlagsForResolve(flags, userId, intent); 5883 ComponentName comp = intent.getComponent(); 5884 if (comp == null) { 5885 if (intent.getSelector() != null) { 5886 intent = intent.getSelector(); 5887 comp = intent.getComponent(); 5888 } 5889 } 5890 if (comp != null) { 5891 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5892 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5893 if (ai != null) { 5894 ResolveInfo ri = new ResolveInfo(); 5895 ri.activityInfo = ai; 5896 list.add(ri); 5897 } 5898 return list; 5899 } 5900 5901 // reader 5902 synchronized (mPackages) { 5903 String pkgName = intent.getPackage(); 5904 if (pkgName == null) { 5905 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5906 } 5907 final PackageParser.Package pkg = mPackages.get(pkgName); 5908 if (pkg != null) { 5909 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5910 userId); 5911 } 5912 return Collections.emptyList(); 5913 } 5914 } 5915 5916 @Override 5917 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5918 if (!sUserManager.exists(userId)) return null; 5919 flags = updateFlagsForResolve(flags, userId, intent); 5920 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5921 if (query != null) { 5922 if (query.size() >= 1) { 5923 // If there is more than one service with the same priority, 5924 // just arbitrarily pick the first one. 5925 return query.get(0); 5926 } 5927 } 5928 return null; 5929 } 5930 5931 @Override 5932 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5933 String resolvedType, int flags, int userId) { 5934 return new ParceledListSlice<>( 5935 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5936 } 5937 5938 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5939 String resolvedType, int flags, int userId) { 5940 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5941 flags = updateFlagsForResolve(flags, userId, intent); 5942 ComponentName comp = intent.getComponent(); 5943 if (comp == null) { 5944 if (intent.getSelector() != null) { 5945 intent = intent.getSelector(); 5946 comp = intent.getComponent(); 5947 } 5948 } 5949 if (comp != null) { 5950 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5951 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5952 if (si != null) { 5953 final ResolveInfo ri = new ResolveInfo(); 5954 ri.serviceInfo = si; 5955 list.add(ri); 5956 } 5957 return list; 5958 } 5959 5960 // reader 5961 synchronized (mPackages) { 5962 String pkgName = intent.getPackage(); 5963 if (pkgName == null) { 5964 return mServices.queryIntent(intent, resolvedType, flags, userId); 5965 } 5966 final PackageParser.Package pkg = mPackages.get(pkgName); 5967 if (pkg != null) { 5968 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5969 userId); 5970 } 5971 return Collections.emptyList(); 5972 } 5973 } 5974 5975 @Override 5976 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5977 String resolvedType, int flags, int userId) { 5978 return new ParceledListSlice<>( 5979 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5980 } 5981 5982 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5983 Intent intent, String resolvedType, int flags, int userId) { 5984 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5985 flags = updateFlagsForResolve(flags, userId, intent); 5986 ComponentName comp = intent.getComponent(); 5987 if (comp == null) { 5988 if (intent.getSelector() != null) { 5989 intent = intent.getSelector(); 5990 comp = intent.getComponent(); 5991 } 5992 } 5993 if (comp != null) { 5994 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5995 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5996 if (pi != null) { 5997 final ResolveInfo ri = new ResolveInfo(); 5998 ri.providerInfo = pi; 5999 list.add(ri); 6000 } 6001 return list; 6002 } 6003 6004 // reader 6005 synchronized (mPackages) { 6006 String pkgName = intent.getPackage(); 6007 if (pkgName == null) { 6008 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6009 } 6010 final PackageParser.Package pkg = mPackages.get(pkgName); 6011 if (pkg != null) { 6012 return mProviders.queryIntentForPackage( 6013 intent, resolvedType, flags, pkg.providers, userId); 6014 } 6015 return Collections.emptyList(); 6016 } 6017 } 6018 6019 @Override 6020 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6021 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6022 flags = updateFlagsForPackage(flags, userId, null); 6023 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6024 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6025 true /* requireFullPermission */, false /* checkShell */, 6026 "get installed packages"); 6027 6028 // writer 6029 synchronized (mPackages) { 6030 ArrayList<PackageInfo> list; 6031 if (listUninstalled) { 6032 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6033 for (PackageSetting ps : mSettings.mPackages.values()) { 6034 final PackageInfo pi; 6035 if (ps.pkg != null) { 6036 pi = generatePackageInfo(ps, flags, userId); 6037 } else { 6038 pi = generatePackageInfo(ps, flags, userId); 6039 } 6040 if (pi != null) { 6041 list.add(pi); 6042 } 6043 } 6044 } else { 6045 list = new ArrayList<PackageInfo>(mPackages.size()); 6046 for (PackageParser.Package p : mPackages.values()) { 6047 final PackageInfo pi = 6048 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6049 if (pi != null) { 6050 list.add(pi); 6051 } 6052 } 6053 } 6054 6055 return new ParceledListSlice<PackageInfo>(list); 6056 } 6057 } 6058 6059 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6060 String[] permissions, boolean[] tmp, int flags, int userId) { 6061 int numMatch = 0; 6062 final PermissionsState permissionsState = ps.getPermissionsState(); 6063 for (int i=0; i<permissions.length; i++) { 6064 final String permission = permissions[i]; 6065 if (permissionsState.hasPermission(permission, userId)) { 6066 tmp[i] = true; 6067 numMatch++; 6068 } else { 6069 tmp[i] = false; 6070 } 6071 } 6072 if (numMatch == 0) { 6073 return; 6074 } 6075 final PackageInfo pi; 6076 if (ps.pkg != null) { 6077 pi = generatePackageInfo(ps, flags, userId); 6078 } else { 6079 pi = generatePackageInfo(ps, flags, userId); 6080 } 6081 // The above might return null in cases of uninstalled apps or install-state 6082 // skew across users/profiles. 6083 if (pi != null) { 6084 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6085 if (numMatch == permissions.length) { 6086 pi.requestedPermissions = permissions; 6087 } else { 6088 pi.requestedPermissions = new String[numMatch]; 6089 numMatch = 0; 6090 for (int i=0; i<permissions.length; i++) { 6091 if (tmp[i]) { 6092 pi.requestedPermissions[numMatch] = permissions[i]; 6093 numMatch++; 6094 } 6095 } 6096 } 6097 } 6098 list.add(pi); 6099 } 6100 } 6101 6102 @Override 6103 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6104 String[] permissions, int flags, int userId) { 6105 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6106 flags = updateFlagsForPackage(flags, userId, permissions); 6107 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6108 6109 // writer 6110 synchronized (mPackages) { 6111 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6112 boolean[] tmpBools = new boolean[permissions.length]; 6113 if (listUninstalled) { 6114 for (PackageSetting ps : mSettings.mPackages.values()) { 6115 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6116 } 6117 } else { 6118 for (PackageParser.Package pkg : mPackages.values()) { 6119 PackageSetting ps = (PackageSetting)pkg.mExtras; 6120 if (ps != null) { 6121 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6122 userId); 6123 } 6124 } 6125 } 6126 6127 return new ParceledListSlice<PackageInfo>(list); 6128 } 6129 } 6130 6131 @Override 6132 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6133 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6134 flags = updateFlagsForApplication(flags, userId, null); 6135 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6136 6137 // writer 6138 synchronized (mPackages) { 6139 ArrayList<ApplicationInfo> list; 6140 if (listUninstalled) { 6141 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6142 for (PackageSetting ps : mSettings.mPackages.values()) { 6143 ApplicationInfo ai; 6144 if (ps.pkg != null) { 6145 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6146 ps.readUserState(userId), userId); 6147 } else { 6148 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6149 } 6150 if (ai != null) { 6151 list.add(ai); 6152 } 6153 } 6154 } else { 6155 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6156 for (PackageParser.Package p : mPackages.values()) { 6157 if (p.mExtras != null) { 6158 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6159 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6160 if (ai != null) { 6161 list.add(ai); 6162 } 6163 } 6164 } 6165 } 6166 6167 return new ParceledListSlice<ApplicationInfo>(list); 6168 } 6169 } 6170 6171 @Override 6172 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6173 if (DISABLE_EPHEMERAL_APPS) { 6174 return null; 6175 } 6176 6177 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6178 "getEphemeralApplications"); 6179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6180 true /* requireFullPermission */, false /* checkShell */, 6181 "getEphemeralApplications"); 6182 synchronized (mPackages) { 6183 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6184 .getEphemeralApplicationsLPw(userId); 6185 if (ephemeralApps != null) { 6186 return new ParceledListSlice<>(ephemeralApps); 6187 } 6188 } 6189 return null; 6190 } 6191 6192 @Override 6193 public boolean isEphemeralApplication(String packageName, int userId) { 6194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6195 true /* requireFullPermission */, false /* checkShell */, 6196 "isEphemeral"); 6197 if (DISABLE_EPHEMERAL_APPS) { 6198 return false; 6199 } 6200 6201 if (!isCallerSameApp(packageName)) { 6202 return false; 6203 } 6204 synchronized (mPackages) { 6205 PackageParser.Package pkg = mPackages.get(packageName); 6206 if (pkg != null) { 6207 return pkg.applicationInfo.isEphemeralApp(); 6208 } 6209 } 6210 return false; 6211 } 6212 6213 @Override 6214 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6215 if (DISABLE_EPHEMERAL_APPS) { 6216 return null; 6217 } 6218 6219 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6220 true /* requireFullPermission */, false /* checkShell */, 6221 "getCookie"); 6222 if (!isCallerSameApp(packageName)) { 6223 return null; 6224 } 6225 synchronized (mPackages) { 6226 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6227 packageName, userId); 6228 } 6229 } 6230 6231 @Override 6232 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6233 if (DISABLE_EPHEMERAL_APPS) { 6234 return true; 6235 } 6236 6237 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6238 true /* requireFullPermission */, true /* checkShell */, 6239 "setCookie"); 6240 if (!isCallerSameApp(packageName)) { 6241 return false; 6242 } 6243 synchronized (mPackages) { 6244 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6245 packageName, cookie, userId); 6246 } 6247 } 6248 6249 @Override 6250 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6251 if (DISABLE_EPHEMERAL_APPS) { 6252 return null; 6253 } 6254 6255 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6256 "getEphemeralApplicationIcon"); 6257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6258 true /* requireFullPermission */, false /* checkShell */, 6259 "getEphemeralApplicationIcon"); 6260 synchronized (mPackages) { 6261 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6262 packageName, userId); 6263 } 6264 } 6265 6266 private boolean isCallerSameApp(String packageName) { 6267 PackageParser.Package pkg = mPackages.get(packageName); 6268 return pkg != null 6269 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6270 } 6271 6272 @Override 6273 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6274 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6275 } 6276 6277 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6278 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6279 6280 // reader 6281 synchronized (mPackages) { 6282 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6283 final int userId = UserHandle.getCallingUserId(); 6284 while (i.hasNext()) { 6285 final PackageParser.Package p = i.next(); 6286 if (p.applicationInfo == null) continue; 6287 6288 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6289 && !p.applicationInfo.isDirectBootAware(); 6290 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6291 && p.applicationInfo.isDirectBootAware(); 6292 6293 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6294 && (!mSafeMode || isSystemApp(p)) 6295 && (matchesUnaware || matchesAware)) { 6296 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6297 if (ps != null) { 6298 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6299 ps.readUserState(userId), userId); 6300 if (ai != null) { 6301 finalList.add(ai); 6302 } 6303 } 6304 } 6305 } 6306 } 6307 6308 return finalList; 6309 } 6310 6311 @Override 6312 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6313 if (!sUserManager.exists(userId)) return null; 6314 flags = updateFlagsForComponent(flags, userId, name); 6315 // reader 6316 synchronized (mPackages) { 6317 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6318 PackageSetting ps = provider != null 6319 ? mSettings.mPackages.get(provider.owner.packageName) 6320 : null; 6321 return ps != null 6322 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6323 ? PackageParser.generateProviderInfo(provider, flags, 6324 ps.readUserState(userId), userId) 6325 : null; 6326 } 6327 } 6328 6329 /** 6330 * @deprecated 6331 */ 6332 @Deprecated 6333 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6334 // reader 6335 synchronized (mPackages) { 6336 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6337 .entrySet().iterator(); 6338 final int userId = UserHandle.getCallingUserId(); 6339 while (i.hasNext()) { 6340 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6341 PackageParser.Provider p = entry.getValue(); 6342 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6343 6344 if (ps != null && p.syncable 6345 && (!mSafeMode || (p.info.applicationInfo.flags 6346 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6347 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6348 ps.readUserState(userId), userId); 6349 if (info != null) { 6350 outNames.add(entry.getKey()); 6351 outInfo.add(info); 6352 } 6353 } 6354 } 6355 } 6356 } 6357 6358 @Override 6359 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6360 int uid, int flags) { 6361 final int userId = processName != null ? UserHandle.getUserId(uid) 6362 : UserHandle.getCallingUserId(); 6363 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6364 flags = updateFlagsForComponent(flags, userId, processName); 6365 6366 ArrayList<ProviderInfo> finalList = null; 6367 // reader 6368 synchronized (mPackages) { 6369 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6370 while (i.hasNext()) { 6371 final PackageParser.Provider p = i.next(); 6372 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6373 if (ps != null && p.info.authority != null 6374 && (processName == null 6375 || (p.info.processName.equals(processName) 6376 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6377 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6378 if (finalList == null) { 6379 finalList = new ArrayList<ProviderInfo>(3); 6380 } 6381 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6382 ps.readUserState(userId), userId); 6383 if (info != null) { 6384 finalList.add(info); 6385 } 6386 } 6387 } 6388 } 6389 6390 if (finalList != null) { 6391 Collections.sort(finalList, mProviderInitOrderSorter); 6392 return new ParceledListSlice<ProviderInfo>(finalList); 6393 } 6394 6395 return ParceledListSlice.emptyList(); 6396 } 6397 6398 @Override 6399 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6400 // reader 6401 synchronized (mPackages) { 6402 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6403 return PackageParser.generateInstrumentationInfo(i, flags); 6404 } 6405 } 6406 6407 @Override 6408 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6409 String targetPackage, int flags) { 6410 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6411 } 6412 6413 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6414 int flags) { 6415 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6416 6417 // reader 6418 synchronized (mPackages) { 6419 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6420 while (i.hasNext()) { 6421 final PackageParser.Instrumentation p = i.next(); 6422 if (targetPackage == null 6423 || targetPackage.equals(p.info.targetPackage)) { 6424 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6425 flags); 6426 if (ii != null) { 6427 finalList.add(ii); 6428 } 6429 } 6430 } 6431 } 6432 6433 return finalList; 6434 } 6435 6436 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6437 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6438 if (overlays == null) { 6439 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6440 return; 6441 } 6442 for (PackageParser.Package opkg : overlays.values()) { 6443 // Not much to do if idmap fails: we already logged the error 6444 // and we certainly don't want to abort installation of pkg simply 6445 // because an overlay didn't fit properly. For these reasons, 6446 // ignore the return value of createIdmapForPackagePairLI. 6447 createIdmapForPackagePairLI(pkg, opkg); 6448 } 6449 } 6450 6451 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6452 PackageParser.Package opkg) { 6453 if (!opkg.mTrustedOverlay) { 6454 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6455 opkg.baseCodePath + ": overlay not trusted"); 6456 return false; 6457 } 6458 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6459 if (overlaySet == null) { 6460 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6461 opkg.baseCodePath + " but target package has no known overlays"); 6462 return false; 6463 } 6464 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6465 // TODO: generate idmap for split APKs 6466 try { 6467 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6468 } catch (InstallerException e) { 6469 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6470 + opkg.baseCodePath); 6471 return false; 6472 } 6473 PackageParser.Package[] overlayArray = 6474 overlaySet.values().toArray(new PackageParser.Package[0]); 6475 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6476 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6477 return p1.mOverlayPriority - p2.mOverlayPriority; 6478 } 6479 }; 6480 Arrays.sort(overlayArray, cmp); 6481 6482 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6483 int i = 0; 6484 for (PackageParser.Package p : overlayArray) { 6485 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6486 } 6487 return true; 6488 } 6489 6490 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6492 try { 6493 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6494 } finally { 6495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6496 } 6497 } 6498 6499 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6500 final File[] files = dir.listFiles(); 6501 if (ArrayUtils.isEmpty(files)) { 6502 Log.d(TAG, "No files in app dir " + dir); 6503 return; 6504 } 6505 6506 if (DEBUG_PACKAGE_SCANNING) { 6507 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6508 + " flags=0x" + Integer.toHexString(parseFlags)); 6509 } 6510 6511 for (File file : files) { 6512 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6513 && !PackageInstallerService.isStageName(file.getName()); 6514 if (!isPackage) { 6515 // Ignore entries which are not packages 6516 continue; 6517 } 6518 try { 6519 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6520 scanFlags, currentTime, null); 6521 } catch (PackageManagerException e) { 6522 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6523 6524 // Delete invalid userdata apps 6525 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6526 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6527 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6528 removeCodePathLI(file); 6529 } 6530 } 6531 } 6532 } 6533 6534 private static File getSettingsProblemFile() { 6535 File dataDir = Environment.getDataDirectory(); 6536 File systemDir = new File(dataDir, "system"); 6537 File fname = new File(systemDir, "uiderrors.txt"); 6538 return fname; 6539 } 6540 6541 static void reportSettingsProblem(int priority, String msg) { 6542 logCriticalInfo(priority, msg); 6543 } 6544 6545 static void logCriticalInfo(int priority, String msg) { 6546 Slog.println(priority, TAG, msg); 6547 EventLogTags.writePmCriticalInfo(msg); 6548 try { 6549 File fname = getSettingsProblemFile(); 6550 FileOutputStream out = new FileOutputStream(fname, true); 6551 PrintWriter pw = new FastPrintWriter(out); 6552 SimpleDateFormat formatter = new SimpleDateFormat(); 6553 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6554 pw.println(dateString + ": " + msg); 6555 pw.close(); 6556 FileUtils.setPermissions( 6557 fname.toString(), 6558 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6559 -1, -1); 6560 } catch (java.io.IOException e) { 6561 } 6562 } 6563 6564 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6565 int parseFlags) throws PackageManagerException { 6566 if (ps != null 6567 && ps.codePath.equals(srcFile) 6568 && ps.timeStamp == srcFile.lastModified() 6569 && !isCompatSignatureUpdateNeeded(pkg) 6570 && !isRecoverSignatureUpdateNeeded(pkg)) { 6571 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6572 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6573 ArraySet<PublicKey> signingKs; 6574 synchronized (mPackages) { 6575 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6576 } 6577 if (ps.signatures.mSignatures != null 6578 && ps.signatures.mSignatures.length != 0 6579 && signingKs != null) { 6580 // Optimization: reuse the existing cached certificates 6581 // if the package appears to be unchanged. 6582 pkg.mSignatures = ps.signatures.mSignatures; 6583 pkg.mSigningKeys = signingKs; 6584 return; 6585 } 6586 6587 Slog.w(TAG, "PackageSetting for " + ps.name 6588 + " is missing signatures. Collecting certs again to recover them."); 6589 } else { 6590 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6591 } 6592 6593 try { 6594 PackageParser.collectCertificates(pkg, parseFlags); 6595 } catch (PackageParserException e) { 6596 throw PackageManagerException.from(e); 6597 } 6598 } 6599 6600 /** 6601 * Traces a package scan. 6602 * @see #scanPackageLI(File, int, int, long, UserHandle) 6603 */ 6604 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6605 long currentTime, UserHandle user) throws PackageManagerException { 6606 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6607 try { 6608 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6609 } finally { 6610 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6611 } 6612 } 6613 6614 /** 6615 * Scans a package and returns the newly parsed package. 6616 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6617 */ 6618 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6619 long currentTime, UserHandle user) throws PackageManagerException { 6620 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6621 parseFlags |= mDefParseFlags; 6622 PackageParser pp = new PackageParser(); 6623 pp.setSeparateProcesses(mSeparateProcesses); 6624 pp.setOnlyCoreApps(mOnlyCore); 6625 pp.setDisplayMetrics(mMetrics); 6626 6627 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6628 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6629 } 6630 6631 final PackageParser.Package pkg; 6632 try { 6633 pkg = pp.parsePackage(scanFile, parseFlags); 6634 } catch (PackageParserException e) { 6635 throw PackageManagerException.from(e); 6636 } 6637 6638 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6639 } 6640 6641 /** 6642 * Scans a package and returns the newly parsed package. 6643 * @throws PackageManagerException on a parse error. 6644 */ 6645 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6646 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6647 throws PackageManagerException { 6648 // If the package has children and this is the first dive in the function 6649 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6650 // packages (parent and children) would be successfully scanned before the 6651 // actual scan since scanning mutates internal state and we want to atomically 6652 // install the package and its children. 6653 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6654 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6655 scanFlags |= SCAN_CHECK_ONLY; 6656 } 6657 } else { 6658 scanFlags &= ~SCAN_CHECK_ONLY; 6659 } 6660 6661 // Scan the parent 6662 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6663 scanFlags, currentTime, user); 6664 6665 // Scan the children 6666 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6667 for (int i = 0; i < childCount; i++) { 6668 PackageParser.Package childPackage = pkg.childPackages.get(i); 6669 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6670 currentTime, user); 6671 } 6672 6673 6674 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6675 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6676 } 6677 6678 return scannedPkg; 6679 } 6680 6681 /** 6682 * Scans a package and returns the newly parsed package. 6683 * @throws PackageManagerException on a parse error. 6684 */ 6685 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6686 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6687 throws PackageManagerException { 6688 PackageSetting ps = null; 6689 PackageSetting updatedPkg; 6690 // reader 6691 synchronized (mPackages) { 6692 // Look to see if we already know about this package. 6693 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6694 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6695 // This package has been renamed to its original name. Let's 6696 // use that. 6697 ps = mSettings.peekPackageLPr(oldName); 6698 } 6699 // If there was no original package, see one for the real package name. 6700 if (ps == null) { 6701 ps = mSettings.peekPackageLPr(pkg.packageName); 6702 } 6703 // Check to see if this package could be hiding/updating a system 6704 // package. Must look for it either under the original or real 6705 // package name depending on our state. 6706 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6707 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6708 6709 // If this is a package we don't know about on the system partition, we 6710 // may need to remove disabled child packages on the system partition 6711 // or may need to not add child packages if the parent apk is updated 6712 // on the data partition and no longer defines this child package. 6713 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6714 // If this is a parent package for an updated system app and this system 6715 // app got an OTA update which no longer defines some of the child packages 6716 // we have to prune them from the disabled system packages. 6717 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6718 if (disabledPs != null) { 6719 final int scannedChildCount = (pkg.childPackages != null) 6720 ? pkg.childPackages.size() : 0; 6721 final int disabledChildCount = disabledPs.childPackageNames != null 6722 ? disabledPs.childPackageNames.size() : 0; 6723 for (int i = 0; i < disabledChildCount; i++) { 6724 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6725 boolean disabledPackageAvailable = false; 6726 for (int j = 0; j < scannedChildCount; j++) { 6727 PackageParser.Package childPkg = pkg.childPackages.get(j); 6728 if (childPkg.packageName.equals(disabledChildPackageName)) { 6729 disabledPackageAvailable = true; 6730 break; 6731 } 6732 } 6733 if (!disabledPackageAvailable) { 6734 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6735 } 6736 } 6737 } 6738 } 6739 } 6740 6741 boolean updatedPkgBetter = false; 6742 // First check if this is a system package that may involve an update 6743 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6744 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6745 // it needs to drop FLAG_PRIVILEGED. 6746 if (locationIsPrivileged(scanFile)) { 6747 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6748 } else { 6749 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6750 } 6751 6752 if (ps != null && !ps.codePath.equals(scanFile)) { 6753 // The path has changed from what was last scanned... check the 6754 // version of the new path against what we have stored to determine 6755 // what to do. 6756 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6757 if (pkg.mVersionCode <= ps.versionCode) { 6758 // The system package has been updated and the code path does not match 6759 // Ignore entry. Skip it. 6760 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6761 + " ignored: updated version " + ps.versionCode 6762 + " better than this " + pkg.mVersionCode); 6763 if (!updatedPkg.codePath.equals(scanFile)) { 6764 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6765 + ps.name + " changing from " + updatedPkg.codePathString 6766 + " to " + scanFile); 6767 updatedPkg.codePath = scanFile; 6768 updatedPkg.codePathString = scanFile.toString(); 6769 updatedPkg.resourcePath = scanFile; 6770 updatedPkg.resourcePathString = scanFile.toString(); 6771 } 6772 updatedPkg.pkg = pkg; 6773 updatedPkg.versionCode = pkg.mVersionCode; 6774 6775 // Update the disabled system child packages to point to the package too. 6776 final int childCount = updatedPkg.childPackageNames != null 6777 ? updatedPkg.childPackageNames.size() : 0; 6778 for (int i = 0; i < childCount; i++) { 6779 String childPackageName = updatedPkg.childPackageNames.get(i); 6780 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6781 childPackageName); 6782 if (updatedChildPkg != null) { 6783 updatedChildPkg.pkg = pkg; 6784 updatedChildPkg.versionCode = pkg.mVersionCode; 6785 } 6786 } 6787 6788 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6789 + scanFile + " ignored: updated version " + ps.versionCode 6790 + " better than this " + pkg.mVersionCode); 6791 } else { 6792 // The current app on the system partition is better than 6793 // what we have updated to on the data partition; switch 6794 // back to the system partition version. 6795 // At this point, its safely assumed that package installation for 6796 // apps in system partition will go through. If not there won't be a working 6797 // version of the app 6798 // writer 6799 synchronized (mPackages) { 6800 // Just remove the loaded entries from package lists. 6801 mPackages.remove(ps.name); 6802 } 6803 6804 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6805 + " reverting from " + ps.codePathString 6806 + ": new version " + pkg.mVersionCode 6807 + " better than installed " + ps.versionCode); 6808 6809 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6810 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6811 synchronized (mInstallLock) { 6812 args.cleanUpResourcesLI(); 6813 } 6814 synchronized (mPackages) { 6815 mSettings.enableSystemPackageLPw(ps.name); 6816 } 6817 updatedPkgBetter = true; 6818 } 6819 } 6820 } 6821 6822 if (updatedPkg != null) { 6823 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6824 // initially 6825 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6826 6827 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6828 // flag set initially 6829 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6830 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6831 } 6832 } 6833 6834 // Verify certificates against what was last scanned 6835 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6836 6837 /* 6838 * A new system app appeared, but we already had a non-system one of the 6839 * same name installed earlier. 6840 */ 6841 boolean shouldHideSystemApp = false; 6842 if (updatedPkg == null && ps != null 6843 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6844 /* 6845 * Check to make sure the signatures match first. If they don't, 6846 * wipe the installed application and its data. 6847 */ 6848 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6849 != PackageManager.SIGNATURE_MATCH) { 6850 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6851 + " signatures don't match existing userdata copy; removing"); 6852 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6853 "scanPackageInternalLI")) { 6854 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6855 } 6856 ps = null; 6857 } else { 6858 /* 6859 * If the newly-added system app is an older version than the 6860 * already installed version, hide it. It will be scanned later 6861 * and re-added like an update. 6862 */ 6863 if (pkg.mVersionCode <= ps.versionCode) { 6864 shouldHideSystemApp = true; 6865 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6866 + " but new version " + pkg.mVersionCode + " better than installed " 6867 + ps.versionCode + "; hiding system"); 6868 } else { 6869 /* 6870 * The newly found system app is a newer version that the 6871 * one previously installed. Simply remove the 6872 * already-installed application and replace it with our own 6873 * while keeping the application data. 6874 */ 6875 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6876 + " reverting from " + ps.codePathString + ": new version " 6877 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6878 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6879 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6880 synchronized (mInstallLock) { 6881 args.cleanUpResourcesLI(); 6882 } 6883 } 6884 } 6885 } 6886 6887 // The apk is forward locked (not public) if its code and resources 6888 // are kept in different files. (except for app in either system or 6889 // vendor path). 6890 // TODO grab this value from PackageSettings 6891 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6892 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6893 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6894 } 6895 } 6896 6897 // TODO: extend to support forward-locked splits 6898 String resourcePath = null; 6899 String baseResourcePath = null; 6900 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6901 if (ps != null && ps.resourcePathString != null) { 6902 resourcePath = ps.resourcePathString; 6903 baseResourcePath = ps.resourcePathString; 6904 } else { 6905 // Should not happen at all. Just log an error. 6906 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6907 } 6908 } else { 6909 resourcePath = pkg.codePath; 6910 baseResourcePath = pkg.baseCodePath; 6911 } 6912 6913 // Set application objects path explicitly. 6914 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6915 pkg.setApplicationInfoCodePath(pkg.codePath); 6916 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6917 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6918 pkg.setApplicationInfoResourcePath(resourcePath); 6919 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6920 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6921 6922 // Note that we invoke the following method only if we are about to unpack an application 6923 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6924 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6925 6926 /* 6927 * If the system app should be overridden by a previously installed 6928 * data, hide the system app now and let the /data/app scan pick it up 6929 * again. 6930 */ 6931 if (shouldHideSystemApp) { 6932 synchronized (mPackages) { 6933 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6934 } 6935 } 6936 6937 return scannedPkg; 6938 } 6939 6940 private static String fixProcessName(String defProcessName, 6941 String processName, int uid) { 6942 if (processName == null) { 6943 return defProcessName; 6944 } 6945 return processName; 6946 } 6947 6948 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6949 throws PackageManagerException { 6950 if (pkgSetting.signatures.mSignatures != null) { 6951 // Already existing package. Make sure signatures match 6952 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6953 == PackageManager.SIGNATURE_MATCH; 6954 if (!match) { 6955 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6956 == PackageManager.SIGNATURE_MATCH; 6957 } 6958 if (!match) { 6959 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6960 == PackageManager.SIGNATURE_MATCH; 6961 } 6962 if (!match) { 6963 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6964 + pkg.packageName + " signatures do not match the " 6965 + "previously installed version; ignoring!"); 6966 } 6967 } 6968 6969 // Check for shared user signatures 6970 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6971 // Already existing package. Make sure signatures match 6972 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6973 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6974 if (!match) { 6975 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6976 == PackageManager.SIGNATURE_MATCH; 6977 } 6978 if (!match) { 6979 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6980 == PackageManager.SIGNATURE_MATCH; 6981 } 6982 if (!match) { 6983 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6984 "Package " + pkg.packageName 6985 + " has no signatures that match those in shared user " 6986 + pkgSetting.sharedUser.name + "; ignoring!"); 6987 } 6988 } 6989 } 6990 6991 /** 6992 * Enforces that only the system UID or root's UID can call a method exposed 6993 * via Binder. 6994 * 6995 * @param message used as message if SecurityException is thrown 6996 * @throws SecurityException if the caller is not system or root 6997 */ 6998 private static final void enforceSystemOrRoot(String message) { 6999 final int uid = Binder.getCallingUid(); 7000 if (uid != Process.SYSTEM_UID && uid != 0) { 7001 throw new SecurityException(message); 7002 } 7003 } 7004 7005 @Override 7006 public void performFstrimIfNeeded() { 7007 enforceSystemOrRoot("Only the system can request fstrim"); 7008 7009 // Before everything else, see whether we need to fstrim. 7010 try { 7011 IMountService ms = PackageHelper.getMountService(); 7012 if (ms != null) { 7013 final boolean isUpgrade = isUpgrade(); 7014 boolean doTrim = isUpgrade; 7015 if (doTrim) { 7016 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7017 } else { 7018 final long interval = android.provider.Settings.Global.getLong( 7019 mContext.getContentResolver(), 7020 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7021 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7022 if (interval > 0) { 7023 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7024 if (timeSinceLast > interval) { 7025 doTrim = true; 7026 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7027 + "; running immediately"); 7028 } 7029 } 7030 } 7031 if (doTrim) { 7032 if (!isFirstBoot()) { 7033 try { 7034 ActivityManagerNative.getDefault().showBootMessage( 7035 mContext.getResources().getString( 7036 R.string.android_upgrading_fstrim), true); 7037 } catch (RemoteException e) { 7038 } 7039 } 7040 ms.runMaintenance(); 7041 } 7042 } else { 7043 Slog.e(TAG, "Mount service unavailable!"); 7044 } 7045 } catch (RemoteException e) { 7046 // Can't happen; MountService is local 7047 } 7048 } 7049 7050 @Override 7051 public void updatePackagesIfNeeded() { 7052 enforceSystemOrRoot("Only the system can request package update"); 7053 7054 // We need to re-extract after an OTA. 7055 boolean causeUpgrade = isUpgrade(); 7056 7057 // First boot or factory reset. 7058 // Note: we also handle devices that are upgrading to N right now as if it is their 7059 // first boot, as they do not have profile data. 7060 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7061 7062 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7063 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7064 7065 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7066 return; 7067 } 7068 7069 List<PackageParser.Package> pkgs; 7070 synchronized (mPackages) { 7071 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7072 } 7073 7074 UsageStatsManager usageMgr = 7075 (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 7076 7077 int curr = 0; 7078 int total = pkgs.size(); 7079 for (PackageParser.Package pkg : pkgs) { 7080 curr++; 7081 7082 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7083 if (DEBUG_DEXOPT) { 7084 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7085 } 7086 continue; 7087 } 7088 7089 if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) { 7090 if (DEBUG_DEXOPT) { 7091 Log.i(TAG, "Skipping update of of idle app " + pkg.packageName); 7092 } 7093 continue; 7094 } 7095 7096 if (DEBUG_DEXOPT) { 7097 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7098 } 7099 7100 if (!isFirstBoot()) { 7101 try { 7102 ActivityManagerNative.getDefault().showBootMessage( 7103 mContext.getResources().getString(R.string.android_upgrading_apk, 7104 curr, total), true); 7105 } catch (RemoteException e) { 7106 } 7107 } 7108 7109 performDexOpt(pkg.packageName, 7110 null /* instructionSet */, 7111 false /* checkProfiles */, 7112 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7113 false /* force */); 7114 } 7115 } 7116 7117 @Override 7118 public void notifyPackageUse(String packageName) { 7119 synchronized (mPackages) { 7120 PackageParser.Package p = mPackages.get(packageName); 7121 if (p == null) { 7122 return; 7123 } 7124 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7125 } 7126 } 7127 7128 // TODO: this is not used nor needed. Delete it. 7129 @Override 7130 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7131 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7132 getFullCompilerFilter(), false /* force */); 7133 } 7134 7135 @Override 7136 public boolean performDexOpt(String packageName, String instructionSet, 7137 boolean checkProfiles, int compileReason, boolean force) { 7138 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7139 getCompilerFilterForReason(compileReason), force); 7140 } 7141 7142 @Override 7143 public boolean performDexOptMode(String packageName, String instructionSet, 7144 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7145 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7146 targetCompilerFilter, force); 7147 } 7148 7149 private boolean performDexOptTraced(String packageName, String instructionSet, 7150 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7151 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7152 try { 7153 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7154 targetCompilerFilter, force); 7155 } finally { 7156 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7157 } 7158 } 7159 7160 private boolean performDexOptInternal(String packageName, String instructionSet, 7161 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7162 PackageParser.Package p; 7163 final String targetInstructionSet; 7164 synchronized (mPackages) { 7165 p = mPackages.get(packageName); 7166 if (p == null) { 7167 return false; 7168 } 7169 mPackageUsage.write(false); 7170 7171 targetInstructionSet = instructionSet != null ? instructionSet : 7172 getPrimaryInstructionSet(p.applicationInfo); 7173 } 7174 long callingId = Binder.clearCallingIdentity(); 7175 try { 7176 synchronized (mInstallLock) { 7177 final String[] instructionSets = new String[] { targetInstructionSet }; 7178 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7179 checkProfiles, targetCompilerFilter, force); 7180 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7181 } 7182 } finally { 7183 Binder.restoreCallingIdentity(callingId); 7184 } 7185 } 7186 7187 public ArraySet<String> getOptimizablePackages() { 7188 ArraySet<String> pkgs = new ArraySet<String>(); 7189 synchronized (mPackages) { 7190 for (PackageParser.Package p : mPackages.values()) { 7191 if (PackageDexOptimizer.canOptimizePackage(p)) { 7192 pkgs.add(p.packageName); 7193 } 7194 } 7195 } 7196 return pkgs; 7197 } 7198 7199 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7200 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7201 boolean force) { 7202 // Select the dex optimizer based on the force parameter. 7203 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7204 // allocate an object here. 7205 PackageDexOptimizer pdo = force 7206 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7207 : mPackageDexOptimizer; 7208 7209 // Optimize all dependencies first. Note: we ignore the return value and march on 7210 // on errors. 7211 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7212 if (!deps.isEmpty()) { 7213 for (PackageParser.Package depPackage : deps) { 7214 // TODO: Analyze and investigate if we (should) profile libraries. 7215 // Currently this will do a full compilation of the library by default. 7216 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7217 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7218 } 7219 } 7220 7221 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7222 } 7223 7224 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7225 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7226 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7227 Set<String> collectedNames = new HashSet<>(); 7228 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7229 7230 retValue.remove(p); 7231 7232 return retValue; 7233 } else { 7234 return Collections.emptyList(); 7235 } 7236 } 7237 7238 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7239 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7240 if (!collectedNames.contains(p.packageName)) { 7241 collectedNames.add(p.packageName); 7242 collected.add(p); 7243 7244 if (p.usesLibraries != null) { 7245 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7246 } 7247 if (p.usesOptionalLibraries != null) { 7248 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7249 collectedNames); 7250 } 7251 } 7252 } 7253 7254 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7255 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7256 for (String libName : libs) { 7257 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7258 if (libPkg != null) { 7259 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7260 } 7261 } 7262 } 7263 7264 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7265 synchronized (mPackages) { 7266 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7267 if (lib != null && lib.apk != null) { 7268 return mPackages.get(lib.apk); 7269 } 7270 } 7271 return null; 7272 } 7273 7274 public void shutdown() { 7275 mPackageUsage.write(true); 7276 } 7277 7278 @Override 7279 public void forceDexOpt(String packageName) { 7280 enforceSystemOrRoot("forceDexOpt"); 7281 7282 PackageParser.Package pkg; 7283 synchronized (mPackages) { 7284 pkg = mPackages.get(packageName); 7285 if (pkg == null) { 7286 throw new IllegalArgumentException("Unknown package: " + packageName); 7287 } 7288 } 7289 7290 synchronized (mInstallLock) { 7291 final String[] instructionSets = new String[] { 7292 getPrimaryInstructionSet(pkg.applicationInfo) }; 7293 7294 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7295 7296 // Whoever is calling forceDexOpt wants a fully compiled package. 7297 // Don't use profiles since that may cause compilation to be skipped. 7298 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7299 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7300 true /* force */); 7301 7302 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7303 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7304 throw new IllegalStateException("Failed to dexopt: " + res); 7305 } 7306 } 7307 } 7308 7309 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7310 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7311 Slog.w(TAG, "Unable to update from " + oldPkg.name 7312 + " to " + newPkg.packageName 7313 + ": old package not in system partition"); 7314 return false; 7315 } else if (mPackages.get(oldPkg.name) != null) { 7316 Slog.w(TAG, "Unable to update from " + oldPkg.name 7317 + " to " + newPkg.packageName 7318 + ": old package still exists"); 7319 return false; 7320 } 7321 return true; 7322 } 7323 7324 private boolean removeDataDirsLIF(String volumeUuid, String packageName) { 7325 // TODO: triage flags as part of 26466827 7326 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7327 7328 boolean res = true; 7329 final int[] userIds = sUserManager.getUserIds(); 7330 for (int userId : userIds) { 7331 try { 7332 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7333 } catch (InstallerException e) { 7334 Slog.w(TAG, "Failed to delete data directory", e); 7335 res = false; 7336 } 7337 } 7338 return res; 7339 } 7340 7341 void removeCodePathLI(File codePath) { 7342 if (codePath.isDirectory()) { 7343 try { 7344 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7345 } catch (InstallerException e) { 7346 Slog.w(TAG, "Failed to remove code path", e); 7347 } 7348 } else { 7349 codePath.delete(); 7350 } 7351 } 7352 7353 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7354 try (PackageFreezer freezer = freezePackage(packageName, "destroyAppDataLI")) { 7355 try { 7356 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7357 } catch (InstallerException e) { 7358 Slog.w(TAG, "Failed to destroy app data", e); 7359 } 7360 } 7361 } 7362 7363 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7364 int appId, String seinfo) { 7365 try { 7366 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7367 } catch (InstallerException e) { 7368 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7369 } 7370 } 7371 7372 private void deleteProfilesLIF(PackageParser.Package pkg, boolean destroy) { 7373 try { 7374 if (destroy) { 7375 mInstaller.destroyAppProfiles(pkg.packageName); 7376 } else { 7377 mInstaller.clearAppProfiles(pkg.packageName); 7378 } 7379 } catch (InstallerException ex) { 7380 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7381 } 7382 } 7383 7384 private void deleteCodeCacheDirsLIF(String volumeUuid, String packageName) { 7385 final PackageParser.Package pkg; 7386 synchronized (mPackages) { 7387 pkg = mPackages.get(packageName); 7388 } 7389 if (pkg == null) { 7390 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7391 return; 7392 } 7393 deleteCodeCacheDirsLIF(pkg); 7394 } 7395 7396 private void deleteCodeCacheDirsLIF(PackageParser.Package pkg) { 7397 // TODO: triage flags as part of 26466827 7398 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7399 7400 int[] users = sUserManager.getUserIds(); 7401 int res = 0; 7402 for (int user : users) { 7403 // Remove the parent code cache 7404 try { 7405 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7406 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7407 } catch (InstallerException e) { 7408 Slog.w(TAG, "Failed to delete code cache directory", e); 7409 } 7410 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7411 for (int i = 0; i < childCount; i++) { 7412 PackageParser.Package childPkg = pkg.childPackages.get(i); 7413 // Remove the child code cache 7414 try { 7415 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7416 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7417 } catch (InstallerException e) { 7418 Slog.w(TAG, "Failed to delete code cache directory", e); 7419 } 7420 } 7421 } 7422 } 7423 7424 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7425 long lastUpdateTime) { 7426 // Set parent install/update time 7427 PackageSetting ps = (PackageSetting) pkg.mExtras; 7428 if (ps != null) { 7429 ps.firstInstallTime = firstInstallTime; 7430 ps.lastUpdateTime = lastUpdateTime; 7431 } 7432 // Set children install/update time 7433 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7434 for (int i = 0; i < childCount; i++) { 7435 PackageParser.Package childPkg = pkg.childPackages.get(i); 7436 ps = (PackageSetting) childPkg.mExtras; 7437 if (ps != null) { 7438 ps.firstInstallTime = firstInstallTime; 7439 ps.lastUpdateTime = lastUpdateTime; 7440 } 7441 } 7442 } 7443 7444 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7445 PackageParser.Package changingLib) { 7446 if (file.path != null) { 7447 usesLibraryFiles.add(file.path); 7448 return; 7449 } 7450 PackageParser.Package p = mPackages.get(file.apk); 7451 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7452 // If we are doing this while in the middle of updating a library apk, 7453 // then we need to make sure to use that new apk for determining the 7454 // dependencies here. (We haven't yet finished committing the new apk 7455 // to the package manager state.) 7456 if (p == null || p.packageName.equals(changingLib.packageName)) { 7457 p = changingLib; 7458 } 7459 } 7460 if (p != null) { 7461 usesLibraryFiles.addAll(p.getAllCodePaths()); 7462 } 7463 } 7464 7465 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7466 PackageParser.Package changingLib) throws PackageManagerException { 7467 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7468 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7469 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7470 for (int i=0; i<N; i++) { 7471 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7472 if (file == null) { 7473 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7474 "Package " + pkg.packageName + " requires unavailable shared library " 7475 + pkg.usesLibraries.get(i) + "; failing!"); 7476 } 7477 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7478 } 7479 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7480 for (int i=0; i<N; i++) { 7481 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7482 if (file == null) { 7483 Slog.w(TAG, "Package " + pkg.packageName 7484 + " desires unavailable shared library " 7485 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7486 } else { 7487 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7488 } 7489 } 7490 N = usesLibraryFiles.size(); 7491 if (N > 0) { 7492 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7493 } else { 7494 pkg.usesLibraryFiles = null; 7495 } 7496 } 7497 } 7498 7499 private static boolean hasString(List<String> list, List<String> which) { 7500 if (list == null) { 7501 return false; 7502 } 7503 for (int i=list.size()-1; i>=0; i--) { 7504 for (int j=which.size()-1; j>=0; j--) { 7505 if (which.get(j).equals(list.get(i))) { 7506 return true; 7507 } 7508 } 7509 } 7510 return false; 7511 } 7512 7513 private void updateAllSharedLibrariesLPw() { 7514 for (PackageParser.Package pkg : mPackages.values()) { 7515 try { 7516 updateSharedLibrariesLPw(pkg, null); 7517 } catch (PackageManagerException e) { 7518 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7519 } 7520 } 7521 } 7522 7523 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7524 PackageParser.Package changingPkg) { 7525 ArrayList<PackageParser.Package> res = null; 7526 for (PackageParser.Package pkg : mPackages.values()) { 7527 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7528 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7529 if (res == null) { 7530 res = new ArrayList<PackageParser.Package>(); 7531 } 7532 res.add(pkg); 7533 try { 7534 updateSharedLibrariesLPw(pkg, changingPkg); 7535 } catch (PackageManagerException e) { 7536 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7537 } 7538 } 7539 } 7540 return res; 7541 } 7542 7543 /** 7544 * Derive the value of the {@code cpuAbiOverride} based on the provided 7545 * value and an optional stored value from the package settings. 7546 */ 7547 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7548 String cpuAbiOverride = null; 7549 7550 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7551 cpuAbiOverride = null; 7552 } else if (abiOverride != null) { 7553 cpuAbiOverride = abiOverride; 7554 } else if (settings != null) { 7555 cpuAbiOverride = settings.cpuAbiOverrideString; 7556 } 7557 7558 return cpuAbiOverride; 7559 } 7560 7561 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7562 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7563 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7564 // If the package has children and this is the first dive in the function 7565 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7566 // whether all packages (parent and children) would be successfully scanned 7567 // before the actual scan since scanning mutates internal state and we want 7568 // to atomically install the package and its children. 7569 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7570 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7571 scanFlags |= SCAN_CHECK_ONLY; 7572 } 7573 } else { 7574 scanFlags &= ~SCAN_CHECK_ONLY; 7575 } 7576 7577 final PackageParser.Package scannedPkg; 7578 try { 7579 // Scan the parent 7580 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7581 // Scan the children 7582 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7583 for (int i = 0; i < childCount; i++) { 7584 PackageParser.Package childPkg = pkg.childPackages.get(i); 7585 scanPackageLI(childPkg, parseFlags, 7586 scanFlags, currentTime, user); 7587 } 7588 } finally { 7589 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7590 } 7591 7592 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7593 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7594 } 7595 7596 return scannedPkg; 7597 } 7598 7599 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7600 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7601 boolean success = false; 7602 try { 7603 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7604 currentTime, user); 7605 success = true; 7606 return res; 7607 } finally { 7608 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7609 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7610 removeDataDirsLIF(pkg.volumeUuid, pkg.packageName); 7611 } 7612 } 7613 } 7614 7615 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7616 int scanFlags, long currentTime, UserHandle user) 7617 throws PackageManagerException { 7618 final File scanFile = new File(pkg.codePath); 7619 if (pkg.applicationInfo.getCodePath() == null || 7620 pkg.applicationInfo.getResourcePath() == null) { 7621 // Bail out. The resource and code paths haven't been set. 7622 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7623 "Code and resource paths haven't been set correctly"); 7624 } 7625 7626 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7627 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7628 } else { 7629 // Only allow system apps to be flagged as core apps. 7630 pkg.coreApp = false; 7631 } 7632 7633 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7634 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7635 } 7636 7637 if (mCustomResolverComponentName != null && 7638 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7639 setUpCustomResolverActivity(pkg); 7640 } 7641 7642 if (pkg.packageName.equals("android")) { 7643 synchronized (mPackages) { 7644 if (mAndroidApplication != null) { 7645 Slog.w(TAG, "*************************************************"); 7646 Slog.w(TAG, "Core android package being redefined. Skipping."); 7647 Slog.w(TAG, " file=" + scanFile); 7648 Slog.w(TAG, "*************************************************"); 7649 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7650 "Core android package being redefined. Skipping."); 7651 } 7652 7653 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7654 // Set up information for our fall-back user intent resolution activity. 7655 mPlatformPackage = pkg; 7656 pkg.mVersionCode = mSdkVersion; 7657 mAndroidApplication = pkg.applicationInfo; 7658 7659 if (!mResolverReplaced) { 7660 mResolveActivity.applicationInfo = mAndroidApplication; 7661 mResolveActivity.name = ResolverActivity.class.getName(); 7662 mResolveActivity.packageName = mAndroidApplication.packageName; 7663 mResolveActivity.processName = "system:ui"; 7664 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7665 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7666 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7667 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7668 mResolveActivity.exported = true; 7669 mResolveActivity.enabled = true; 7670 mResolveInfo.activityInfo = mResolveActivity; 7671 mResolveInfo.priority = 0; 7672 mResolveInfo.preferredOrder = 0; 7673 mResolveInfo.match = 0; 7674 mResolveComponentName = new ComponentName( 7675 mAndroidApplication.packageName, mResolveActivity.name); 7676 } 7677 } 7678 } 7679 } 7680 7681 if (DEBUG_PACKAGE_SCANNING) { 7682 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7683 Log.d(TAG, "Scanning package " + pkg.packageName); 7684 } 7685 7686 synchronized (mPackages) { 7687 if (mPackages.containsKey(pkg.packageName) 7688 || mSharedLibraries.containsKey(pkg.packageName)) { 7689 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7690 "Application package " + pkg.packageName 7691 + " already installed. Skipping duplicate."); 7692 } 7693 7694 // If we're only installing presumed-existing packages, require that the 7695 // scanned APK is both already known and at the path previously established 7696 // for it. Previously unknown packages we pick up normally, but if we have an 7697 // a priori expectation about this package's install presence, enforce it. 7698 // With a singular exception for new system packages. When an OTA contains 7699 // a new system package, we allow the codepath to change from a system location 7700 // to the user-installed location. If we don't allow this change, any newer, 7701 // user-installed version of the application will be ignored. 7702 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7703 if (mExpectingBetter.containsKey(pkg.packageName)) { 7704 logCriticalInfo(Log.WARN, 7705 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7706 } else { 7707 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7708 if (known != null) { 7709 if (DEBUG_PACKAGE_SCANNING) { 7710 Log.d(TAG, "Examining " + pkg.codePath 7711 + " and requiring known paths " + known.codePathString 7712 + " & " + known.resourcePathString); 7713 } 7714 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7715 || !pkg.applicationInfo.getResourcePath().equals( 7716 known.resourcePathString)) { 7717 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7718 "Application package " + pkg.packageName 7719 + " found at " + pkg.applicationInfo.getCodePath() 7720 + " but expected at " + known.codePathString 7721 + "; ignoring."); 7722 } 7723 } 7724 } 7725 } 7726 } 7727 7728 // Initialize package source and resource directories 7729 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7730 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7731 7732 SharedUserSetting suid = null; 7733 PackageSetting pkgSetting = null; 7734 7735 if (!isSystemApp(pkg)) { 7736 // Only system apps can use these features. 7737 pkg.mOriginalPackages = null; 7738 pkg.mRealPackage = null; 7739 pkg.mAdoptPermissions = null; 7740 } 7741 7742 // Getting the package setting may have a side-effect, so if we 7743 // are only checking if scan would succeed, stash a copy of the 7744 // old setting to restore at the end. 7745 PackageSetting nonMutatedPs = null; 7746 7747 // writer 7748 synchronized (mPackages) { 7749 if (pkg.mSharedUserId != null) { 7750 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7751 if (suid == null) { 7752 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7753 "Creating application package " + pkg.packageName 7754 + " for shared user failed"); 7755 } 7756 if (DEBUG_PACKAGE_SCANNING) { 7757 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7758 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7759 + "): packages=" + suid.packages); 7760 } 7761 } 7762 7763 // Check if we are renaming from an original package name. 7764 PackageSetting origPackage = null; 7765 String realName = null; 7766 if (pkg.mOriginalPackages != null) { 7767 // This package may need to be renamed to a previously 7768 // installed name. Let's check on that... 7769 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7770 if (pkg.mOriginalPackages.contains(renamed)) { 7771 // This package had originally been installed as the 7772 // original name, and we have already taken care of 7773 // transitioning to the new one. Just update the new 7774 // one to continue using the old name. 7775 realName = pkg.mRealPackage; 7776 if (!pkg.packageName.equals(renamed)) { 7777 // Callers into this function may have already taken 7778 // care of renaming the package; only do it here if 7779 // it is not already done. 7780 pkg.setPackageName(renamed); 7781 } 7782 7783 } else { 7784 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7785 if ((origPackage = mSettings.peekPackageLPr( 7786 pkg.mOriginalPackages.get(i))) != null) { 7787 // We do have the package already installed under its 7788 // original name... should we use it? 7789 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7790 // New package is not compatible with original. 7791 origPackage = null; 7792 continue; 7793 } else if (origPackage.sharedUser != null) { 7794 // Make sure uid is compatible between packages. 7795 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7796 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7797 + " to " + pkg.packageName + ": old uid " 7798 + origPackage.sharedUser.name 7799 + " differs from " + pkg.mSharedUserId); 7800 origPackage = null; 7801 continue; 7802 } 7803 } else { 7804 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7805 + pkg.packageName + " to old name " + origPackage.name); 7806 } 7807 break; 7808 } 7809 } 7810 } 7811 } 7812 7813 if (mTransferedPackages.contains(pkg.packageName)) { 7814 Slog.w(TAG, "Package " + pkg.packageName 7815 + " was transferred to another, but its .apk remains"); 7816 } 7817 7818 // See comments in nonMutatedPs declaration 7819 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7820 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7821 if (foundPs != null) { 7822 nonMutatedPs = new PackageSetting(foundPs); 7823 } 7824 } 7825 7826 // Just create the setting, don't add it yet. For already existing packages 7827 // the PkgSetting exists already and doesn't have to be created. 7828 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7829 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7830 pkg.applicationInfo.primaryCpuAbi, 7831 pkg.applicationInfo.secondaryCpuAbi, 7832 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7833 user, false); 7834 if (pkgSetting == null) { 7835 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7836 "Creating application package " + pkg.packageName + " failed"); 7837 } 7838 7839 if (pkgSetting.origPackage != null) { 7840 // If we are first transitioning from an original package, 7841 // fix up the new package's name now. We need to do this after 7842 // looking up the package under its new name, so getPackageLP 7843 // can take care of fiddling things correctly. 7844 pkg.setPackageName(origPackage.name); 7845 7846 // File a report about this. 7847 String msg = "New package " + pkgSetting.realName 7848 + " renamed to replace old package " + pkgSetting.name; 7849 reportSettingsProblem(Log.WARN, msg); 7850 7851 // Make a note of it. 7852 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7853 mTransferedPackages.add(origPackage.name); 7854 } 7855 7856 // No longer need to retain this. 7857 pkgSetting.origPackage = null; 7858 } 7859 7860 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7861 // Make a note of it. 7862 mTransferedPackages.add(pkg.packageName); 7863 } 7864 7865 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7866 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7867 } 7868 7869 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7870 // Check all shared libraries and map to their actual file path. 7871 // We only do this here for apps not on a system dir, because those 7872 // are the only ones that can fail an install due to this. We 7873 // will take care of the system apps by updating all of their 7874 // library paths after the scan is done. 7875 updateSharedLibrariesLPw(pkg, null); 7876 } 7877 7878 if (mFoundPolicyFile) { 7879 SELinuxMMAC.assignSeinfoValue(pkg); 7880 } 7881 7882 pkg.applicationInfo.uid = pkgSetting.appId; 7883 pkg.mExtras = pkgSetting; 7884 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7885 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7886 // We just determined the app is signed correctly, so bring 7887 // over the latest parsed certs. 7888 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7889 } else { 7890 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7891 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7892 "Package " + pkg.packageName + " upgrade keys do not match the " 7893 + "previously installed version"); 7894 } else { 7895 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7896 String msg = "System package " + pkg.packageName 7897 + " signature changed; retaining data."; 7898 reportSettingsProblem(Log.WARN, msg); 7899 } 7900 } 7901 } else { 7902 try { 7903 verifySignaturesLP(pkgSetting, pkg); 7904 // We just determined the app is signed correctly, so bring 7905 // over the latest parsed certs. 7906 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7907 } catch (PackageManagerException e) { 7908 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7909 throw e; 7910 } 7911 // The signature has changed, but this package is in the system 7912 // image... let's recover! 7913 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7914 // However... if this package is part of a shared user, but it 7915 // doesn't match the signature of the shared user, let's fail. 7916 // What this means is that you can't change the signatures 7917 // associated with an overall shared user, which doesn't seem all 7918 // that unreasonable. 7919 if (pkgSetting.sharedUser != null) { 7920 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7921 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7922 throw new PackageManagerException( 7923 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7924 "Signature mismatch for shared user: " 7925 + pkgSetting.sharedUser); 7926 } 7927 } 7928 // File a report about this. 7929 String msg = "System package " + pkg.packageName 7930 + " signature changed; retaining data."; 7931 reportSettingsProblem(Log.WARN, msg); 7932 } 7933 } 7934 // Verify that this new package doesn't have any content providers 7935 // that conflict with existing packages. Only do this if the 7936 // package isn't already installed, since we don't want to break 7937 // things that are installed. 7938 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7939 final int N = pkg.providers.size(); 7940 int i; 7941 for (i=0; i<N; i++) { 7942 PackageParser.Provider p = pkg.providers.get(i); 7943 if (p.info.authority != null) { 7944 String names[] = p.info.authority.split(";"); 7945 for (int j = 0; j < names.length; j++) { 7946 if (mProvidersByAuthority.containsKey(names[j])) { 7947 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7948 final String otherPackageName = 7949 ((other != null && other.getComponentName() != null) ? 7950 other.getComponentName().getPackageName() : "?"); 7951 throw new PackageManagerException( 7952 INSTALL_FAILED_CONFLICTING_PROVIDER, 7953 "Can't install because provider name " + names[j] 7954 + " (in package " + pkg.applicationInfo.packageName 7955 + ") is already used by " + otherPackageName); 7956 } 7957 } 7958 } 7959 } 7960 } 7961 7962 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7963 // This package wants to adopt ownership of permissions from 7964 // another package. 7965 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7966 final String origName = pkg.mAdoptPermissions.get(i); 7967 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7968 if (orig != null) { 7969 if (verifyPackageUpdateLPr(orig, pkg)) { 7970 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7971 + pkg.packageName); 7972 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7973 } 7974 } 7975 } 7976 } 7977 } 7978 7979 final String pkgName = pkg.packageName; 7980 7981 final long scanFileTime = scanFile.lastModified(); 7982 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7983 pkg.applicationInfo.processName = fixProcessName( 7984 pkg.applicationInfo.packageName, 7985 pkg.applicationInfo.processName, 7986 pkg.applicationInfo.uid); 7987 7988 if (pkg != mPlatformPackage) { 7989 // Get all of our default paths setup 7990 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7991 } 7992 7993 final String path = scanFile.getPath(); 7994 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7995 7996 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7997 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7998 7999 // Some system apps still use directory structure for native libraries 8000 // in which case we might end up not detecting abi solely based on apk 8001 // structure. Try to detect abi based on directory structure. 8002 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8003 pkg.applicationInfo.primaryCpuAbi == null) { 8004 setBundledAppAbisAndRoots(pkg, pkgSetting); 8005 setNativeLibraryPaths(pkg); 8006 } 8007 8008 } else { 8009 if ((scanFlags & SCAN_MOVE) != 0) { 8010 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8011 // but we already have this packages package info in the PackageSetting. We just 8012 // use that and derive the native library path based on the new codepath. 8013 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8014 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8015 } 8016 8017 // Set native library paths again. For moves, the path will be updated based on the 8018 // ABIs we've determined above. For non-moves, the path will be updated based on the 8019 // ABIs we determined during compilation, but the path will depend on the final 8020 // package path (after the rename away from the stage path). 8021 setNativeLibraryPaths(pkg); 8022 } 8023 8024 // This is a special case for the "system" package, where the ABI is 8025 // dictated by the zygote configuration (and init.rc). We should keep track 8026 // of this ABI so that we can deal with "normal" applications that run under 8027 // the same UID correctly. 8028 if (mPlatformPackage == pkg) { 8029 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8030 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8031 } 8032 8033 // If there's a mismatch between the abi-override in the package setting 8034 // and the abiOverride specified for the install. Warn about this because we 8035 // would've already compiled the app without taking the package setting into 8036 // account. 8037 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8038 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8039 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8040 " for package " + pkg.packageName); 8041 } 8042 } 8043 8044 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8045 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8046 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8047 8048 // Copy the derived override back to the parsed package, so that we can 8049 // update the package settings accordingly. 8050 pkg.cpuAbiOverride = cpuAbiOverride; 8051 8052 if (DEBUG_ABI_SELECTION) { 8053 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8054 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8055 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8056 } 8057 8058 // Push the derived path down into PackageSettings so we know what to 8059 // clean up at uninstall time. 8060 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8061 8062 if (DEBUG_ABI_SELECTION) { 8063 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8064 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8065 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8066 } 8067 8068 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8069 // We don't do this here during boot because we can do it all 8070 // at once after scanning all existing packages. 8071 // 8072 // We also do this *before* we perform dexopt on this package, so that 8073 // we can avoid redundant dexopts, and also to make sure we've got the 8074 // code and package path correct. 8075 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8076 pkg, true /* boot complete */); 8077 } 8078 8079 if (mFactoryTest && pkg.requestedPermissions.contains( 8080 android.Manifest.permission.FACTORY_TEST)) { 8081 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8082 } 8083 8084 ArrayList<PackageParser.Package> clientLibPkgs = null; 8085 8086 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8087 if (nonMutatedPs != null) { 8088 synchronized (mPackages) { 8089 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8090 } 8091 } 8092 return pkg; 8093 } 8094 8095 // Only privileged apps and updated privileged apps can add child packages. 8096 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8097 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8098 throw new PackageManagerException("Only privileged apps and updated " 8099 + "privileged apps can add child packages. Ignoring package " 8100 + pkg.packageName); 8101 } 8102 final int childCount = pkg.childPackages.size(); 8103 for (int i = 0; i < childCount; i++) { 8104 PackageParser.Package childPkg = pkg.childPackages.get(i); 8105 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8106 childPkg.packageName)) { 8107 throw new PackageManagerException("Cannot override a child package of " 8108 + "another disabled system app. Ignoring package " + pkg.packageName); 8109 } 8110 } 8111 } 8112 8113 // writer 8114 synchronized (mPackages) { 8115 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8116 // Only system apps can add new shared libraries. 8117 if (pkg.libraryNames != null) { 8118 for (int i=0; i<pkg.libraryNames.size(); i++) { 8119 String name = pkg.libraryNames.get(i); 8120 boolean allowed = false; 8121 if (pkg.isUpdatedSystemApp()) { 8122 // New library entries can only be added through the 8123 // system image. This is important to get rid of a lot 8124 // of nasty edge cases: for example if we allowed a non- 8125 // system update of the app to add a library, then uninstalling 8126 // the update would make the library go away, and assumptions 8127 // we made such as through app install filtering would now 8128 // have allowed apps on the device which aren't compatible 8129 // with it. Better to just have the restriction here, be 8130 // conservative, and create many fewer cases that can negatively 8131 // impact the user experience. 8132 final PackageSetting sysPs = mSettings 8133 .getDisabledSystemPkgLPr(pkg.packageName); 8134 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8135 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8136 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8137 allowed = true; 8138 break; 8139 } 8140 } 8141 } 8142 } else { 8143 allowed = true; 8144 } 8145 if (allowed) { 8146 if (!mSharedLibraries.containsKey(name)) { 8147 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8148 } else if (!name.equals(pkg.packageName)) { 8149 Slog.w(TAG, "Package " + pkg.packageName + " library " 8150 + name + " already exists; skipping"); 8151 } 8152 } else { 8153 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8154 + name + " that is not declared on system image; skipping"); 8155 } 8156 } 8157 if ((scanFlags & SCAN_BOOTING) == 0) { 8158 // If we are not booting, we need to update any applications 8159 // that are clients of our shared library. If we are booting, 8160 // this will all be done once the scan is complete. 8161 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8162 } 8163 } 8164 } 8165 } 8166 8167 if ((scanFlags & SCAN_BOOTING) != 0) { 8168 // No apps can run during boot scan, so they don't need to be frozen 8169 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8170 // Caller asked to not kill app, so it's probably not frozen 8171 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8172 // Caller asked us to ignore frozen check for some reason; they 8173 // probably didn't know the package name 8174 } else { 8175 // We're doing major surgery on this package, so it better be frozen 8176 // right now to keep it from launching 8177 checkPackageFrozen(pkgName); 8178 } 8179 8180 // Also need to kill any apps that are dependent on the library. 8181 if (clientLibPkgs != null) { 8182 for (int i=0; i<clientLibPkgs.size(); i++) { 8183 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8184 killApplication(clientPkg.applicationInfo.packageName, 8185 clientPkg.applicationInfo.uid, "update lib"); 8186 } 8187 } 8188 8189 // Make sure we're not adding any bogus keyset info 8190 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8191 ksms.assertScannedPackageValid(pkg); 8192 8193 // writer 8194 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8195 8196 boolean createIdmapFailed = false; 8197 synchronized (mPackages) { 8198 // We don't expect installation to fail beyond this point 8199 8200 // Add the new setting to mSettings 8201 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8202 // Add the new setting to mPackages 8203 mPackages.put(pkg.applicationInfo.packageName, pkg); 8204 // Make sure we don't accidentally delete its data. 8205 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8206 while (iter.hasNext()) { 8207 PackageCleanItem item = iter.next(); 8208 if (pkgName.equals(item.packageName)) { 8209 iter.remove(); 8210 } 8211 } 8212 8213 // Take care of first install / last update times. 8214 if (currentTime != 0) { 8215 if (pkgSetting.firstInstallTime == 0) { 8216 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8217 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8218 pkgSetting.lastUpdateTime = currentTime; 8219 } 8220 } else if (pkgSetting.firstInstallTime == 0) { 8221 // We need *something*. Take time time stamp of the file. 8222 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8223 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8224 if (scanFileTime != pkgSetting.timeStamp) { 8225 // A package on the system image has changed; consider this 8226 // to be an update. 8227 pkgSetting.lastUpdateTime = scanFileTime; 8228 } 8229 } 8230 8231 // Add the package's KeySets to the global KeySetManagerService 8232 ksms.addScannedPackageLPw(pkg); 8233 8234 int N = pkg.providers.size(); 8235 StringBuilder r = null; 8236 int i; 8237 for (i=0; i<N; i++) { 8238 PackageParser.Provider p = pkg.providers.get(i); 8239 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8240 p.info.processName, pkg.applicationInfo.uid); 8241 mProviders.addProvider(p); 8242 p.syncable = p.info.isSyncable; 8243 if (p.info.authority != null) { 8244 String names[] = p.info.authority.split(";"); 8245 p.info.authority = null; 8246 for (int j = 0; j < names.length; j++) { 8247 if (j == 1 && p.syncable) { 8248 // We only want the first authority for a provider to possibly be 8249 // syncable, so if we already added this provider using a different 8250 // authority clear the syncable flag. We copy the provider before 8251 // changing it because the mProviders object contains a reference 8252 // to a provider that we don't want to change. 8253 // Only do this for the second authority since the resulting provider 8254 // object can be the same for all future authorities for this provider. 8255 p = new PackageParser.Provider(p); 8256 p.syncable = false; 8257 } 8258 if (!mProvidersByAuthority.containsKey(names[j])) { 8259 mProvidersByAuthority.put(names[j], p); 8260 if (p.info.authority == null) { 8261 p.info.authority = names[j]; 8262 } else { 8263 p.info.authority = p.info.authority + ";" + names[j]; 8264 } 8265 if (DEBUG_PACKAGE_SCANNING) { 8266 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8267 Log.d(TAG, "Registered content provider: " + names[j] 8268 + ", className = " + p.info.name + ", isSyncable = " 8269 + p.info.isSyncable); 8270 } 8271 } else { 8272 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8273 Slog.w(TAG, "Skipping provider name " + names[j] + 8274 " (in package " + pkg.applicationInfo.packageName + 8275 "): name already used by " 8276 + ((other != null && other.getComponentName() != null) 8277 ? other.getComponentName().getPackageName() : "?")); 8278 } 8279 } 8280 } 8281 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8282 if (r == null) { 8283 r = new StringBuilder(256); 8284 } else { 8285 r.append(' '); 8286 } 8287 r.append(p.info.name); 8288 } 8289 } 8290 if (r != null) { 8291 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8292 } 8293 8294 N = pkg.services.size(); 8295 r = null; 8296 for (i=0; i<N; i++) { 8297 PackageParser.Service s = pkg.services.get(i); 8298 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8299 s.info.processName, pkg.applicationInfo.uid); 8300 mServices.addService(s); 8301 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8302 if (r == null) { 8303 r = new StringBuilder(256); 8304 } else { 8305 r.append(' '); 8306 } 8307 r.append(s.info.name); 8308 } 8309 } 8310 if (r != null) { 8311 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8312 } 8313 8314 N = pkg.receivers.size(); 8315 r = null; 8316 for (i=0; i<N; i++) { 8317 PackageParser.Activity a = pkg.receivers.get(i); 8318 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8319 a.info.processName, pkg.applicationInfo.uid); 8320 mReceivers.addActivity(a, "receiver"); 8321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8322 if (r == null) { 8323 r = new StringBuilder(256); 8324 } else { 8325 r.append(' '); 8326 } 8327 r.append(a.info.name); 8328 } 8329 } 8330 if (r != null) { 8331 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8332 } 8333 8334 N = pkg.activities.size(); 8335 r = null; 8336 for (i=0; i<N; i++) { 8337 PackageParser.Activity a = pkg.activities.get(i); 8338 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8339 a.info.processName, pkg.applicationInfo.uid); 8340 mActivities.addActivity(a, "activity"); 8341 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8342 if (r == null) { 8343 r = new StringBuilder(256); 8344 } else { 8345 r.append(' '); 8346 } 8347 r.append(a.info.name); 8348 } 8349 } 8350 if (r != null) { 8351 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8352 } 8353 8354 N = pkg.permissionGroups.size(); 8355 r = null; 8356 for (i=0; i<N; i++) { 8357 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8358 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8359 if (cur == null) { 8360 mPermissionGroups.put(pg.info.name, pg); 8361 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8362 if (r == null) { 8363 r = new StringBuilder(256); 8364 } else { 8365 r.append(' '); 8366 } 8367 r.append(pg.info.name); 8368 } 8369 } else { 8370 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8371 + pg.info.packageName + " ignored: original from " 8372 + cur.info.packageName); 8373 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8374 if (r == null) { 8375 r = new StringBuilder(256); 8376 } else { 8377 r.append(' '); 8378 } 8379 r.append("DUP:"); 8380 r.append(pg.info.name); 8381 } 8382 } 8383 } 8384 if (r != null) { 8385 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8386 } 8387 8388 N = pkg.permissions.size(); 8389 r = null; 8390 for (i=0; i<N; i++) { 8391 PackageParser.Permission p = pkg.permissions.get(i); 8392 8393 // Assume by default that we did not install this permission into the system. 8394 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8395 8396 // Now that permission groups have a special meaning, we ignore permission 8397 // groups for legacy apps to prevent unexpected behavior. In particular, 8398 // permissions for one app being granted to someone just becase they happen 8399 // to be in a group defined by another app (before this had no implications). 8400 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8401 p.group = mPermissionGroups.get(p.info.group); 8402 // Warn for a permission in an unknown group. 8403 if (p.info.group != null && p.group == null) { 8404 Slog.w(TAG, "Permission " + p.info.name + " from package " 8405 + p.info.packageName + " in an unknown group " + p.info.group); 8406 } 8407 } 8408 8409 ArrayMap<String, BasePermission> permissionMap = 8410 p.tree ? mSettings.mPermissionTrees 8411 : mSettings.mPermissions; 8412 BasePermission bp = permissionMap.get(p.info.name); 8413 8414 // Allow system apps to redefine non-system permissions 8415 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8416 final boolean currentOwnerIsSystem = (bp.perm != null 8417 && isSystemApp(bp.perm.owner)); 8418 if (isSystemApp(p.owner)) { 8419 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8420 // It's a built-in permission and no owner, take ownership now 8421 bp.packageSetting = pkgSetting; 8422 bp.perm = p; 8423 bp.uid = pkg.applicationInfo.uid; 8424 bp.sourcePackage = p.info.packageName; 8425 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8426 } else if (!currentOwnerIsSystem) { 8427 String msg = "New decl " + p.owner + " of permission " 8428 + p.info.name + " is system; overriding " + bp.sourcePackage; 8429 reportSettingsProblem(Log.WARN, msg); 8430 bp = null; 8431 } 8432 } 8433 } 8434 8435 if (bp == null) { 8436 bp = new BasePermission(p.info.name, p.info.packageName, 8437 BasePermission.TYPE_NORMAL); 8438 permissionMap.put(p.info.name, bp); 8439 } 8440 8441 if (bp.perm == null) { 8442 if (bp.sourcePackage == null 8443 || bp.sourcePackage.equals(p.info.packageName)) { 8444 BasePermission tree = findPermissionTreeLP(p.info.name); 8445 if (tree == null 8446 || tree.sourcePackage.equals(p.info.packageName)) { 8447 bp.packageSetting = pkgSetting; 8448 bp.perm = p; 8449 bp.uid = pkg.applicationInfo.uid; 8450 bp.sourcePackage = p.info.packageName; 8451 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8452 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8453 if (r == null) { 8454 r = new StringBuilder(256); 8455 } else { 8456 r.append(' '); 8457 } 8458 r.append(p.info.name); 8459 } 8460 } else { 8461 Slog.w(TAG, "Permission " + p.info.name + " from package " 8462 + p.info.packageName + " ignored: base tree " 8463 + tree.name + " is from package " 8464 + tree.sourcePackage); 8465 } 8466 } else { 8467 Slog.w(TAG, "Permission " + p.info.name + " from package " 8468 + p.info.packageName + " ignored: original from " 8469 + bp.sourcePackage); 8470 } 8471 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8472 if (r == null) { 8473 r = new StringBuilder(256); 8474 } else { 8475 r.append(' '); 8476 } 8477 r.append("DUP:"); 8478 r.append(p.info.name); 8479 } 8480 if (bp.perm == p) { 8481 bp.protectionLevel = p.info.protectionLevel; 8482 } 8483 } 8484 8485 if (r != null) { 8486 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8487 } 8488 8489 N = pkg.instrumentation.size(); 8490 r = null; 8491 for (i=0; i<N; i++) { 8492 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8493 a.info.packageName = pkg.applicationInfo.packageName; 8494 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8495 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8496 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8497 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8498 a.info.dataDir = pkg.applicationInfo.dataDir; 8499 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8500 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8501 8502 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8503 // need other information about the application, like the ABI and what not ? 8504 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8505 mInstrumentation.put(a.getComponentName(), a); 8506 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(a.info.name); 8513 } 8514 } 8515 if (r != null) { 8516 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8517 } 8518 8519 if (pkg.protectedBroadcasts != null) { 8520 N = pkg.protectedBroadcasts.size(); 8521 for (i=0; i<N; i++) { 8522 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8523 } 8524 } 8525 8526 pkgSetting.setTimeStamp(scanFileTime); 8527 8528 // Create idmap files for pairs of (packages, overlay packages). 8529 // Note: "android", ie framework-res.apk, is handled by native layers. 8530 if (pkg.mOverlayTarget != null) { 8531 // This is an overlay package. 8532 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8533 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8534 mOverlays.put(pkg.mOverlayTarget, 8535 new ArrayMap<String, PackageParser.Package>()); 8536 } 8537 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8538 map.put(pkg.packageName, pkg); 8539 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8540 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8541 createIdmapFailed = true; 8542 } 8543 } 8544 } else if (mOverlays.containsKey(pkg.packageName) && 8545 !pkg.packageName.equals("android")) { 8546 // This is a regular package, with one or more known overlay packages. 8547 createIdmapsForPackageLI(pkg); 8548 } 8549 } 8550 8551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8552 8553 if (createIdmapFailed) { 8554 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8555 "scanPackageLI failed to createIdmap"); 8556 } 8557 return pkg; 8558 } 8559 8560 /** 8561 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8562 * is derived purely on the basis of the contents of {@code scanFile} and 8563 * {@code cpuAbiOverride}. 8564 * 8565 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8566 */ 8567 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8568 String cpuAbiOverride, boolean extractLibs) 8569 throws PackageManagerException { 8570 // TODO: We can probably be smarter about this stuff. For installed apps, 8571 // we can calculate this information at install time once and for all. For 8572 // system apps, we can probably assume that this information doesn't change 8573 // after the first boot scan. As things stand, we do lots of unnecessary work. 8574 8575 // Give ourselves some initial paths; we'll come back for another 8576 // pass once we've determined ABI below. 8577 setNativeLibraryPaths(pkg); 8578 8579 // We would never need to extract libs for forward-locked and external packages, 8580 // since the container service will do it for us. We shouldn't attempt to 8581 // extract libs from system app when it was not updated. 8582 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8583 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8584 extractLibs = false; 8585 } 8586 8587 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8588 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8589 8590 NativeLibraryHelper.Handle handle = null; 8591 try { 8592 handle = NativeLibraryHelper.Handle.create(pkg); 8593 // TODO(multiArch): This can be null for apps that didn't go through the 8594 // usual installation process. We can calculate it again, like we 8595 // do during install time. 8596 // 8597 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8598 // unnecessary. 8599 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8600 8601 // Null out the abis so that they can be recalculated. 8602 pkg.applicationInfo.primaryCpuAbi = null; 8603 pkg.applicationInfo.secondaryCpuAbi = null; 8604 if (isMultiArch(pkg.applicationInfo)) { 8605 // Warn if we've set an abiOverride for multi-lib packages.. 8606 // By definition, we need to copy both 32 and 64 bit libraries for 8607 // such packages. 8608 if (pkg.cpuAbiOverride != null 8609 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8610 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8611 } 8612 8613 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8614 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8615 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8616 if (extractLibs) { 8617 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8618 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8619 useIsaSpecificSubdirs); 8620 } else { 8621 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8622 } 8623 } 8624 8625 maybeThrowExceptionForMultiArchCopy( 8626 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8627 8628 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8629 if (extractLibs) { 8630 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8631 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8632 useIsaSpecificSubdirs); 8633 } else { 8634 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8635 } 8636 } 8637 8638 maybeThrowExceptionForMultiArchCopy( 8639 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8640 8641 if (abi64 >= 0) { 8642 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8643 } 8644 8645 if (abi32 >= 0) { 8646 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8647 if (abi64 >= 0) { 8648 if (pkg.use32bitAbi) { 8649 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8650 pkg.applicationInfo.primaryCpuAbi = abi; 8651 } else { 8652 pkg.applicationInfo.secondaryCpuAbi = abi; 8653 } 8654 } else { 8655 pkg.applicationInfo.primaryCpuAbi = abi; 8656 } 8657 } 8658 8659 } else { 8660 String[] abiList = (cpuAbiOverride != null) ? 8661 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8662 8663 // Enable gross and lame hacks for apps that are built with old 8664 // SDK tools. We must scan their APKs for renderscript bitcode and 8665 // not launch them if it's present. Don't bother checking on devices 8666 // that don't have 64 bit support. 8667 boolean needsRenderScriptOverride = false; 8668 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8669 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8670 abiList = Build.SUPPORTED_32_BIT_ABIS; 8671 needsRenderScriptOverride = true; 8672 } 8673 8674 final int copyRet; 8675 if (extractLibs) { 8676 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8677 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8678 } else { 8679 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8680 } 8681 8682 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8683 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8684 "Error unpackaging native libs for app, errorCode=" + copyRet); 8685 } 8686 8687 if (copyRet >= 0) { 8688 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8689 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8690 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8691 } else if (needsRenderScriptOverride) { 8692 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8693 } 8694 } 8695 } catch (IOException ioe) { 8696 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8697 } finally { 8698 IoUtils.closeQuietly(handle); 8699 } 8700 8701 // Now that we've calculated the ABIs and determined if it's an internal app, 8702 // we will go ahead and populate the nativeLibraryPath. 8703 setNativeLibraryPaths(pkg); 8704 } 8705 8706 /** 8707 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8708 * i.e, so that all packages can be run inside a single process if required. 8709 * 8710 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8711 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8712 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8713 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8714 * updating a package that belongs to a shared user. 8715 * 8716 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8717 * adds unnecessary complexity. 8718 */ 8719 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8720 PackageParser.Package scannedPackage, boolean bootComplete) { 8721 String requiredInstructionSet = null; 8722 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8723 requiredInstructionSet = VMRuntime.getInstructionSet( 8724 scannedPackage.applicationInfo.primaryCpuAbi); 8725 } 8726 8727 PackageSetting requirer = null; 8728 for (PackageSetting ps : packagesForUser) { 8729 // If packagesForUser contains scannedPackage, we skip it. This will happen 8730 // when scannedPackage is an update of an existing package. Without this check, 8731 // we will never be able to change the ABI of any package belonging to a shared 8732 // user, even if it's compatible with other packages. 8733 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8734 if (ps.primaryCpuAbiString == null) { 8735 continue; 8736 } 8737 8738 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8739 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8740 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8741 // this but there's not much we can do. 8742 String errorMessage = "Instruction set mismatch, " 8743 + ((requirer == null) ? "[caller]" : requirer) 8744 + " requires " + requiredInstructionSet + " whereas " + ps 8745 + " requires " + instructionSet; 8746 Slog.w(TAG, errorMessage); 8747 } 8748 8749 if (requiredInstructionSet == null) { 8750 requiredInstructionSet = instructionSet; 8751 requirer = ps; 8752 } 8753 } 8754 } 8755 8756 if (requiredInstructionSet != null) { 8757 String adjustedAbi; 8758 if (requirer != null) { 8759 // requirer != null implies that either scannedPackage was null or that scannedPackage 8760 // did not require an ABI, in which case we have to adjust scannedPackage to match 8761 // the ABI of the set (which is the same as requirer's ABI) 8762 adjustedAbi = requirer.primaryCpuAbiString; 8763 if (scannedPackage != null) { 8764 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8765 } 8766 } else { 8767 // requirer == null implies that we're updating all ABIs in the set to 8768 // match scannedPackage. 8769 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8770 } 8771 8772 for (PackageSetting ps : packagesForUser) { 8773 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8774 if (ps.primaryCpuAbiString != null) { 8775 continue; 8776 } 8777 8778 ps.primaryCpuAbiString = adjustedAbi; 8779 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8780 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8781 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8782 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8783 + " (requirer=" 8784 + (requirer == null ? "null" : requirer.pkg.packageName) 8785 + ", scannedPackage=" 8786 + (scannedPackage != null ? scannedPackage.packageName : "null") 8787 + ")"); 8788 try { 8789 mInstaller.rmdex(ps.codePathString, 8790 getDexCodeInstructionSet(getPreferredInstructionSet())); 8791 } catch (InstallerException ignored) { 8792 } 8793 } 8794 } 8795 } 8796 } 8797 } 8798 8799 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8800 synchronized (mPackages) { 8801 mResolverReplaced = true; 8802 // Set up information for custom user intent resolution activity. 8803 mResolveActivity.applicationInfo = pkg.applicationInfo; 8804 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8805 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8806 mResolveActivity.processName = pkg.applicationInfo.packageName; 8807 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8808 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8809 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8810 mResolveActivity.theme = 0; 8811 mResolveActivity.exported = true; 8812 mResolveActivity.enabled = true; 8813 mResolveInfo.activityInfo = mResolveActivity; 8814 mResolveInfo.priority = 0; 8815 mResolveInfo.preferredOrder = 0; 8816 mResolveInfo.match = 0; 8817 mResolveComponentName = mCustomResolverComponentName; 8818 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8819 mResolveComponentName); 8820 } 8821 } 8822 8823 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8824 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8825 8826 // Set up information for ephemeral installer activity 8827 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8828 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8829 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8830 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8831 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8832 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8833 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8834 mEphemeralInstallerActivity.theme = 0; 8835 mEphemeralInstallerActivity.exported = true; 8836 mEphemeralInstallerActivity.enabled = true; 8837 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8838 mEphemeralInstallerInfo.priority = 0; 8839 mEphemeralInstallerInfo.preferredOrder = 0; 8840 mEphemeralInstallerInfo.match = 0; 8841 8842 if (DEBUG_EPHEMERAL) { 8843 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8844 } 8845 } 8846 8847 private static String calculateBundledApkRoot(final String codePathString) { 8848 final File codePath = new File(codePathString); 8849 final File codeRoot; 8850 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8851 codeRoot = Environment.getRootDirectory(); 8852 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8853 codeRoot = Environment.getOemDirectory(); 8854 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8855 codeRoot = Environment.getVendorDirectory(); 8856 } else { 8857 // Unrecognized code path; take its top real segment as the apk root: 8858 // e.g. /something/app/blah.apk => /something 8859 try { 8860 File f = codePath.getCanonicalFile(); 8861 File parent = f.getParentFile(); // non-null because codePath is a file 8862 File tmp; 8863 while ((tmp = parent.getParentFile()) != null) { 8864 f = parent; 8865 parent = tmp; 8866 } 8867 codeRoot = f; 8868 Slog.w(TAG, "Unrecognized code path " 8869 + codePath + " - using " + codeRoot); 8870 } catch (IOException e) { 8871 // Can't canonicalize the code path -- shenanigans? 8872 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8873 return Environment.getRootDirectory().getPath(); 8874 } 8875 } 8876 return codeRoot.getPath(); 8877 } 8878 8879 /** 8880 * Derive and set the location of native libraries for the given package, 8881 * which varies depending on where and how the package was installed. 8882 */ 8883 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8884 final ApplicationInfo info = pkg.applicationInfo; 8885 final String codePath = pkg.codePath; 8886 final File codeFile = new File(codePath); 8887 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8888 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8889 8890 info.nativeLibraryRootDir = null; 8891 info.nativeLibraryRootRequiresIsa = false; 8892 info.nativeLibraryDir = null; 8893 info.secondaryNativeLibraryDir = null; 8894 8895 if (isApkFile(codeFile)) { 8896 // Monolithic install 8897 if (bundledApp) { 8898 // If "/system/lib64/apkname" exists, assume that is the per-package 8899 // native library directory to use; otherwise use "/system/lib/apkname". 8900 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8901 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8902 getPrimaryInstructionSet(info)); 8903 8904 // This is a bundled system app so choose the path based on the ABI. 8905 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8906 // is just the default path. 8907 final String apkName = deriveCodePathName(codePath); 8908 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8909 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8910 apkName).getAbsolutePath(); 8911 8912 if (info.secondaryCpuAbi != null) { 8913 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8914 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8915 secondaryLibDir, apkName).getAbsolutePath(); 8916 } 8917 } else if (asecApp) { 8918 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8919 .getAbsolutePath(); 8920 } else { 8921 final String apkName = deriveCodePathName(codePath); 8922 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8923 .getAbsolutePath(); 8924 } 8925 8926 info.nativeLibraryRootRequiresIsa = false; 8927 info.nativeLibraryDir = info.nativeLibraryRootDir; 8928 } else { 8929 // Cluster install 8930 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8931 info.nativeLibraryRootRequiresIsa = true; 8932 8933 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8934 getPrimaryInstructionSet(info)).getAbsolutePath(); 8935 8936 if (info.secondaryCpuAbi != null) { 8937 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8938 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8939 } 8940 } 8941 } 8942 8943 /** 8944 * Calculate the abis and roots for a bundled app. These can uniquely 8945 * be determined from the contents of the system partition, i.e whether 8946 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8947 * of this information, and instead assume that the system was built 8948 * sensibly. 8949 */ 8950 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8951 PackageSetting pkgSetting) { 8952 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8953 8954 // If "/system/lib64/apkname" exists, assume that is the per-package 8955 // native library directory to use; otherwise use "/system/lib/apkname". 8956 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8957 setBundledAppAbi(pkg, apkRoot, apkName); 8958 // pkgSetting might be null during rescan following uninstall of updates 8959 // to a bundled app, so accommodate that possibility. The settings in 8960 // that case will be established later from the parsed package. 8961 // 8962 // If the settings aren't null, sync them up with what we've just derived. 8963 // note that apkRoot isn't stored in the package settings. 8964 if (pkgSetting != null) { 8965 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8966 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8967 } 8968 } 8969 8970 /** 8971 * Deduces the ABI of a bundled app and sets the relevant fields on the 8972 * parsed pkg object. 8973 * 8974 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8975 * under which system libraries are installed. 8976 * @param apkName the name of the installed package. 8977 */ 8978 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8979 final File codeFile = new File(pkg.codePath); 8980 8981 final boolean has64BitLibs; 8982 final boolean has32BitLibs; 8983 if (isApkFile(codeFile)) { 8984 // Monolithic install 8985 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8986 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8987 } else { 8988 // Cluster install 8989 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8990 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8991 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8992 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8993 has64BitLibs = (new File(rootDir, isa)).exists(); 8994 } else { 8995 has64BitLibs = false; 8996 } 8997 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8998 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8999 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9000 has32BitLibs = (new File(rootDir, isa)).exists(); 9001 } else { 9002 has32BitLibs = false; 9003 } 9004 } 9005 9006 if (has64BitLibs && !has32BitLibs) { 9007 // The package has 64 bit libs, but not 32 bit libs. Its primary 9008 // ABI should be 64 bit. We can safely assume here that the bundled 9009 // native libraries correspond to the most preferred ABI in the list. 9010 9011 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9012 pkg.applicationInfo.secondaryCpuAbi = null; 9013 } else if (has32BitLibs && !has64BitLibs) { 9014 // The package has 32 bit libs but not 64 bit libs. Its primary 9015 // ABI should be 32 bit. 9016 9017 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9018 pkg.applicationInfo.secondaryCpuAbi = null; 9019 } else if (has32BitLibs && has64BitLibs) { 9020 // The application has both 64 and 32 bit bundled libraries. We check 9021 // here that the app declares multiArch support, and warn if it doesn't. 9022 // 9023 // We will be lenient here and record both ABIs. The primary will be the 9024 // ABI that's higher on the list, i.e, a device that's configured to prefer 9025 // 64 bit apps will see a 64 bit primary ABI, 9026 9027 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9028 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9029 } 9030 9031 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9032 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9033 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9034 } else { 9035 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9036 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9037 } 9038 } else { 9039 pkg.applicationInfo.primaryCpuAbi = null; 9040 pkg.applicationInfo.secondaryCpuAbi = null; 9041 } 9042 } 9043 9044 private void killApplication(String pkgName, int appId, String reason) { 9045 // Request the ActivityManager to kill the process(only for existing packages) 9046 // so that we do not end up in a confused state while the user is still using the older 9047 // version of the application while the new one gets installed. 9048 final long token = Binder.clearCallingIdentity(); 9049 try { 9050 IActivityManager am = ActivityManagerNative.getDefault(); 9051 if (am != null) { 9052 try { 9053 am.killApplicationWithAppId(pkgName, appId, reason); 9054 } catch (RemoteException e) { 9055 } 9056 } 9057 } finally { 9058 Binder.restoreCallingIdentity(token); 9059 } 9060 } 9061 9062 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9063 // Remove the parent package setting 9064 PackageSetting ps = (PackageSetting) pkg.mExtras; 9065 if (ps != null) { 9066 removePackageLI(ps, chatty); 9067 } 9068 // Remove the child package setting 9069 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9070 for (int i = 0; i < childCount; i++) { 9071 PackageParser.Package childPkg = pkg.childPackages.get(i); 9072 ps = (PackageSetting) childPkg.mExtras; 9073 if (ps != null) { 9074 removePackageLI(ps, chatty); 9075 } 9076 } 9077 } 9078 9079 void removePackageLI(PackageSetting ps, boolean chatty) { 9080 if (DEBUG_INSTALL) { 9081 if (chatty) 9082 Log.d(TAG, "Removing package " + ps.name); 9083 } 9084 9085 // writer 9086 synchronized (mPackages) { 9087 mPackages.remove(ps.name); 9088 final PackageParser.Package pkg = ps.pkg; 9089 if (pkg != null) { 9090 cleanPackageDataStructuresLILPw(pkg, chatty); 9091 } 9092 } 9093 } 9094 9095 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9096 if (DEBUG_INSTALL) { 9097 if (chatty) 9098 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9099 } 9100 9101 // writer 9102 synchronized (mPackages) { 9103 // Remove the parent package 9104 mPackages.remove(pkg.applicationInfo.packageName); 9105 cleanPackageDataStructuresLILPw(pkg, chatty); 9106 9107 // Remove the child packages 9108 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9109 for (int i = 0; i < childCount; i++) { 9110 PackageParser.Package childPkg = pkg.childPackages.get(i); 9111 mPackages.remove(childPkg.applicationInfo.packageName); 9112 cleanPackageDataStructuresLILPw(childPkg, chatty); 9113 } 9114 } 9115 } 9116 9117 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9118 int N = pkg.providers.size(); 9119 StringBuilder r = null; 9120 int i; 9121 for (i=0; i<N; i++) { 9122 PackageParser.Provider p = pkg.providers.get(i); 9123 mProviders.removeProvider(p); 9124 if (p.info.authority == null) { 9125 9126 /* There was another ContentProvider with this authority when 9127 * this app was installed so this authority is null, 9128 * Ignore it as we don't have to unregister the provider. 9129 */ 9130 continue; 9131 } 9132 String names[] = p.info.authority.split(";"); 9133 for (int j = 0; j < names.length; j++) { 9134 if (mProvidersByAuthority.get(names[j]) == p) { 9135 mProvidersByAuthority.remove(names[j]); 9136 if (DEBUG_REMOVE) { 9137 if (chatty) 9138 Log.d(TAG, "Unregistered content provider: " + names[j] 9139 + ", className = " + p.info.name + ", isSyncable = " 9140 + p.info.isSyncable); 9141 } 9142 } 9143 } 9144 if (DEBUG_REMOVE && chatty) { 9145 if (r == null) { 9146 r = new StringBuilder(256); 9147 } else { 9148 r.append(' '); 9149 } 9150 r.append(p.info.name); 9151 } 9152 } 9153 if (r != null) { 9154 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9155 } 9156 9157 N = pkg.services.size(); 9158 r = null; 9159 for (i=0; i<N; i++) { 9160 PackageParser.Service s = pkg.services.get(i); 9161 mServices.removeService(s); 9162 if (chatty) { 9163 if (r == null) { 9164 r = new StringBuilder(256); 9165 } else { 9166 r.append(' '); 9167 } 9168 r.append(s.info.name); 9169 } 9170 } 9171 if (r != null) { 9172 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9173 } 9174 9175 N = pkg.receivers.size(); 9176 r = null; 9177 for (i=0; i<N; i++) { 9178 PackageParser.Activity a = pkg.receivers.get(i); 9179 mReceivers.removeActivity(a, "receiver"); 9180 if (DEBUG_REMOVE && chatty) { 9181 if (r == null) { 9182 r = new StringBuilder(256); 9183 } else { 9184 r.append(' '); 9185 } 9186 r.append(a.info.name); 9187 } 9188 } 9189 if (r != null) { 9190 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9191 } 9192 9193 N = pkg.activities.size(); 9194 r = null; 9195 for (i=0; i<N; i++) { 9196 PackageParser.Activity a = pkg.activities.get(i); 9197 mActivities.removeActivity(a, "activity"); 9198 if (DEBUG_REMOVE && chatty) { 9199 if (r == null) { 9200 r = new StringBuilder(256); 9201 } else { 9202 r.append(' '); 9203 } 9204 r.append(a.info.name); 9205 } 9206 } 9207 if (r != null) { 9208 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9209 } 9210 9211 N = pkg.permissions.size(); 9212 r = null; 9213 for (i=0; i<N; i++) { 9214 PackageParser.Permission p = pkg.permissions.get(i); 9215 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9216 if (bp == null) { 9217 bp = mSettings.mPermissionTrees.get(p.info.name); 9218 } 9219 if (bp != null && bp.perm == p) { 9220 bp.perm = null; 9221 if (DEBUG_REMOVE && chatty) { 9222 if (r == null) { 9223 r = new StringBuilder(256); 9224 } else { 9225 r.append(' '); 9226 } 9227 r.append(p.info.name); 9228 } 9229 } 9230 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9231 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9232 if (appOpPkgs != null) { 9233 appOpPkgs.remove(pkg.packageName); 9234 } 9235 } 9236 } 9237 if (r != null) { 9238 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9239 } 9240 9241 N = pkg.requestedPermissions.size(); 9242 r = null; 9243 for (i=0; i<N; i++) { 9244 String perm = pkg.requestedPermissions.get(i); 9245 BasePermission bp = mSettings.mPermissions.get(perm); 9246 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9247 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9248 if (appOpPkgs != null) { 9249 appOpPkgs.remove(pkg.packageName); 9250 if (appOpPkgs.isEmpty()) { 9251 mAppOpPermissionPackages.remove(perm); 9252 } 9253 } 9254 } 9255 } 9256 if (r != null) { 9257 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9258 } 9259 9260 N = pkg.instrumentation.size(); 9261 r = null; 9262 for (i=0; i<N; i++) { 9263 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9264 mInstrumentation.remove(a.getComponentName()); 9265 if (DEBUG_REMOVE && chatty) { 9266 if (r == null) { 9267 r = new StringBuilder(256); 9268 } else { 9269 r.append(' '); 9270 } 9271 r.append(a.info.name); 9272 } 9273 } 9274 if (r != null) { 9275 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9276 } 9277 9278 r = null; 9279 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9280 // Only system apps can hold shared libraries. 9281 if (pkg.libraryNames != null) { 9282 for (i=0; i<pkg.libraryNames.size(); i++) { 9283 String name = pkg.libraryNames.get(i); 9284 SharedLibraryEntry cur = mSharedLibraries.get(name); 9285 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9286 mSharedLibraries.remove(name); 9287 if (DEBUG_REMOVE && chatty) { 9288 if (r == null) { 9289 r = new StringBuilder(256); 9290 } else { 9291 r.append(' '); 9292 } 9293 r.append(name); 9294 } 9295 } 9296 } 9297 } 9298 } 9299 if (r != null) { 9300 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9301 } 9302 } 9303 9304 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9305 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9306 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9307 return true; 9308 } 9309 } 9310 return false; 9311 } 9312 9313 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9314 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9315 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9316 9317 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9318 // Update the parent permissions 9319 updatePermissionsLPw(pkg.packageName, pkg, flags); 9320 // Update the child permissions 9321 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9322 for (int i = 0; i < childCount; i++) { 9323 PackageParser.Package childPkg = pkg.childPackages.get(i); 9324 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9325 } 9326 } 9327 9328 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9329 int flags) { 9330 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9331 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9332 } 9333 9334 private void updatePermissionsLPw(String changingPkg, 9335 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9336 // Make sure there are no dangling permission trees. 9337 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9338 while (it.hasNext()) { 9339 final BasePermission bp = it.next(); 9340 if (bp.packageSetting == null) { 9341 // We may not yet have parsed the package, so just see if 9342 // we still know about its settings. 9343 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9344 } 9345 if (bp.packageSetting == null) { 9346 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9347 + " from package " + bp.sourcePackage); 9348 it.remove(); 9349 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9350 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9351 Slog.i(TAG, "Removing old permission tree: " + bp.name 9352 + " from package " + bp.sourcePackage); 9353 flags |= UPDATE_PERMISSIONS_ALL; 9354 it.remove(); 9355 } 9356 } 9357 } 9358 9359 // Make sure all dynamic permissions have been assigned to a package, 9360 // and make sure there are no dangling permissions. 9361 it = mSettings.mPermissions.values().iterator(); 9362 while (it.hasNext()) { 9363 final BasePermission bp = it.next(); 9364 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9365 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9366 + bp.name + " pkg=" + bp.sourcePackage 9367 + " info=" + bp.pendingInfo); 9368 if (bp.packageSetting == null && bp.pendingInfo != null) { 9369 final BasePermission tree = findPermissionTreeLP(bp.name); 9370 if (tree != null && tree.perm != null) { 9371 bp.packageSetting = tree.packageSetting; 9372 bp.perm = new PackageParser.Permission(tree.perm.owner, 9373 new PermissionInfo(bp.pendingInfo)); 9374 bp.perm.info.packageName = tree.perm.info.packageName; 9375 bp.perm.info.name = bp.name; 9376 bp.uid = tree.uid; 9377 } 9378 } 9379 } 9380 if (bp.packageSetting == null) { 9381 // We may not yet have parsed the package, so just see if 9382 // we still know about its settings. 9383 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9384 } 9385 if (bp.packageSetting == null) { 9386 Slog.w(TAG, "Removing dangling permission: " + bp.name 9387 + " from package " + bp.sourcePackage); 9388 it.remove(); 9389 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9390 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9391 Slog.i(TAG, "Removing old permission: " + bp.name 9392 + " from package " + bp.sourcePackage); 9393 flags |= UPDATE_PERMISSIONS_ALL; 9394 it.remove(); 9395 } 9396 } 9397 } 9398 9399 // Now update the permissions for all packages, in particular 9400 // replace the granted permissions of the system packages. 9401 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9402 for (PackageParser.Package pkg : mPackages.values()) { 9403 if (pkg != pkgInfo) { 9404 // Only replace for packages on requested volume 9405 final String volumeUuid = getVolumeUuidForPackage(pkg); 9406 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9407 && Objects.equals(replaceVolumeUuid, volumeUuid); 9408 grantPermissionsLPw(pkg, replace, changingPkg); 9409 } 9410 } 9411 } 9412 9413 if (pkgInfo != null) { 9414 // Only replace for packages on requested volume 9415 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9416 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9417 && Objects.equals(replaceVolumeUuid, volumeUuid); 9418 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9419 } 9420 } 9421 9422 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9423 String packageOfInterest) { 9424 // IMPORTANT: There are two types of permissions: install and runtime. 9425 // Install time permissions are granted when the app is installed to 9426 // all device users and users added in the future. Runtime permissions 9427 // are granted at runtime explicitly to specific users. Normal and signature 9428 // protected permissions are install time permissions. Dangerous permissions 9429 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9430 // otherwise they are runtime permissions. This function does not manage 9431 // runtime permissions except for the case an app targeting Lollipop MR1 9432 // being upgraded to target a newer SDK, in which case dangerous permissions 9433 // are transformed from install time to runtime ones. 9434 9435 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9436 if (ps == null) { 9437 return; 9438 } 9439 9440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9441 9442 PermissionsState permissionsState = ps.getPermissionsState(); 9443 PermissionsState origPermissions = permissionsState; 9444 9445 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9446 9447 boolean runtimePermissionsRevoked = false; 9448 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9449 9450 boolean changedInstallPermission = false; 9451 9452 if (replace) { 9453 ps.installPermissionsFixed = false; 9454 if (!ps.isSharedUser()) { 9455 origPermissions = new PermissionsState(permissionsState); 9456 permissionsState.reset(); 9457 } else { 9458 // We need to know only about runtime permission changes since the 9459 // calling code always writes the install permissions state but 9460 // the runtime ones are written only if changed. The only cases of 9461 // changed runtime permissions here are promotion of an install to 9462 // runtime and revocation of a runtime from a shared user. 9463 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9464 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9465 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9466 runtimePermissionsRevoked = true; 9467 } 9468 } 9469 } 9470 9471 permissionsState.setGlobalGids(mGlobalGids); 9472 9473 final int N = pkg.requestedPermissions.size(); 9474 for (int i=0; i<N; i++) { 9475 final String name = pkg.requestedPermissions.get(i); 9476 final BasePermission bp = mSettings.mPermissions.get(name); 9477 9478 if (DEBUG_INSTALL) { 9479 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9480 } 9481 9482 if (bp == null || bp.packageSetting == null) { 9483 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9484 Slog.w(TAG, "Unknown permission " + name 9485 + " in package " + pkg.packageName); 9486 } 9487 continue; 9488 } 9489 9490 final String perm = bp.name; 9491 boolean allowedSig = false; 9492 int grant = GRANT_DENIED; 9493 9494 // Keep track of app op permissions. 9495 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9496 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9497 if (pkgs == null) { 9498 pkgs = new ArraySet<>(); 9499 mAppOpPermissionPackages.put(bp.name, pkgs); 9500 } 9501 pkgs.add(pkg.packageName); 9502 } 9503 9504 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9505 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9506 >= Build.VERSION_CODES.M; 9507 switch (level) { 9508 case PermissionInfo.PROTECTION_NORMAL: { 9509 // For all apps normal permissions are install time ones. 9510 grant = GRANT_INSTALL; 9511 } break; 9512 9513 case PermissionInfo.PROTECTION_DANGEROUS: { 9514 // If a permission review is required for legacy apps we represent 9515 // their permissions as always granted runtime ones since we need 9516 // to keep the review required permission flag per user while an 9517 // install permission's state is shared across all users. 9518 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9519 // For legacy apps dangerous permissions are install time ones. 9520 grant = GRANT_INSTALL; 9521 } else if (origPermissions.hasInstallPermission(bp.name)) { 9522 // For legacy apps that became modern, install becomes runtime. 9523 grant = GRANT_UPGRADE; 9524 } else if (mPromoteSystemApps 9525 && isSystemApp(ps) 9526 && mExistingSystemPackages.contains(ps.name)) { 9527 // For legacy system apps, install becomes runtime. 9528 // We cannot check hasInstallPermission() for system apps since those 9529 // permissions were granted implicitly and not persisted pre-M. 9530 grant = GRANT_UPGRADE; 9531 } else { 9532 // For modern apps keep runtime permissions unchanged. 9533 grant = GRANT_RUNTIME; 9534 } 9535 } break; 9536 9537 case PermissionInfo.PROTECTION_SIGNATURE: { 9538 // For all apps signature permissions are install time ones. 9539 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9540 if (allowedSig) { 9541 grant = GRANT_INSTALL; 9542 } 9543 } break; 9544 } 9545 9546 if (DEBUG_INSTALL) { 9547 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9548 } 9549 9550 if (grant != GRANT_DENIED) { 9551 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9552 // If this is an existing, non-system package, then 9553 // we can't add any new permissions to it. 9554 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9555 // Except... if this is a permission that was added 9556 // to the platform (note: need to only do this when 9557 // updating the platform). 9558 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9559 grant = GRANT_DENIED; 9560 } 9561 } 9562 } 9563 9564 switch (grant) { 9565 case GRANT_INSTALL: { 9566 // Revoke this as runtime permission to handle the case of 9567 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9568 for (int userId : UserManagerService.getInstance().getUserIds()) { 9569 if (origPermissions.getRuntimePermissionState( 9570 bp.name, userId) != null) { 9571 // Revoke the runtime permission and clear the flags. 9572 origPermissions.revokeRuntimePermission(bp, userId); 9573 origPermissions.updatePermissionFlags(bp, userId, 9574 PackageManager.MASK_PERMISSION_FLAGS, 0); 9575 // If we revoked a permission permission, we have to write. 9576 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9577 changedRuntimePermissionUserIds, userId); 9578 } 9579 } 9580 // Grant an install permission. 9581 if (permissionsState.grantInstallPermission(bp) != 9582 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9583 changedInstallPermission = true; 9584 } 9585 } break; 9586 9587 case GRANT_RUNTIME: { 9588 // Grant previously granted runtime permissions. 9589 for (int userId : UserManagerService.getInstance().getUserIds()) { 9590 PermissionState permissionState = origPermissions 9591 .getRuntimePermissionState(bp.name, userId); 9592 int flags = permissionState != null 9593 ? permissionState.getFlags() : 0; 9594 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9595 if (permissionsState.grantRuntimePermission(bp, userId) == 9596 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9597 // If we cannot put the permission as it was, we have to write. 9598 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9599 changedRuntimePermissionUserIds, userId); 9600 } 9601 // If the app supports runtime permissions no need for a review. 9602 if (Build.PERMISSIONS_REVIEW_REQUIRED 9603 && appSupportsRuntimePermissions 9604 && (flags & PackageManager 9605 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9606 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9607 // Since we changed the flags, we have to write. 9608 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9609 changedRuntimePermissionUserIds, userId); 9610 } 9611 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9612 && !appSupportsRuntimePermissions) { 9613 // For legacy apps that need a permission review, every new 9614 // runtime permission is granted but it is pending a review. 9615 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9616 permissionsState.grantRuntimePermission(bp, userId); 9617 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9618 // We changed the permission and flags, hence have to write. 9619 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9620 changedRuntimePermissionUserIds, userId); 9621 } 9622 } 9623 // Propagate the permission flags. 9624 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9625 } 9626 } break; 9627 9628 case GRANT_UPGRADE: { 9629 // Grant runtime permissions for a previously held install permission. 9630 PermissionState permissionState = origPermissions 9631 .getInstallPermissionState(bp.name); 9632 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9633 9634 if (origPermissions.revokeInstallPermission(bp) 9635 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9636 // We will be transferring the permission flags, so clear them. 9637 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9638 PackageManager.MASK_PERMISSION_FLAGS, 0); 9639 changedInstallPermission = true; 9640 } 9641 9642 // If the permission is not to be promoted to runtime we ignore it and 9643 // also its other flags as they are not applicable to install permissions. 9644 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9645 for (int userId : currentUserIds) { 9646 if (permissionsState.grantRuntimePermission(bp, userId) != 9647 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9648 // Transfer the permission flags. 9649 permissionsState.updatePermissionFlags(bp, userId, 9650 flags, flags); 9651 // If we granted the permission, we have to write. 9652 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9653 changedRuntimePermissionUserIds, userId); 9654 } 9655 } 9656 } 9657 } break; 9658 9659 default: { 9660 if (packageOfInterest == null 9661 || packageOfInterest.equals(pkg.packageName)) { 9662 Slog.w(TAG, "Not granting permission " + perm 9663 + " to package " + pkg.packageName 9664 + " because it was previously installed without"); 9665 } 9666 } break; 9667 } 9668 } else { 9669 if (permissionsState.revokeInstallPermission(bp) != 9670 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9671 // Also drop the permission flags. 9672 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9673 PackageManager.MASK_PERMISSION_FLAGS, 0); 9674 changedInstallPermission = true; 9675 Slog.i(TAG, "Un-granting permission " + perm 9676 + " from package " + pkg.packageName 9677 + " (protectionLevel=" + bp.protectionLevel 9678 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9679 + ")"); 9680 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9681 // Don't print warning for app op permissions, since it is fine for them 9682 // not to be granted, there is a UI for the user to decide. 9683 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9684 Slog.w(TAG, "Not granting permission " + perm 9685 + " to package " + pkg.packageName 9686 + " (protectionLevel=" + bp.protectionLevel 9687 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9688 + ")"); 9689 } 9690 } 9691 } 9692 } 9693 9694 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9695 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9696 // This is the first that we have heard about this package, so the 9697 // permissions we have now selected are fixed until explicitly 9698 // changed. 9699 ps.installPermissionsFixed = true; 9700 } 9701 9702 // Persist the runtime permissions state for users with changes. If permissions 9703 // were revoked because no app in the shared user declares them we have to 9704 // write synchronously to avoid losing runtime permissions state. 9705 for (int userId : changedRuntimePermissionUserIds) { 9706 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9707 } 9708 9709 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9710 } 9711 9712 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9713 boolean allowed = false; 9714 final int NP = PackageParser.NEW_PERMISSIONS.length; 9715 for (int ip=0; ip<NP; ip++) { 9716 final PackageParser.NewPermissionInfo npi 9717 = PackageParser.NEW_PERMISSIONS[ip]; 9718 if (npi.name.equals(perm) 9719 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9720 allowed = true; 9721 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9722 + pkg.packageName); 9723 break; 9724 } 9725 } 9726 return allowed; 9727 } 9728 9729 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9730 BasePermission bp, PermissionsState origPermissions) { 9731 boolean allowed; 9732 allowed = (compareSignatures( 9733 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9734 == PackageManager.SIGNATURE_MATCH) 9735 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9736 == PackageManager.SIGNATURE_MATCH); 9737 if (!allowed && (bp.protectionLevel 9738 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9739 if (isSystemApp(pkg)) { 9740 // For updated system applications, a system permission 9741 // is granted only if it had been defined by the original application. 9742 if (pkg.isUpdatedSystemApp()) { 9743 final PackageSetting sysPs = mSettings 9744 .getDisabledSystemPkgLPr(pkg.packageName); 9745 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9746 // If the original was granted this permission, we take 9747 // that grant decision as read and propagate it to the 9748 // update. 9749 if (sysPs.isPrivileged()) { 9750 allowed = true; 9751 } 9752 } else { 9753 // The system apk may have been updated with an older 9754 // version of the one on the data partition, but which 9755 // granted a new system permission that it didn't have 9756 // before. In this case we do want to allow the app to 9757 // now get the new permission if the ancestral apk is 9758 // privileged to get it. 9759 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9760 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9761 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9762 allowed = true; 9763 break; 9764 } 9765 } 9766 } 9767 // Also if a privileged parent package on the system image or any of 9768 // its children requested a privileged permission, the updated child 9769 // packages can also get the permission. 9770 if (pkg.parentPackage != null) { 9771 final PackageSetting disabledSysParentPs = mSettings 9772 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9773 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9774 && disabledSysParentPs.isPrivileged()) { 9775 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9776 allowed = true; 9777 } else if (disabledSysParentPs.pkg.childPackages != null) { 9778 final int count = disabledSysParentPs.pkg.childPackages.size(); 9779 for (int i = 0; i < count; i++) { 9780 PackageParser.Package disabledSysChildPkg = 9781 disabledSysParentPs.pkg.childPackages.get(i); 9782 if (isPackageRequestingPermission(disabledSysChildPkg, 9783 perm)) { 9784 allowed = true; 9785 break; 9786 } 9787 } 9788 } 9789 } 9790 } 9791 } 9792 } else { 9793 allowed = isPrivilegedApp(pkg); 9794 } 9795 } 9796 } 9797 if (!allowed) { 9798 if (!allowed && (bp.protectionLevel 9799 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9800 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9801 // If this was a previously normal/dangerous permission that got moved 9802 // to a system permission as part of the runtime permission redesign, then 9803 // we still want to blindly grant it to old apps. 9804 allowed = true; 9805 } 9806 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9807 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9808 // If this permission is to be granted to the system installer and 9809 // this app is an installer, then it gets the permission. 9810 allowed = true; 9811 } 9812 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9813 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9814 // If this permission is to be granted to the system verifier and 9815 // this app is a verifier, then it gets the permission. 9816 allowed = true; 9817 } 9818 if (!allowed && (bp.protectionLevel 9819 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9820 && isSystemApp(pkg)) { 9821 // Any pre-installed system app is allowed to get this permission. 9822 allowed = true; 9823 } 9824 if (!allowed && (bp.protectionLevel 9825 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9826 // For development permissions, a development permission 9827 // is granted only if it was already granted. 9828 allowed = origPermissions.hasInstallPermission(perm); 9829 } 9830 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9831 && pkg.packageName.equals(mSetupWizardPackage)) { 9832 // If this permission is to be granted to the system setup wizard and 9833 // this app is a setup wizard, then it gets the permission. 9834 allowed = true; 9835 } 9836 } 9837 return allowed; 9838 } 9839 9840 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9841 final int permCount = pkg.requestedPermissions.size(); 9842 for (int j = 0; j < permCount; j++) { 9843 String requestedPermission = pkg.requestedPermissions.get(j); 9844 if (permission.equals(requestedPermission)) { 9845 return true; 9846 } 9847 } 9848 return false; 9849 } 9850 9851 final class ActivityIntentResolver 9852 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9853 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9854 boolean defaultOnly, int userId) { 9855 if (!sUserManager.exists(userId)) return null; 9856 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9857 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9858 } 9859 9860 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9861 int userId) { 9862 if (!sUserManager.exists(userId)) return null; 9863 mFlags = flags; 9864 return super.queryIntent(intent, resolvedType, 9865 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9866 } 9867 9868 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9869 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9870 if (!sUserManager.exists(userId)) return null; 9871 if (packageActivities == null) { 9872 return null; 9873 } 9874 mFlags = flags; 9875 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9876 final int N = packageActivities.size(); 9877 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9878 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9879 9880 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9881 for (int i = 0; i < N; ++i) { 9882 intentFilters = packageActivities.get(i).intents; 9883 if (intentFilters != null && intentFilters.size() > 0) { 9884 PackageParser.ActivityIntentInfo[] array = 9885 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9886 intentFilters.toArray(array); 9887 listCut.add(array); 9888 } 9889 } 9890 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9891 } 9892 9893 /** 9894 * Finds a privileged activity that matches the specified activity names. 9895 */ 9896 private PackageParser.Activity findMatchingActivity( 9897 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9898 for (PackageParser.Activity sysActivity : activityList) { 9899 if (sysActivity.info.name.equals(activityInfo.name)) { 9900 return sysActivity; 9901 } 9902 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9903 return sysActivity; 9904 } 9905 if (sysActivity.info.targetActivity != null) { 9906 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9907 return sysActivity; 9908 } 9909 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9910 return sysActivity; 9911 } 9912 } 9913 } 9914 return null; 9915 } 9916 9917 public class IterGenerator<E> { 9918 public Iterator<E> generate(ActivityIntentInfo info) { 9919 return null; 9920 } 9921 } 9922 9923 public class ActionIterGenerator extends IterGenerator<String> { 9924 @Override 9925 public Iterator<String> generate(ActivityIntentInfo info) { 9926 return info.actionsIterator(); 9927 } 9928 } 9929 9930 public class CategoriesIterGenerator extends IterGenerator<String> { 9931 @Override 9932 public Iterator<String> generate(ActivityIntentInfo info) { 9933 return info.categoriesIterator(); 9934 } 9935 } 9936 9937 public class SchemesIterGenerator extends IterGenerator<String> { 9938 @Override 9939 public Iterator<String> generate(ActivityIntentInfo info) { 9940 return info.schemesIterator(); 9941 } 9942 } 9943 9944 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9945 @Override 9946 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9947 return info.authoritiesIterator(); 9948 } 9949 } 9950 9951 /** 9952 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9953 * MODIFIED. Do not pass in a list that should not be changed. 9954 */ 9955 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9956 IterGenerator<T> generator, Iterator<T> searchIterator) { 9957 // loop through the set of actions; every one must be found in the intent filter 9958 while (searchIterator.hasNext()) { 9959 // we must have at least one filter in the list to consider a match 9960 if (intentList.size() == 0) { 9961 break; 9962 } 9963 9964 final T searchAction = searchIterator.next(); 9965 9966 // loop through the set of intent filters 9967 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9968 while (intentIter.hasNext()) { 9969 final ActivityIntentInfo intentInfo = intentIter.next(); 9970 boolean selectionFound = false; 9971 9972 // loop through the intent filter's selection criteria; at least one 9973 // of them must match the searched criteria 9974 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9975 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9976 final T intentSelection = intentSelectionIter.next(); 9977 if (intentSelection != null && intentSelection.equals(searchAction)) { 9978 selectionFound = true; 9979 break; 9980 } 9981 } 9982 9983 // the selection criteria wasn't found in this filter's set; this filter 9984 // is not a potential match 9985 if (!selectionFound) { 9986 intentIter.remove(); 9987 } 9988 } 9989 } 9990 } 9991 9992 private boolean isProtectedAction(ActivityIntentInfo filter) { 9993 final Iterator<String> actionsIter = filter.actionsIterator(); 9994 while (actionsIter != null && actionsIter.hasNext()) { 9995 final String filterAction = actionsIter.next(); 9996 if (PROTECTED_ACTIONS.contains(filterAction)) { 9997 return true; 9998 } 9999 } 10000 return false; 10001 } 10002 10003 /** 10004 * Adjusts the priority of the given intent filter according to policy. 10005 * <p> 10006 * <ul> 10007 * <li>The priority for non privileged applications is capped to '0'</li> 10008 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10009 * <li>The priority for unbundled updates to privileged applications is capped to the 10010 * priority defined on the system partition</li> 10011 * </ul> 10012 * <p> 10013 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10014 * allowed to obtain any priority on any action. 10015 */ 10016 private void adjustPriority( 10017 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10018 // nothing to do; priority is fine as-is 10019 if (intent.getPriority() <= 0) { 10020 return; 10021 } 10022 10023 final ActivityInfo activityInfo = intent.activity.info; 10024 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10025 10026 final boolean privilegedApp = 10027 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10028 if (!privilegedApp) { 10029 // non-privileged applications can never define a priority >0 10030 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10031 + " package: " + applicationInfo.packageName 10032 + " activity: " + intent.activity.className 10033 + " origPrio: " + intent.getPriority()); 10034 intent.setPriority(0); 10035 return; 10036 } 10037 10038 if (systemActivities == null) { 10039 // the system package is not disabled; we're parsing the system partition 10040 if (isProtectedAction(intent)) { 10041 if (mDeferProtectedFilters) { 10042 // We can't deal with these just yet. No component should ever obtain a 10043 // >0 priority for a protected actions, with ONE exception -- the setup 10044 // wizard. The setup wizard, however, cannot be known until we're able to 10045 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10046 // until all intent filters have been processed. Chicken, meet egg. 10047 // Let the filter temporarily have a high priority and rectify the 10048 // priorities after all system packages have been scanned. 10049 mProtectedFilters.add(intent); 10050 if (DEBUG_FILTERS) { 10051 Slog.i(TAG, "Protected action; save for later;" 10052 + " package: " + applicationInfo.packageName 10053 + " activity: " + intent.activity.className 10054 + " origPrio: " + intent.getPriority()); 10055 } 10056 return; 10057 } else { 10058 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10059 Slog.i(TAG, "No setup wizard;" 10060 + " All protected intents capped to priority 0"); 10061 } 10062 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10063 if (DEBUG_FILTERS) { 10064 Slog.i(TAG, "Found setup wizard;" 10065 + " allow priority " + intent.getPriority() + ";" 10066 + " package: " + intent.activity.info.packageName 10067 + " activity: " + intent.activity.className 10068 + " priority: " + intent.getPriority()); 10069 } 10070 // setup wizard gets whatever it wants 10071 return; 10072 } 10073 Slog.w(TAG, "Protected action; cap priority to 0;" 10074 + " package: " + intent.activity.info.packageName 10075 + " activity: " + intent.activity.className 10076 + " origPrio: " + intent.getPriority()); 10077 intent.setPriority(0); 10078 return; 10079 } 10080 } 10081 // privileged apps on the system image get whatever priority they request 10082 return; 10083 } 10084 10085 // privileged app unbundled update ... try to find the same activity 10086 final PackageParser.Activity foundActivity = 10087 findMatchingActivity(systemActivities, activityInfo); 10088 if (foundActivity == null) { 10089 // this is a new activity; it cannot obtain >0 priority 10090 if (DEBUG_FILTERS) { 10091 Slog.i(TAG, "New activity; cap priority to 0;" 10092 + " package: " + applicationInfo.packageName 10093 + " activity: " + intent.activity.className 10094 + " origPrio: " + intent.getPriority()); 10095 } 10096 intent.setPriority(0); 10097 return; 10098 } 10099 10100 // found activity, now check for filter equivalence 10101 10102 // a shallow copy is enough; we modify the list, not its contents 10103 final List<ActivityIntentInfo> intentListCopy = 10104 new ArrayList<>(foundActivity.intents); 10105 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10106 10107 // find matching action subsets 10108 final Iterator<String> actionsIterator = intent.actionsIterator(); 10109 if (actionsIterator != null) { 10110 getIntentListSubset( 10111 intentListCopy, new ActionIterGenerator(), actionsIterator); 10112 if (intentListCopy.size() == 0) { 10113 // no more intents to match; we're not equivalent 10114 if (DEBUG_FILTERS) { 10115 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10116 + " package: " + applicationInfo.packageName 10117 + " activity: " + intent.activity.className 10118 + " origPrio: " + intent.getPriority()); 10119 } 10120 intent.setPriority(0); 10121 return; 10122 } 10123 } 10124 10125 // find matching category subsets 10126 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10127 if (categoriesIterator != null) { 10128 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10129 categoriesIterator); 10130 if (intentListCopy.size() == 0) { 10131 // no more intents to match; we're not equivalent 10132 if (DEBUG_FILTERS) { 10133 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10134 + " package: " + applicationInfo.packageName 10135 + " activity: " + intent.activity.className 10136 + " origPrio: " + intent.getPriority()); 10137 } 10138 intent.setPriority(0); 10139 return; 10140 } 10141 } 10142 10143 // find matching schemes subsets 10144 final Iterator<String> schemesIterator = intent.schemesIterator(); 10145 if (schemesIterator != null) { 10146 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10147 schemesIterator); 10148 if (intentListCopy.size() == 0) { 10149 // no more intents to match; we're not equivalent 10150 if (DEBUG_FILTERS) { 10151 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10152 + " package: " + applicationInfo.packageName 10153 + " activity: " + intent.activity.className 10154 + " origPrio: " + intent.getPriority()); 10155 } 10156 intent.setPriority(0); 10157 return; 10158 } 10159 } 10160 10161 // find matching authorities subsets 10162 final Iterator<IntentFilter.AuthorityEntry> 10163 authoritiesIterator = intent.authoritiesIterator(); 10164 if (authoritiesIterator != null) { 10165 getIntentListSubset(intentListCopy, 10166 new AuthoritiesIterGenerator(), 10167 authoritiesIterator); 10168 if (intentListCopy.size() == 0) { 10169 // no more intents to match; we're not equivalent 10170 if (DEBUG_FILTERS) { 10171 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10172 + " package: " + applicationInfo.packageName 10173 + " activity: " + intent.activity.className 10174 + " origPrio: " + intent.getPriority()); 10175 } 10176 intent.setPriority(0); 10177 return; 10178 } 10179 } 10180 10181 // we found matching filter(s); app gets the max priority of all intents 10182 int cappedPriority = 0; 10183 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10184 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10185 } 10186 if (intent.getPriority() > cappedPriority) { 10187 if (DEBUG_FILTERS) { 10188 Slog.i(TAG, "Found matching filter(s);" 10189 + " cap priority to " + cappedPriority + ";" 10190 + " package: " + applicationInfo.packageName 10191 + " activity: " + intent.activity.className 10192 + " origPrio: " + intent.getPriority()); 10193 } 10194 intent.setPriority(cappedPriority); 10195 return; 10196 } 10197 // all this for nothing; the requested priority was <= what was on the system 10198 } 10199 10200 public final void addActivity(PackageParser.Activity a, String type) { 10201 mActivities.put(a.getComponentName(), a); 10202 if (DEBUG_SHOW_INFO) 10203 Log.v( 10204 TAG, " " + type + " " + 10205 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10206 if (DEBUG_SHOW_INFO) 10207 Log.v(TAG, " Class=" + a.info.name); 10208 final int NI = a.intents.size(); 10209 for (int j=0; j<NI; j++) { 10210 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10211 if ("activity".equals(type)) { 10212 final PackageSetting ps = 10213 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10214 final List<PackageParser.Activity> systemActivities = 10215 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10216 adjustPriority(systemActivities, intent); 10217 } 10218 if (DEBUG_SHOW_INFO) { 10219 Log.v(TAG, " IntentFilter:"); 10220 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10221 } 10222 if (!intent.debugCheck()) { 10223 Log.w(TAG, "==> For Activity " + a.info.name); 10224 } 10225 addFilter(intent); 10226 } 10227 } 10228 10229 public final void removeActivity(PackageParser.Activity a, String type) { 10230 mActivities.remove(a.getComponentName()); 10231 if (DEBUG_SHOW_INFO) { 10232 Log.v(TAG, " " + type + " " 10233 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10234 : a.info.name) + ":"); 10235 Log.v(TAG, " Class=" + a.info.name); 10236 } 10237 final int NI = a.intents.size(); 10238 for (int j=0; j<NI; j++) { 10239 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10240 if (DEBUG_SHOW_INFO) { 10241 Log.v(TAG, " IntentFilter:"); 10242 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10243 } 10244 removeFilter(intent); 10245 } 10246 } 10247 10248 @Override 10249 protected boolean allowFilterResult( 10250 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10251 ActivityInfo filterAi = filter.activity.info; 10252 for (int i=dest.size()-1; i>=0; i--) { 10253 ActivityInfo destAi = dest.get(i).activityInfo; 10254 if (destAi.name == filterAi.name 10255 && destAi.packageName == filterAi.packageName) { 10256 return false; 10257 } 10258 } 10259 return true; 10260 } 10261 10262 @Override 10263 protected ActivityIntentInfo[] newArray(int size) { 10264 return new ActivityIntentInfo[size]; 10265 } 10266 10267 @Override 10268 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10269 if (!sUserManager.exists(userId)) return true; 10270 PackageParser.Package p = filter.activity.owner; 10271 if (p != null) { 10272 PackageSetting ps = (PackageSetting)p.mExtras; 10273 if (ps != null) { 10274 // System apps are never considered stopped for purposes of 10275 // filtering, because there may be no way for the user to 10276 // actually re-launch them. 10277 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10278 && ps.getStopped(userId); 10279 } 10280 } 10281 return false; 10282 } 10283 10284 @Override 10285 protected boolean isPackageForFilter(String packageName, 10286 PackageParser.ActivityIntentInfo info) { 10287 return packageName.equals(info.activity.owner.packageName); 10288 } 10289 10290 @Override 10291 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10292 int match, int userId) { 10293 if (!sUserManager.exists(userId)) return null; 10294 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10295 return null; 10296 } 10297 final PackageParser.Activity activity = info.activity; 10298 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10299 if (ps == null) { 10300 return null; 10301 } 10302 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10303 ps.readUserState(userId), userId); 10304 if (ai == null) { 10305 return null; 10306 } 10307 final ResolveInfo res = new ResolveInfo(); 10308 res.activityInfo = ai; 10309 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10310 res.filter = info; 10311 } 10312 if (info != null) { 10313 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10314 } 10315 res.priority = info.getPriority(); 10316 res.preferredOrder = activity.owner.mPreferredOrder; 10317 //System.out.println("Result: " + res.activityInfo.className + 10318 // " = " + res.priority); 10319 res.match = match; 10320 res.isDefault = info.hasDefault; 10321 res.labelRes = info.labelRes; 10322 res.nonLocalizedLabel = info.nonLocalizedLabel; 10323 if (userNeedsBadging(userId)) { 10324 res.noResourceId = true; 10325 } else { 10326 res.icon = info.icon; 10327 } 10328 res.iconResourceId = info.icon; 10329 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10330 return res; 10331 } 10332 10333 @Override 10334 protected void sortResults(List<ResolveInfo> results) { 10335 Collections.sort(results, mResolvePrioritySorter); 10336 } 10337 10338 @Override 10339 protected void dumpFilter(PrintWriter out, String prefix, 10340 PackageParser.ActivityIntentInfo filter) { 10341 out.print(prefix); out.print( 10342 Integer.toHexString(System.identityHashCode(filter.activity))); 10343 out.print(' '); 10344 filter.activity.printComponentShortName(out); 10345 out.print(" filter "); 10346 out.println(Integer.toHexString(System.identityHashCode(filter))); 10347 } 10348 10349 @Override 10350 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10351 return filter.activity; 10352 } 10353 10354 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10355 PackageParser.Activity activity = (PackageParser.Activity)label; 10356 out.print(prefix); out.print( 10357 Integer.toHexString(System.identityHashCode(activity))); 10358 out.print(' '); 10359 activity.printComponentShortName(out); 10360 if (count > 1) { 10361 out.print(" ("); out.print(count); out.print(" filters)"); 10362 } 10363 out.println(); 10364 } 10365 10366 // Keys are String (activity class name), values are Activity. 10367 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10368 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10369 private int mFlags; 10370 } 10371 10372 private final class ServiceIntentResolver 10373 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10374 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10375 boolean defaultOnly, int userId) { 10376 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10377 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10378 } 10379 10380 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10381 int userId) { 10382 if (!sUserManager.exists(userId)) return null; 10383 mFlags = flags; 10384 return super.queryIntent(intent, resolvedType, 10385 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10386 } 10387 10388 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10389 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10390 if (!sUserManager.exists(userId)) return null; 10391 if (packageServices == null) { 10392 return null; 10393 } 10394 mFlags = flags; 10395 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10396 final int N = packageServices.size(); 10397 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10398 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10399 10400 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10401 for (int i = 0; i < N; ++i) { 10402 intentFilters = packageServices.get(i).intents; 10403 if (intentFilters != null && intentFilters.size() > 0) { 10404 PackageParser.ServiceIntentInfo[] array = 10405 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10406 intentFilters.toArray(array); 10407 listCut.add(array); 10408 } 10409 } 10410 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10411 } 10412 10413 public final void addService(PackageParser.Service s) { 10414 mServices.put(s.getComponentName(), s); 10415 if (DEBUG_SHOW_INFO) { 10416 Log.v(TAG, " " 10417 + (s.info.nonLocalizedLabel != null 10418 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10419 Log.v(TAG, " Class=" + s.info.name); 10420 } 10421 final int NI = s.intents.size(); 10422 int j; 10423 for (j=0; j<NI; j++) { 10424 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10425 if (DEBUG_SHOW_INFO) { 10426 Log.v(TAG, " IntentFilter:"); 10427 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10428 } 10429 if (!intent.debugCheck()) { 10430 Log.w(TAG, "==> For Service " + s.info.name); 10431 } 10432 addFilter(intent); 10433 } 10434 } 10435 10436 public final void removeService(PackageParser.Service s) { 10437 mServices.remove(s.getComponentName()); 10438 if (DEBUG_SHOW_INFO) { 10439 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10440 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10441 Log.v(TAG, " Class=" + s.info.name); 10442 } 10443 final int NI = s.intents.size(); 10444 int j; 10445 for (j=0; j<NI; j++) { 10446 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10447 if (DEBUG_SHOW_INFO) { 10448 Log.v(TAG, " IntentFilter:"); 10449 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10450 } 10451 removeFilter(intent); 10452 } 10453 } 10454 10455 @Override 10456 protected boolean allowFilterResult( 10457 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10458 ServiceInfo filterSi = filter.service.info; 10459 for (int i=dest.size()-1; i>=0; i--) { 10460 ServiceInfo destAi = dest.get(i).serviceInfo; 10461 if (destAi.name == filterSi.name 10462 && destAi.packageName == filterSi.packageName) { 10463 return false; 10464 } 10465 } 10466 return true; 10467 } 10468 10469 @Override 10470 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10471 return new PackageParser.ServiceIntentInfo[size]; 10472 } 10473 10474 @Override 10475 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10476 if (!sUserManager.exists(userId)) return true; 10477 PackageParser.Package p = filter.service.owner; 10478 if (p != null) { 10479 PackageSetting ps = (PackageSetting)p.mExtras; 10480 if (ps != null) { 10481 // System apps are never considered stopped for purposes of 10482 // filtering, because there may be no way for the user to 10483 // actually re-launch them. 10484 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10485 && ps.getStopped(userId); 10486 } 10487 } 10488 return false; 10489 } 10490 10491 @Override 10492 protected boolean isPackageForFilter(String packageName, 10493 PackageParser.ServiceIntentInfo info) { 10494 return packageName.equals(info.service.owner.packageName); 10495 } 10496 10497 @Override 10498 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10499 int match, int userId) { 10500 if (!sUserManager.exists(userId)) return null; 10501 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10502 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10503 return null; 10504 } 10505 final PackageParser.Service service = info.service; 10506 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10507 if (ps == null) { 10508 return null; 10509 } 10510 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10511 ps.readUserState(userId), userId); 10512 if (si == null) { 10513 return null; 10514 } 10515 final ResolveInfo res = new ResolveInfo(); 10516 res.serviceInfo = si; 10517 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10518 res.filter = filter; 10519 } 10520 res.priority = info.getPriority(); 10521 res.preferredOrder = service.owner.mPreferredOrder; 10522 res.match = match; 10523 res.isDefault = info.hasDefault; 10524 res.labelRes = info.labelRes; 10525 res.nonLocalizedLabel = info.nonLocalizedLabel; 10526 res.icon = info.icon; 10527 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10528 return res; 10529 } 10530 10531 @Override 10532 protected void sortResults(List<ResolveInfo> results) { 10533 Collections.sort(results, mResolvePrioritySorter); 10534 } 10535 10536 @Override 10537 protected void dumpFilter(PrintWriter out, String prefix, 10538 PackageParser.ServiceIntentInfo filter) { 10539 out.print(prefix); out.print( 10540 Integer.toHexString(System.identityHashCode(filter.service))); 10541 out.print(' '); 10542 filter.service.printComponentShortName(out); 10543 out.print(" filter "); 10544 out.println(Integer.toHexString(System.identityHashCode(filter))); 10545 } 10546 10547 @Override 10548 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10549 return filter.service; 10550 } 10551 10552 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10553 PackageParser.Service service = (PackageParser.Service)label; 10554 out.print(prefix); out.print( 10555 Integer.toHexString(System.identityHashCode(service))); 10556 out.print(' '); 10557 service.printComponentShortName(out); 10558 if (count > 1) { 10559 out.print(" ("); out.print(count); out.print(" filters)"); 10560 } 10561 out.println(); 10562 } 10563 10564// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10565// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10566// final List<ResolveInfo> retList = Lists.newArrayList(); 10567// while (i.hasNext()) { 10568// final ResolveInfo resolveInfo = (ResolveInfo) i; 10569// if (isEnabledLP(resolveInfo.serviceInfo)) { 10570// retList.add(resolveInfo); 10571// } 10572// } 10573// return retList; 10574// } 10575 10576 // Keys are String (activity class name), values are Activity. 10577 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10578 = new ArrayMap<ComponentName, PackageParser.Service>(); 10579 private int mFlags; 10580 }; 10581 10582 private final class ProviderIntentResolver 10583 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10584 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10585 boolean defaultOnly, int userId) { 10586 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10587 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10588 } 10589 10590 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10591 int userId) { 10592 if (!sUserManager.exists(userId)) 10593 return null; 10594 mFlags = flags; 10595 return super.queryIntent(intent, resolvedType, 10596 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10597 } 10598 10599 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10600 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10601 if (!sUserManager.exists(userId)) 10602 return null; 10603 if (packageProviders == null) { 10604 return null; 10605 } 10606 mFlags = flags; 10607 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10608 final int N = packageProviders.size(); 10609 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10610 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10611 10612 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10613 for (int i = 0; i < N; ++i) { 10614 intentFilters = packageProviders.get(i).intents; 10615 if (intentFilters != null && intentFilters.size() > 0) { 10616 PackageParser.ProviderIntentInfo[] array = 10617 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10618 intentFilters.toArray(array); 10619 listCut.add(array); 10620 } 10621 } 10622 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10623 } 10624 10625 public final void addProvider(PackageParser.Provider p) { 10626 if (mProviders.containsKey(p.getComponentName())) { 10627 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10628 return; 10629 } 10630 10631 mProviders.put(p.getComponentName(), p); 10632 if (DEBUG_SHOW_INFO) { 10633 Log.v(TAG, " " 10634 + (p.info.nonLocalizedLabel != null 10635 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10636 Log.v(TAG, " Class=" + p.info.name); 10637 } 10638 final int NI = p.intents.size(); 10639 int j; 10640 for (j = 0; j < NI; j++) { 10641 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10642 if (DEBUG_SHOW_INFO) { 10643 Log.v(TAG, " IntentFilter:"); 10644 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10645 } 10646 if (!intent.debugCheck()) { 10647 Log.w(TAG, "==> For Provider " + p.info.name); 10648 } 10649 addFilter(intent); 10650 } 10651 } 10652 10653 public final void removeProvider(PackageParser.Provider p) { 10654 mProviders.remove(p.getComponentName()); 10655 if (DEBUG_SHOW_INFO) { 10656 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10657 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10658 Log.v(TAG, " Class=" + p.info.name); 10659 } 10660 final int NI = p.intents.size(); 10661 int j; 10662 for (j = 0; j < NI; j++) { 10663 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10664 if (DEBUG_SHOW_INFO) { 10665 Log.v(TAG, " IntentFilter:"); 10666 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10667 } 10668 removeFilter(intent); 10669 } 10670 } 10671 10672 @Override 10673 protected boolean allowFilterResult( 10674 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10675 ProviderInfo filterPi = filter.provider.info; 10676 for (int i = dest.size() - 1; i >= 0; i--) { 10677 ProviderInfo destPi = dest.get(i).providerInfo; 10678 if (destPi.name == filterPi.name 10679 && destPi.packageName == filterPi.packageName) { 10680 return false; 10681 } 10682 } 10683 return true; 10684 } 10685 10686 @Override 10687 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10688 return new PackageParser.ProviderIntentInfo[size]; 10689 } 10690 10691 @Override 10692 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10693 if (!sUserManager.exists(userId)) 10694 return true; 10695 PackageParser.Package p = filter.provider.owner; 10696 if (p != null) { 10697 PackageSetting ps = (PackageSetting) p.mExtras; 10698 if (ps != null) { 10699 // System apps are never considered stopped for purposes of 10700 // filtering, because there may be no way for the user to 10701 // actually re-launch them. 10702 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10703 && ps.getStopped(userId); 10704 } 10705 } 10706 return false; 10707 } 10708 10709 @Override 10710 protected boolean isPackageForFilter(String packageName, 10711 PackageParser.ProviderIntentInfo info) { 10712 return packageName.equals(info.provider.owner.packageName); 10713 } 10714 10715 @Override 10716 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10717 int match, int userId) { 10718 if (!sUserManager.exists(userId)) 10719 return null; 10720 final PackageParser.ProviderIntentInfo info = filter; 10721 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10722 return null; 10723 } 10724 final PackageParser.Provider provider = info.provider; 10725 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10726 if (ps == null) { 10727 return null; 10728 } 10729 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10730 ps.readUserState(userId), userId); 10731 if (pi == null) { 10732 return null; 10733 } 10734 final ResolveInfo res = new ResolveInfo(); 10735 res.providerInfo = pi; 10736 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10737 res.filter = filter; 10738 } 10739 res.priority = info.getPriority(); 10740 res.preferredOrder = provider.owner.mPreferredOrder; 10741 res.match = match; 10742 res.isDefault = info.hasDefault; 10743 res.labelRes = info.labelRes; 10744 res.nonLocalizedLabel = info.nonLocalizedLabel; 10745 res.icon = info.icon; 10746 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10747 return res; 10748 } 10749 10750 @Override 10751 protected void sortResults(List<ResolveInfo> results) { 10752 Collections.sort(results, mResolvePrioritySorter); 10753 } 10754 10755 @Override 10756 protected void dumpFilter(PrintWriter out, String prefix, 10757 PackageParser.ProviderIntentInfo filter) { 10758 out.print(prefix); 10759 out.print( 10760 Integer.toHexString(System.identityHashCode(filter.provider))); 10761 out.print(' '); 10762 filter.provider.printComponentShortName(out); 10763 out.print(" filter "); 10764 out.println(Integer.toHexString(System.identityHashCode(filter))); 10765 } 10766 10767 @Override 10768 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10769 return filter.provider; 10770 } 10771 10772 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10773 PackageParser.Provider provider = (PackageParser.Provider)label; 10774 out.print(prefix); out.print( 10775 Integer.toHexString(System.identityHashCode(provider))); 10776 out.print(' '); 10777 provider.printComponentShortName(out); 10778 if (count > 1) { 10779 out.print(" ("); out.print(count); out.print(" filters)"); 10780 } 10781 out.println(); 10782 } 10783 10784 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10785 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10786 private int mFlags; 10787 } 10788 10789 private static final class EphemeralIntentResolver 10790 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10791 @Override 10792 protected EphemeralResolveIntentInfo[] newArray(int size) { 10793 return new EphemeralResolveIntentInfo[size]; 10794 } 10795 10796 @Override 10797 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10798 return true; 10799 } 10800 10801 @Override 10802 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10803 int userId) { 10804 if (!sUserManager.exists(userId)) { 10805 return null; 10806 } 10807 return info.getEphemeralResolveInfo(); 10808 } 10809 } 10810 10811 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10812 new Comparator<ResolveInfo>() { 10813 public int compare(ResolveInfo r1, ResolveInfo r2) { 10814 int v1 = r1.priority; 10815 int v2 = r2.priority; 10816 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10817 if (v1 != v2) { 10818 return (v1 > v2) ? -1 : 1; 10819 } 10820 v1 = r1.preferredOrder; 10821 v2 = r2.preferredOrder; 10822 if (v1 != v2) { 10823 return (v1 > v2) ? -1 : 1; 10824 } 10825 if (r1.isDefault != r2.isDefault) { 10826 return r1.isDefault ? -1 : 1; 10827 } 10828 v1 = r1.match; 10829 v2 = r2.match; 10830 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10831 if (v1 != v2) { 10832 return (v1 > v2) ? -1 : 1; 10833 } 10834 if (r1.system != r2.system) { 10835 return r1.system ? -1 : 1; 10836 } 10837 if (r1.activityInfo != null) { 10838 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10839 } 10840 if (r1.serviceInfo != null) { 10841 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10842 } 10843 if (r1.providerInfo != null) { 10844 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10845 } 10846 return 0; 10847 } 10848 }; 10849 10850 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10851 new Comparator<ProviderInfo>() { 10852 public int compare(ProviderInfo p1, ProviderInfo p2) { 10853 final int v1 = p1.initOrder; 10854 final int v2 = p2.initOrder; 10855 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10856 } 10857 }; 10858 10859 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10860 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10861 final int[] userIds) { 10862 mHandler.post(new Runnable() { 10863 @Override 10864 public void run() { 10865 try { 10866 final IActivityManager am = ActivityManagerNative.getDefault(); 10867 if (am == null) return; 10868 final int[] resolvedUserIds; 10869 if (userIds == null) { 10870 resolvedUserIds = am.getRunningUserIds(); 10871 } else { 10872 resolvedUserIds = userIds; 10873 } 10874 for (int id : resolvedUserIds) { 10875 final Intent intent = new Intent(action, 10876 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10877 if (extras != null) { 10878 intent.putExtras(extras); 10879 } 10880 if (targetPkg != null) { 10881 intent.setPackage(targetPkg); 10882 } 10883 // Modify the UID when posting to other users 10884 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10885 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10886 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10887 intent.putExtra(Intent.EXTRA_UID, uid); 10888 } 10889 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10890 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10891 if (DEBUG_BROADCASTS) { 10892 RuntimeException here = new RuntimeException("here"); 10893 here.fillInStackTrace(); 10894 Slog.d(TAG, "Sending to user " + id + ": " 10895 + intent.toShortString(false, true, false, false) 10896 + " " + intent.getExtras(), here); 10897 } 10898 am.broadcastIntent(null, intent, null, finishedReceiver, 10899 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10900 null, finishedReceiver != null, false, id); 10901 } 10902 } catch (RemoteException ex) { 10903 } 10904 } 10905 }); 10906 } 10907 10908 /** 10909 * Check if the external storage media is available. This is true if there 10910 * is a mounted external storage medium or if the external storage is 10911 * emulated. 10912 */ 10913 private boolean isExternalMediaAvailable() { 10914 return mMediaMounted || Environment.isExternalStorageEmulated(); 10915 } 10916 10917 @Override 10918 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10919 // writer 10920 synchronized (mPackages) { 10921 if (!isExternalMediaAvailable()) { 10922 // If the external storage is no longer mounted at this point, 10923 // the caller may not have been able to delete all of this 10924 // packages files and can not delete any more. Bail. 10925 return null; 10926 } 10927 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10928 if (lastPackage != null) { 10929 pkgs.remove(lastPackage); 10930 } 10931 if (pkgs.size() > 0) { 10932 return pkgs.get(0); 10933 } 10934 } 10935 return null; 10936 } 10937 10938 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10939 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10940 userId, andCode ? 1 : 0, packageName); 10941 if (mSystemReady) { 10942 msg.sendToTarget(); 10943 } else { 10944 if (mPostSystemReadyMessages == null) { 10945 mPostSystemReadyMessages = new ArrayList<>(); 10946 } 10947 mPostSystemReadyMessages.add(msg); 10948 } 10949 } 10950 10951 void startCleaningPackages() { 10952 // reader 10953 if (!isExternalMediaAvailable()) { 10954 return; 10955 } 10956 synchronized (mPackages) { 10957 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10958 return; 10959 } 10960 } 10961 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10962 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10963 IActivityManager am = ActivityManagerNative.getDefault(); 10964 if (am != null) { 10965 try { 10966 am.startService(null, intent, null, mContext.getOpPackageName(), 10967 UserHandle.USER_SYSTEM); 10968 } catch (RemoteException e) { 10969 } 10970 } 10971 } 10972 10973 @Override 10974 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10975 int installFlags, String installerPackageName, int userId) { 10976 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10977 10978 final int callingUid = Binder.getCallingUid(); 10979 enforceCrossUserPermission(callingUid, userId, 10980 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10981 10982 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10983 try { 10984 if (observer != null) { 10985 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10986 } 10987 } catch (RemoteException re) { 10988 } 10989 return; 10990 } 10991 10992 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10993 installFlags |= PackageManager.INSTALL_FROM_ADB; 10994 10995 } else { 10996 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10997 // about installerPackageName. 10998 10999 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11000 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11001 } 11002 11003 UserHandle user; 11004 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11005 user = UserHandle.ALL; 11006 } else { 11007 user = new UserHandle(userId); 11008 } 11009 11010 // Only system components can circumvent runtime permissions when installing. 11011 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11012 && mContext.checkCallingOrSelfPermission(Manifest.permission 11013 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11014 throw new SecurityException("You need the " 11015 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11016 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11017 } 11018 11019 final File originFile = new File(originPath); 11020 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11021 11022 final Message msg = mHandler.obtainMessage(INIT_COPY); 11023 final VerificationInfo verificationInfo = new VerificationInfo( 11024 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11025 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11026 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11027 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11028 null /*certificates*/); 11029 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11030 msg.obj = params; 11031 11032 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11033 System.identityHashCode(msg.obj)); 11034 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11035 System.identityHashCode(msg.obj)); 11036 11037 mHandler.sendMessage(msg); 11038 } 11039 11040 void installStage(String packageName, File stagedDir, String stagedCid, 11041 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11042 String installerPackageName, int installerUid, UserHandle user, 11043 Certificate[][] certificates) { 11044 if (DEBUG_EPHEMERAL) { 11045 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11046 Slog.d(TAG, "Ephemeral install of " + packageName); 11047 } 11048 } 11049 final VerificationInfo verificationInfo = new VerificationInfo( 11050 sessionParams.originatingUri, sessionParams.referrerUri, 11051 sessionParams.originatingUid, installerUid); 11052 11053 final OriginInfo origin; 11054 if (stagedDir != null) { 11055 origin = OriginInfo.fromStagedFile(stagedDir); 11056 } else { 11057 origin = OriginInfo.fromStagedContainer(stagedCid); 11058 } 11059 11060 final Message msg = mHandler.obtainMessage(INIT_COPY); 11061 final InstallParams params = new InstallParams(origin, null, observer, 11062 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11063 verificationInfo, user, sessionParams.abiOverride, 11064 sessionParams.grantedRuntimePermissions, certificates); 11065 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11066 msg.obj = params; 11067 11068 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11069 System.identityHashCode(msg.obj)); 11070 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11071 System.identityHashCode(msg.obj)); 11072 11073 mHandler.sendMessage(msg); 11074 } 11075 11076 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11077 int userId) { 11078 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11079 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11080 } 11081 11082 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11083 int appId, int userId) { 11084 Bundle extras = new Bundle(1); 11085 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11086 11087 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11088 packageName, extras, 0, null, null, new int[] {userId}); 11089 try { 11090 IActivityManager am = ActivityManagerNative.getDefault(); 11091 if (isSystem && am.isUserRunning(userId, 0)) { 11092 // The just-installed/enabled app is bundled on the system, so presumed 11093 // to be able to run automatically without needing an explicit launch. 11094 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11095 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11096 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11097 .setPackage(packageName); 11098 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11099 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11100 } 11101 } catch (RemoteException e) { 11102 // shouldn't happen 11103 Slog.w(TAG, "Unable to bootstrap installed package", e); 11104 } 11105 } 11106 11107 @Override 11108 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11109 int userId) { 11110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11111 PackageSetting pkgSetting; 11112 final int uid = Binder.getCallingUid(); 11113 enforceCrossUserPermission(uid, userId, 11114 true /* requireFullPermission */, true /* checkShell */, 11115 "setApplicationHiddenSetting for user " + userId); 11116 11117 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11118 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11119 return false; 11120 } 11121 11122 long callingId = Binder.clearCallingIdentity(); 11123 try { 11124 boolean sendAdded = false; 11125 boolean sendRemoved = false; 11126 // writer 11127 synchronized (mPackages) { 11128 pkgSetting = mSettings.mPackages.get(packageName); 11129 if (pkgSetting == null) { 11130 return false; 11131 } 11132 if (pkgSetting.getHidden(userId) != hidden) { 11133 pkgSetting.setHidden(hidden, userId); 11134 mSettings.writePackageRestrictionsLPr(userId); 11135 if (hidden) { 11136 sendRemoved = true; 11137 } else { 11138 sendAdded = true; 11139 } 11140 } 11141 } 11142 if (sendAdded) { 11143 sendPackageAddedForUser(packageName, pkgSetting, userId); 11144 return true; 11145 } 11146 if (sendRemoved) { 11147 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11148 "hiding pkg"); 11149 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11150 return true; 11151 } 11152 } finally { 11153 Binder.restoreCallingIdentity(callingId); 11154 } 11155 return false; 11156 } 11157 11158 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11159 int userId) { 11160 final PackageRemovedInfo info = new PackageRemovedInfo(); 11161 info.removedPackage = packageName; 11162 info.removedUsers = new int[] {userId}; 11163 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11164 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11165 } 11166 11167 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11168 if (pkgList.length > 0) { 11169 Bundle extras = new Bundle(1); 11170 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11171 11172 sendPackageBroadcast( 11173 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11174 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11175 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11176 new int[] {userId}); 11177 } 11178 } 11179 11180 /** 11181 * Returns true if application is not found or there was an error. Otherwise it returns 11182 * the hidden state of the package for the given user. 11183 */ 11184 @Override 11185 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11186 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11187 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11188 true /* requireFullPermission */, false /* checkShell */, 11189 "getApplicationHidden for user " + userId); 11190 PackageSetting pkgSetting; 11191 long callingId = Binder.clearCallingIdentity(); 11192 try { 11193 // writer 11194 synchronized (mPackages) { 11195 pkgSetting = mSettings.mPackages.get(packageName); 11196 if (pkgSetting == null) { 11197 return true; 11198 } 11199 return pkgSetting.getHidden(userId); 11200 } 11201 } finally { 11202 Binder.restoreCallingIdentity(callingId); 11203 } 11204 } 11205 11206 /** 11207 * @hide 11208 */ 11209 @Override 11210 public int installExistingPackageAsUser(String packageName, int userId) { 11211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11212 null); 11213 PackageSetting pkgSetting; 11214 final int uid = Binder.getCallingUid(); 11215 enforceCrossUserPermission(uid, userId, 11216 true /* requireFullPermission */, true /* checkShell */, 11217 "installExistingPackage for user " + userId); 11218 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11219 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11220 } 11221 11222 long callingId = Binder.clearCallingIdentity(); 11223 try { 11224 boolean installed = false; 11225 11226 // writer 11227 synchronized (mPackages) { 11228 pkgSetting = mSettings.mPackages.get(packageName); 11229 if (pkgSetting == null) { 11230 return PackageManager.INSTALL_FAILED_INVALID_URI; 11231 } 11232 if (!pkgSetting.getInstalled(userId)) { 11233 pkgSetting.setInstalled(true, userId); 11234 pkgSetting.setHidden(false, userId); 11235 mSettings.writePackageRestrictionsLPr(userId); 11236 installed = true; 11237 } 11238 } 11239 11240 if (installed) { 11241 if (pkgSetting.pkg != null) { 11242 prepareAppDataAfterInstall(pkgSetting.pkg); 11243 } 11244 sendPackageAddedForUser(packageName, pkgSetting, userId); 11245 } 11246 } finally { 11247 Binder.restoreCallingIdentity(callingId); 11248 } 11249 11250 return PackageManager.INSTALL_SUCCEEDED; 11251 } 11252 11253 boolean isUserRestricted(int userId, String restrictionKey) { 11254 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11255 if (restrictions.getBoolean(restrictionKey, false)) { 11256 Log.w(TAG, "User is restricted: " + restrictionKey); 11257 return true; 11258 } 11259 return false; 11260 } 11261 11262 @Override 11263 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11264 int userId) { 11265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11267 true /* requireFullPermission */, true /* checkShell */, 11268 "setPackagesSuspended for user " + userId); 11269 11270 if (ArrayUtils.isEmpty(packageNames)) { 11271 return packageNames; 11272 } 11273 11274 // List of package names for whom the suspended state has changed. 11275 List<String> changedPackages = new ArrayList<>(packageNames.length); 11276 // List of package names for whom the suspended state is not set as requested in this 11277 // method. 11278 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11279 for (int i = 0; i < packageNames.length; i++) { 11280 String packageName = packageNames[i]; 11281 long callingId = Binder.clearCallingIdentity(); 11282 try { 11283 boolean changed = false; 11284 final int appId; 11285 synchronized (mPackages) { 11286 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11287 if (pkgSetting == null) { 11288 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11289 + "\". Skipping suspending/un-suspending."); 11290 unactionedPackages.add(packageName); 11291 continue; 11292 } 11293 appId = pkgSetting.appId; 11294 if (pkgSetting.getSuspended(userId) != suspended) { 11295 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11296 unactionedPackages.add(packageName); 11297 continue; 11298 } 11299 pkgSetting.setSuspended(suspended, userId); 11300 mSettings.writePackageRestrictionsLPr(userId); 11301 changed = true; 11302 changedPackages.add(packageName); 11303 } 11304 } 11305 11306 if (changed && suspended) { 11307 killApplication(packageName, UserHandle.getUid(userId, appId), 11308 "suspending package"); 11309 } 11310 } finally { 11311 Binder.restoreCallingIdentity(callingId); 11312 } 11313 } 11314 11315 if (!changedPackages.isEmpty()) { 11316 sendPackagesSuspendedForUser(changedPackages.toArray( 11317 new String[changedPackages.size()]), userId, suspended); 11318 } 11319 11320 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11321 } 11322 11323 @Override 11324 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11325 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11326 true /* requireFullPermission */, false /* checkShell */, 11327 "isPackageSuspendedForUser for user " + userId); 11328 synchronized (mPackages) { 11329 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11330 if (pkgSetting == null) { 11331 throw new IllegalArgumentException("Unknown target package: " + packageName); 11332 } 11333 return pkgSetting.getSuspended(userId); 11334 } 11335 } 11336 11337 /** 11338 * TODO: cache and disallow blocking the active dialer. 11339 * 11340 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11341 */ 11342 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11343 if (isPackageDeviceAdmin(packageName, userId)) { 11344 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11345 + "\": has an active device admin"); 11346 return false; 11347 } 11348 11349 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11350 if (packageName.equals(activeLauncherPackageName)) { 11351 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11352 + "\": contains the active launcher"); 11353 return false; 11354 } 11355 11356 if (packageName.equals(mRequiredInstallerPackage)) { 11357 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11358 + "\": required for package installation"); 11359 return false; 11360 } 11361 11362 if (packageName.equals(mRequiredVerifierPackage)) { 11363 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11364 + "\": required for package verification"); 11365 return false; 11366 } 11367 11368 final PackageParser.Package pkg = mPackages.get(packageName); 11369 if (pkg != null && isPrivilegedApp(pkg)) { 11370 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11371 + "\": is a privileged app"); 11372 return false; 11373 } 11374 11375 return true; 11376 } 11377 11378 private String getActiveLauncherPackageName(int userId) { 11379 Intent intent = new Intent(Intent.ACTION_MAIN); 11380 intent.addCategory(Intent.CATEGORY_HOME); 11381 ResolveInfo resolveInfo = resolveIntent( 11382 intent, 11383 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11384 PackageManager.MATCH_DEFAULT_ONLY, 11385 userId); 11386 11387 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11388 } 11389 11390 @Override 11391 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11392 mContext.enforceCallingOrSelfPermission( 11393 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11394 "Only package verification agents can verify applications"); 11395 11396 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11397 final PackageVerificationResponse response = new PackageVerificationResponse( 11398 verificationCode, Binder.getCallingUid()); 11399 msg.arg1 = id; 11400 msg.obj = response; 11401 mHandler.sendMessage(msg); 11402 } 11403 11404 @Override 11405 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11406 long millisecondsToDelay) { 11407 mContext.enforceCallingOrSelfPermission( 11408 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11409 "Only package verification agents can extend verification timeouts"); 11410 11411 final PackageVerificationState state = mPendingVerification.get(id); 11412 final PackageVerificationResponse response = new PackageVerificationResponse( 11413 verificationCodeAtTimeout, Binder.getCallingUid()); 11414 11415 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11416 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11417 } 11418 if (millisecondsToDelay < 0) { 11419 millisecondsToDelay = 0; 11420 } 11421 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11422 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11423 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11424 } 11425 11426 if ((state != null) && !state.timeoutExtended()) { 11427 state.extendTimeout(); 11428 11429 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11430 msg.arg1 = id; 11431 msg.obj = response; 11432 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11433 } 11434 } 11435 11436 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11437 int verificationCode, UserHandle user) { 11438 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11439 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11440 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11441 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11442 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11443 11444 mContext.sendBroadcastAsUser(intent, user, 11445 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11446 } 11447 11448 private ComponentName matchComponentForVerifier(String packageName, 11449 List<ResolveInfo> receivers) { 11450 ActivityInfo targetReceiver = null; 11451 11452 final int NR = receivers.size(); 11453 for (int i = 0; i < NR; i++) { 11454 final ResolveInfo info = receivers.get(i); 11455 if (info.activityInfo == null) { 11456 continue; 11457 } 11458 11459 if (packageName.equals(info.activityInfo.packageName)) { 11460 targetReceiver = info.activityInfo; 11461 break; 11462 } 11463 } 11464 11465 if (targetReceiver == null) { 11466 return null; 11467 } 11468 11469 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11470 } 11471 11472 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11473 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11474 if (pkgInfo.verifiers.length == 0) { 11475 return null; 11476 } 11477 11478 final int N = pkgInfo.verifiers.length; 11479 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11480 for (int i = 0; i < N; i++) { 11481 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11482 11483 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11484 receivers); 11485 if (comp == null) { 11486 continue; 11487 } 11488 11489 final int verifierUid = getUidForVerifier(verifierInfo); 11490 if (verifierUid == -1) { 11491 continue; 11492 } 11493 11494 if (DEBUG_VERIFY) { 11495 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11496 + " with the correct signature"); 11497 } 11498 sufficientVerifiers.add(comp); 11499 verificationState.addSufficientVerifier(verifierUid); 11500 } 11501 11502 return sufficientVerifiers; 11503 } 11504 11505 private int getUidForVerifier(VerifierInfo verifierInfo) { 11506 synchronized (mPackages) { 11507 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11508 if (pkg == null) { 11509 return -1; 11510 } else if (pkg.mSignatures.length != 1) { 11511 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11512 + " has more than one signature; ignoring"); 11513 return -1; 11514 } 11515 11516 /* 11517 * If the public key of the package's signature does not match 11518 * our expected public key, then this is a different package and 11519 * we should skip. 11520 */ 11521 11522 final byte[] expectedPublicKey; 11523 try { 11524 final Signature verifierSig = pkg.mSignatures[0]; 11525 final PublicKey publicKey = verifierSig.getPublicKey(); 11526 expectedPublicKey = publicKey.getEncoded(); 11527 } catch (CertificateException e) { 11528 return -1; 11529 } 11530 11531 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11532 11533 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11534 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11535 + " does not have the expected public key; ignoring"); 11536 return -1; 11537 } 11538 11539 return pkg.applicationInfo.uid; 11540 } 11541 } 11542 11543 @Override 11544 public void finishPackageInstall(int token) { 11545 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11546 11547 if (DEBUG_INSTALL) { 11548 Slog.v(TAG, "BM finishing package install for " + token); 11549 } 11550 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11551 11552 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11553 mHandler.sendMessage(msg); 11554 } 11555 11556 /** 11557 * Get the verification agent timeout. 11558 * 11559 * @return verification timeout in milliseconds 11560 */ 11561 private long getVerificationTimeout() { 11562 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11563 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11564 DEFAULT_VERIFICATION_TIMEOUT); 11565 } 11566 11567 /** 11568 * Get the default verification agent response code. 11569 * 11570 * @return default verification response code 11571 */ 11572 private int getDefaultVerificationResponse() { 11573 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11574 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11575 DEFAULT_VERIFICATION_RESPONSE); 11576 } 11577 11578 /** 11579 * Check whether or not package verification has been enabled. 11580 * 11581 * @return true if verification should be performed 11582 */ 11583 private boolean isVerificationEnabled(int userId, int installFlags) { 11584 if (!DEFAULT_VERIFY_ENABLE) { 11585 return false; 11586 } 11587 // Ephemeral apps don't get the full verification treatment 11588 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11589 if (DEBUG_EPHEMERAL) { 11590 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11591 } 11592 return false; 11593 } 11594 11595 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11596 11597 // Check if installing from ADB 11598 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11599 // Do not run verification in a test harness environment 11600 if (ActivityManager.isRunningInTestHarness()) { 11601 return false; 11602 } 11603 if (ensureVerifyAppsEnabled) { 11604 return true; 11605 } 11606 // Check if the developer does not want package verification for ADB installs 11607 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11608 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11609 return false; 11610 } 11611 } 11612 11613 if (ensureVerifyAppsEnabled) { 11614 return true; 11615 } 11616 11617 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11618 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11619 } 11620 11621 @Override 11622 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11623 throws RemoteException { 11624 mContext.enforceCallingOrSelfPermission( 11625 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11626 "Only intentfilter verification agents can verify applications"); 11627 11628 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11629 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11630 Binder.getCallingUid(), verificationCode, failedDomains); 11631 msg.arg1 = id; 11632 msg.obj = response; 11633 mHandler.sendMessage(msg); 11634 } 11635 11636 @Override 11637 public int getIntentVerificationStatus(String packageName, int userId) { 11638 synchronized (mPackages) { 11639 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11640 } 11641 } 11642 11643 @Override 11644 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11645 mContext.enforceCallingOrSelfPermission( 11646 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11647 11648 boolean result = false; 11649 synchronized (mPackages) { 11650 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11651 } 11652 if (result) { 11653 scheduleWritePackageRestrictionsLocked(userId); 11654 } 11655 return result; 11656 } 11657 11658 @Override 11659 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11660 String packageName) { 11661 synchronized (mPackages) { 11662 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11663 } 11664 } 11665 11666 @Override 11667 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11668 if (TextUtils.isEmpty(packageName)) { 11669 return ParceledListSlice.emptyList(); 11670 } 11671 synchronized (mPackages) { 11672 PackageParser.Package pkg = mPackages.get(packageName); 11673 if (pkg == null || pkg.activities == null) { 11674 return ParceledListSlice.emptyList(); 11675 } 11676 final int count = pkg.activities.size(); 11677 ArrayList<IntentFilter> result = new ArrayList<>(); 11678 for (int n=0; n<count; n++) { 11679 PackageParser.Activity activity = pkg.activities.get(n); 11680 if (activity.intents != null && activity.intents.size() > 0) { 11681 result.addAll(activity.intents); 11682 } 11683 } 11684 return new ParceledListSlice<>(result); 11685 } 11686 } 11687 11688 @Override 11689 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11690 mContext.enforceCallingOrSelfPermission( 11691 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11692 11693 synchronized (mPackages) { 11694 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11695 if (packageName != null) { 11696 result |= updateIntentVerificationStatus(packageName, 11697 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11698 userId); 11699 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11700 packageName, userId); 11701 } 11702 return result; 11703 } 11704 } 11705 11706 @Override 11707 public String getDefaultBrowserPackageName(int userId) { 11708 synchronized (mPackages) { 11709 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11710 } 11711 } 11712 11713 /** 11714 * Get the "allow unknown sources" setting. 11715 * 11716 * @return the current "allow unknown sources" setting 11717 */ 11718 private int getUnknownSourcesSettings() { 11719 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11720 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11721 -1); 11722 } 11723 11724 @Override 11725 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11726 final int uid = Binder.getCallingUid(); 11727 // writer 11728 synchronized (mPackages) { 11729 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11730 if (targetPackageSetting == null) { 11731 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11732 } 11733 11734 PackageSetting installerPackageSetting; 11735 if (installerPackageName != null) { 11736 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11737 if (installerPackageSetting == null) { 11738 throw new IllegalArgumentException("Unknown installer package: " 11739 + installerPackageName); 11740 } 11741 } else { 11742 installerPackageSetting = null; 11743 } 11744 11745 Signature[] callerSignature; 11746 Object obj = mSettings.getUserIdLPr(uid); 11747 if (obj != null) { 11748 if (obj instanceof SharedUserSetting) { 11749 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11750 } else if (obj instanceof PackageSetting) { 11751 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11752 } else { 11753 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11754 } 11755 } else { 11756 throw new SecurityException("Unknown calling UID: " + uid); 11757 } 11758 11759 // Verify: can't set installerPackageName to a package that is 11760 // not signed with the same cert as the caller. 11761 if (installerPackageSetting != null) { 11762 if (compareSignatures(callerSignature, 11763 installerPackageSetting.signatures.mSignatures) 11764 != PackageManager.SIGNATURE_MATCH) { 11765 throw new SecurityException( 11766 "Caller does not have same cert as new installer package " 11767 + installerPackageName); 11768 } 11769 } 11770 11771 // Verify: if target already has an installer package, it must 11772 // be signed with the same cert as the caller. 11773 if (targetPackageSetting.installerPackageName != null) { 11774 PackageSetting setting = mSettings.mPackages.get( 11775 targetPackageSetting.installerPackageName); 11776 // If the currently set package isn't valid, then it's always 11777 // okay to change it. 11778 if (setting != null) { 11779 if (compareSignatures(callerSignature, 11780 setting.signatures.mSignatures) 11781 != PackageManager.SIGNATURE_MATCH) { 11782 throw new SecurityException( 11783 "Caller does not have same cert as old installer package " 11784 + targetPackageSetting.installerPackageName); 11785 } 11786 } 11787 } 11788 11789 // Okay! 11790 targetPackageSetting.installerPackageName = installerPackageName; 11791 if (installerPackageName != null) { 11792 mSettings.mInstallerPackages.add(installerPackageName); 11793 } 11794 scheduleWriteSettingsLocked(); 11795 } 11796 } 11797 11798 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11799 // Queue up an async operation since the package installation may take a little while. 11800 mHandler.post(new Runnable() { 11801 public void run() { 11802 mHandler.removeCallbacks(this); 11803 // Result object to be returned 11804 PackageInstalledInfo res = new PackageInstalledInfo(); 11805 res.setReturnCode(currentStatus); 11806 res.uid = -1; 11807 res.pkg = null; 11808 res.removedInfo = null; 11809 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11810 args.doPreInstall(res.returnCode); 11811 synchronized (mInstallLock) { 11812 installPackageTracedLI(args, res); 11813 } 11814 args.doPostInstall(res.returnCode, res.uid); 11815 } 11816 11817 // A restore should be performed at this point if (a) the install 11818 // succeeded, (b) the operation is not an update, and (c) the new 11819 // package has not opted out of backup participation. 11820 final boolean update = res.removedInfo != null 11821 && res.removedInfo.removedPackage != null; 11822 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11823 boolean doRestore = !update 11824 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11825 11826 // Set up the post-install work request bookkeeping. This will be used 11827 // and cleaned up by the post-install event handling regardless of whether 11828 // there's a restore pass performed. Token values are >= 1. 11829 int token; 11830 if (mNextInstallToken < 0) mNextInstallToken = 1; 11831 token = mNextInstallToken++; 11832 11833 PostInstallData data = new PostInstallData(args, res); 11834 mRunningInstalls.put(token, data); 11835 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11836 11837 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11838 // Pass responsibility to the Backup Manager. It will perform a 11839 // restore if appropriate, then pass responsibility back to the 11840 // Package Manager to run the post-install observer callbacks 11841 // and broadcasts. 11842 IBackupManager bm = IBackupManager.Stub.asInterface( 11843 ServiceManager.getService(Context.BACKUP_SERVICE)); 11844 if (bm != null) { 11845 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11846 + " to BM for possible restore"); 11847 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11848 try { 11849 // TODO: http://b/22388012 11850 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11851 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11852 } else { 11853 doRestore = false; 11854 } 11855 } catch (RemoteException e) { 11856 // can't happen; the backup manager is local 11857 } catch (Exception e) { 11858 Slog.e(TAG, "Exception trying to enqueue restore", e); 11859 doRestore = false; 11860 } 11861 } else { 11862 Slog.e(TAG, "Backup Manager not found!"); 11863 doRestore = false; 11864 } 11865 } 11866 11867 if (!doRestore) { 11868 // No restore possible, or the Backup Manager was mysteriously not 11869 // available -- just fire the post-install work request directly. 11870 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11871 11872 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11873 11874 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11875 mHandler.sendMessage(msg); 11876 } 11877 } 11878 }); 11879 } 11880 11881 private abstract class HandlerParams { 11882 private static final int MAX_RETRIES = 4; 11883 11884 /** 11885 * Number of times startCopy() has been attempted and had a non-fatal 11886 * error. 11887 */ 11888 private int mRetries = 0; 11889 11890 /** User handle for the user requesting the information or installation. */ 11891 private final UserHandle mUser; 11892 String traceMethod; 11893 int traceCookie; 11894 11895 HandlerParams(UserHandle user) { 11896 mUser = user; 11897 } 11898 11899 UserHandle getUser() { 11900 return mUser; 11901 } 11902 11903 HandlerParams setTraceMethod(String traceMethod) { 11904 this.traceMethod = traceMethod; 11905 return this; 11906 } 11907 11908 HandlerParams setTraceCookie(int traceCookie) { 11909 this.traceCookie = traceCookie; 11910 return this; 11911 } 11912 11913 final boolean startCopy() { 11914 boolean res; 11915 try { 11916 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11917 11918 if (++mRetries > MAX_RETRIES) { 11919 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11920 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11921 handleServiceError(); 11922 return false; 11923 } else { 11924 handleStartCopy(); 11925 res = true; 11926 } 11927 } catch (RemoteException e) { 11928 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11929 mHandler.sendEmptyMessage(MCS_RECONNECT); 11930 res = false; 11931 } 11932 handleReturnCode(); 11933 return res; 11934 } 11935 11936 final void serviceError() { 11937 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11938 handleServiceError(); 11939 handleReturnCode(); 11940 } 11941 11942 abstract void handleStartCopy() throws RemoteException; 11943 abstract void handleServiceError(); 11944 abstract void handleReturnCode(); 11945 } 11946 11947 class MeasureParams extends HandlerParams { 11948 private final PackageStats mStats; 11949 private boolean mSuccess; 11950 11951 private final IPackageStatsObserver mObserver; 11952 11953 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11954 super(new UserHandle(stats.userHandle)); 11955 mObserver = observer; 11956 mStats = stats; 11957 } 11958 11959 @Override 11960 public String toString() { 11961 return "MeasureParams{" 11962 + Integer.toHexString(System.identityHashCode(this)) 11963 + " " + mStats.packageName + "}"; 11964 } 11965 11966 @Override 11967 void handleStartCopy() throws RemoteException { 11968 synchronized (mInstallLock) { 11969 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11970 } 11971 11972 if (mSuccess) { 11973 final boolean mounted; 11974 if (Environment.isExternalStorageEmulated()) { 11975 mounted = true; 11976 } else { 11977 final String status = Environment.getExternalStorageState(); 11978 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11979 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11980 } 11981 11982 if (mounted) { 11983 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11984 11985 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11986 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11987 11988 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11989 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11990 11991 // Always subtract cache size, since it's a subdirectory 11992 mStats.externalDataSize -= mStats.externalCacheSize; 11993 11994 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11995 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11996 11997 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11998 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11999 } 12000 } 12001 } 12002 12003 @Override 12004 void handleReturnCode() { 12005 if (mObserver != null) { 12006 try { 12007 mObserver.onGetStatsCompleted(mStats, mSuccess); 12008 } catch (RemoteException e) { 12009 Slog.i(TAG, "Observer no longer exists."); 12010 } 12011 } 12012 } 12013 12014 @Override 12015 void handleServiceError() { 12016 Slog.e(TAG, "Could not measure application " + mStats.packageName 12017 + " external storage"); 12018 } 12019 } 12020 12021 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12022 throws RemoteException { 12023 long result = 0; 12024 for (File path : paths) { 12025 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12026 } 12027 return result; 12028 } 12029 12030 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12031 for (File path : paths) { 12032 try { 12033 mcs.clearDirectory(path.getAbsolutePath()); 12034 } catch (RemoteException e) { 12035 } 12036 } 12037 } 12038 12039 static class OriginInfo { 12040 /** 12041 * Location where install is coming from, before it has been 12042 * copied/renamed into place. This could be a single monolithic APK 12043 * file, or a cluster directory. This location may be untrusted. 12044 */ 12045 final File file; 12046 final String cid; 12047 12048 /** 12049 * Flag indicating that {@link #file} or {@link #cid} has already been 12050 * staged, meaning downstream users don't need to defensively copy the 12051 * contents. 12052 */ 12053 final boolean staged; 12054 12055 /** 12056 * Flag indicating that {@link #file} or {@link #cid} is an already 12057 * installed app that is being moved. 12058 */ 12059 final boolean existing; 12060 12061 final String resolvedPath; 12062 final File resolvedFile; 12063 12064 static OriginInfo fromNothing() { 12065 return new OriginInfo(null, null, false, false); 12066 } 12067 12068 static OriginInfo fromUntrustedFile(File file) { 12069 return new OriginInfo(file, null, false, false); 12070 } 12071 12072 static OriginInfo fromExistingFile(File file) { 12073 return new OriginInfo(file, null, false, true); 12074 } 12075 12076 static OriginInfo fromStagedFile(File file) { 12077 return new OriginInfo(file, null, true, false); 12078 } 12079 12080 static OriginInfo fromStagedContainer(String cid) { 12081 return new OriginInfo(null, cid, true, false); 12082 } 12083 12084 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12085 this.file = file; 12086 this.cid = cid; 12087 this.staged = staged; 12088 this.existing = existing; 12089 12090 if (cid != null) { 12091 resolvedPath = PackageHelper.getSdDir(cid); 12092 resolvedFile = new File(resolvedPath); 12093 } else if (file != null) { 12094 resolvedPath = file.getAbsolutePath(); 12095 resolvedFile = file; 12096 } else { 12097 resolvedPath = null; 12098 resolvedFile = null; 12099 } 12100 } 12101 } 12102 12103 static class MoveInfo { 12104 final int moveId; 12105 final String fromUuid; 12106 final String toUuid; 12107 final String packageName; 12108 final String dataAppName; 12109 final int appId; 12110 final String seinfo; 12111 final int targetSdkVersion; 12112 12113 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12114 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12115 this.moveId = moveId; 12116 this.fromUuid = fromUuid; 12117 this.toUuid = toUuid; 12118 this.packageName = packageName; 12119 this.dataAppName = dataAppName; 12120 this.appId = appId; 12121 this.seinfo = seinfo; 12122 this.targetSdkVersion = targetSdkVersion; 12123 } 12124 } 12125 12126 static class VerificationInfo { 12127 /** A constant used to indicate that a uid value is not present. */ 12128 public static final int NO_UID = -1; 12129 12130 /** URI referencing where the package was downloaded from. */ 12131 final Uri originatingUri; 12132 12133 /** HTTP referrer URI associated with the originatingURI. */ 12134 final Uri referrer; 12135 12136 /** UID of the application that the install request originated from. */ 12137 final int originatingUid; 12138 12139 /** UID of application requesting the install */ 12140 final int installerUid; 12141 12142 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12143 this.originatingUri = originatingUri; 12144 this.referrer = referrer; 12145 this.originatingUid = originatingUid; 12146 this.installerUid = installerUid; 12147 } 12148 } 12149 12150 class InstallParams extends HandlerParams { 12151 final OriginInfo origin; 12152 final MoveInfo move; 12153 final IPackageInstallObserver2 observer; 12154 int installFlags; 12155 final String installerPackageName; 12156 final String volumeUuid; 12157 private InstallArgs mArgs; 12158 private int mRet; 12159 final String packageAbiOverride; 12160 final String[] grantedRuntimePermissions; 12161 final VerificationInfo verificationInfo; 12162 final Certificate[][] certificates; 12163 12164 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12165 int installFlags, String installerPackageName, String volumeUuid, 12166 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12167 String[] grantedPermissions, Certificate[][] certificates) { 12168 super(user); 12169 this.origin = origin; 12170 this.move = move; 12171 this.observer = observer; 12172 this.installFlags = installFlags; 12173 this.installerPackageName = installerPackageName; 12174 this.volumeUuid = volumeUuid; 12175 this.verificationInfo = verificationInfo; 12176 this.packageAbiOverride = packageAbiOverride; 12177 this.grantedRuntimePermissions = grantedPermissions; 12178 this.certificates = certificates; 12179 } 12180 12181 @Override 12182 public String toString() { 12183 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12184 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12185 } 12186 12187 private int installLocationPolicy(PackageInfoLite pkgLite) { 12188 String packageName = pkgLite.packageName; 12189 int installLocation = pkgLite.installLocation; 12190 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12191 // reader 12192 synchronized (mPackages) { 12193 // Currently installed package which the new package is attempting to replace or 12194 // null if no such package is installed. 12195 PackageParser.Package installedPkg = mPackages.get(packageName); 12196 // Package which currently owns the data which the new package will own if installed. 12197 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12198 // will be null whereas dataOwnerPkg will contain information about the package 12199 // which was uninstalled while keeping its data. 12200 PackageParser.Package dataOwnerPkg = installedPkg; 12201 if (dataOwnerPkg == null) { 12202 PackageSetting ps = mSettings.mPackages.get(packageName); 12203 if (ps != null) { 12204 dataOwnerPkg = ps.pkg; 12205 } 12206 } 12207 12208 if (dataOwnerPkg != null) { 12209 // If installed, the package will get access to data left on the device by its 12210 // predecessor. As a security measure, this is permited only if this is not a 12211 // version downgrade or if the predecessor package is marked as debuggable and 12212 // a downgrade is explicitly requested. 12213 // 12214 // On debuggable platform builds, downgrades are permitted even for 12215 // non-debuggable packages to make testing easier. Debuggable platform builds do 12216 // not offer security guarantees and thus it's OK to disable some security 12217 // mechanisms to make debugging/testing easier on those builds. However, even on 12218 // debuggable builds downgrades of packages are permitted only if requested via 12219 // installFlags. This is because we aim to keep the behavior of debuggable 12220 // platform builds as close as possible to the behavior of non-debuggable 12221 // platform builds. 12222 final boolean downgradeRequested = 12223 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12224 final boolean packageDebuggable = 12225 (dataOwnerPkg.applicationInfo.flags 12226 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12227 final boolean downgradePermitted = 12228 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12229 if (!downgradePermitted) { 12230 try { 12231 checkDowngrade(dataOwnerPkg, pkgLite); 12232 } catch (PackageManagerException e) { 12233 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12234 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12235 } 12236 } 12237 } 12238 12239 if (installedPkg != null) { 12240 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12241 // Check for updated system application. 12242 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12243 if (onSd) { 12244 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12245 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12246 } 12247 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12248 } else { 12249 if (onSd) { 12250 // Install flag overrides everything. 12251 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12252 } 12253 // If current upgrade specifies particular preference 12254 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12255 // Application explicitly specified internal. 12256 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12257 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12258 // App explictly prefers external. Let policy decide 12259 } else { 12260 // Prefer previous location 12261 if (isExternal(installedPkg)) { 12262 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12263 } 12264 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12265 } 12266 } 12267 } else { 12268 // Invalid install. Return error code 12269 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12270 } 12271 } 12272 } 12273 // All the special cases have been taken care of. 12274 // Return result based on recommended install location. 12275 if (onSd) { 12276 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12277 } 12278 return pkgLite.recommendedInstallLocation; 12279 } 12280 12281 /* 12282 * Invoke remote method to get package information and install 12283 * location values. Override install location based on default 12284 * policy if needed and then create install arguments based 12285 * on the install location. 12286 */ 12287 public void handleStartCopy() throws RemoteException { 12288 int ret = PackageManager.INSTALL_SUCCEEDED; 12289 12290 // If we're already staged, we've firmly committed to an install location 12291 if (origin.staged) { 12292 if (origin.file != null) { 12293 installFlags |= PackageManager.INSTALL_INTERNAL; 12294 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12295 } else if (origin.cid != null) { 12296 installFlags |= PackageManager.INSTALL_EXTERNAL; 12297 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12298 } else { 12299 throw new IllegalStateException("Invalid stage location"); 12300 } 12301 } 12302 12303 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12304 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12305 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12306 PackageInfoLite pkgLite = null; 12307 12308 if (onInt && onSd) { 12309 // Check if both bits are set. 12310 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12311 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12312 } else if (onSd && ephemeral) { 12313 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12314 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12315 } else { 12316 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12317 packageAbiOverride); 12318 12319 if (DEBUG_EPHEMERAL && ephemeral) { 12320 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12321 } 12322 12323 /* 12324 * If we have too little free space, try to free cache 12325 * before giving up. 12326 */ 12327 if (!origin.staged && pkgLite.recommendedInstallLocation 12328 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12329 // TODO: focus freeing disk space on the target device 12330 final StorageManager storage = StorageManager.from(mContext); 12331 final long lowThreshold = storage.getStorageLowBytes( 12332 Environment.getDataDirectory()); 12333 12334 final long sizeBytes = mContainerService.calculateInstalledSize( 12335 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12336 12337 try { 12338 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12339 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12340 installFlags, packageAbiOverride); 12341 } catch (InstallerException e) { 12342 Slog.w(TAG, "Failed to free cache", e); 12343 } 12344 12345 /* 12346 * The cache free must have deleted the file we 12347 * downloaded to install. 12348 * 12349 * TODO: fix the "freeCache" call to not delete 12350 * the file we care about. 12351 */ 12352 if (pkgLite.recommendedInstallLocation 12353 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12354 pkgLite.recommendedInstallLocation 12355 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12356 } 12357 } 12358 } 12359 12360 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12361 int loc = pkgLite.recommendedInstallLocation; 12362 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12363 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12364 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12365 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12366 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12367 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12368 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12369 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12370 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12371 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12372 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12373 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12374 } else { 12375 // Override with defaults if needed. 12376 loc = installLocationPolicy(pkgLite); 12377 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12378 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12379 } else if (!onSd && !onInt) { 12380 // Override install location with flags 12381 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12382 // Set the flag to install on external media. 12383 installFlags |= PackageManager.INSTALL_EXTERNAL; 12384 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12385 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12386 if (DEBUG_EPHEMERAL) { 12387 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12388 } 12389 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12390 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12391 |PackageManager.INSTALL_INTERNAL); 12392 } else { 12393 // Make sure the flag for installing on external 12394 // media is unset 12395 installFlags |= PackageManager.INSTALL_INTERNAL; 12396 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12397 } 12398 } 12399 } 12400 } 12401 12402 final InstallArgs args = createInstallArgs(this); 12403 mArgs = args; 12404 12405 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12406 // TODO: http://b/22976637 12407 // Apps installed for "all" users use the device owner to verify the app 12408 UserHandle verifierUser = getUser(); 12409 if (verifierUser == UserHandle.ALL) { 12410 verifierUser = UserHandle.SYSTEM; 12411 } 12412 12413 /* 12414 * Determine if we have any installed package verifiers. If we 12415 * do, then we'll defer to them to verify the packages. 12416 */ 12417 final int requiredUid = mRequiredVerifierPackage == null ? -1 12418 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12419 verifierUser.getIdentifier()); 12420 if (!origin.existing && requiredUid != -1 12421 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12422 final Intent verification = new Intent( 12423 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12424 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12425 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12426 PACKAGE_MIME_TYPE); 12427 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12428 12429 // Query all live verifiers based on current user state 12430 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12431 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12432 12433 if (DEBUG_VERIFY) { 12434 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12435 + verification.toString() + " with " + pkgLite.verifiers.length 12436 + " optional verifiers"); 12437 } 12438 12439 final int verificationId = mPendingVerificationToken++; 12440 12441 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12442 12443 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12444 installerPackageName); 12445 12446 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12447 installFlags); 12448 12449 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12450 pkgLite.packageName); 12451 12452 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12453 pkgLite.versionCode); 12454 12455 if (verificationInfo != null) { 12456 if (verificationInfo.originatingUri != null) { 12457 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12458 verificationInfo.originatingUri); 12459 } 12460 if (verificationInfo.referrer != null) { 12461 verification.putExtra(Intent.EXTRA_REFERRER, 12462 verificationInfo.referrer); 12463 } 12464 if (verificationInfo.originatingUid >= 0) { 12465 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12466 verificationInfo.originatingUid); 12467 } 12468 if (verificationInfo.installerUid >= 0) { 12469 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12470 verificationInfo.installerUid); 12471 } 12472 } 12473 12474 final PackageVerificationState verificationState = new PackageVerificationState( 12475 requiredUid, args); 12476 12477 mPendingVerification.append(verificationId, verificationState); 12478 12479 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12480 receivers, verificationState); 12481 12482 /* 12483 * If any sufficient verifiers were listed in the package 12484 * manifest, attempt to ask them. 12485 */ 12486 if (sufficientVerifiers != null) { 12487 final int N = sufficientVerifiers.size(); 12488 if (N == 0) { 12489 Slog.i(TAG, "Additional verifiers required, but none installed."); 12490 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12491 } else { 12492 for (int i = 0; i < N; i++) { 12493 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12494 12495 final Intent sufficientIntent = new Intent(verification); 12496 sufficientIntent.setComponent(verifierComponent); 12497 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12498 } 12499 } 12500 } 12501 12502 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12503 mRequiredVerifierPackage, receivers); 12504 if (ret == PackageManager.INSTALL_SUCCEEDED 12505 && mRequiredVerifierPackage != null) { 12506 Trace.asyncTraceBegin( 12507 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12508 /* 12509 * Send the intent to the required verification agent, 12510 * but only start the verification timeout after the 12511 * target BroadcastReceivers have run. 12512 */ 12513 verification.setComponent(requiredVerifierComponent); 12514 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12515 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12516 new BroadcastReceiver() { 12517 @Override 12518 public void onReceive(Context context, Intent intent) { 12519 final Message msg = mHandler 12520 .obtainMessage(CHECK_PENDING_VERIFICATION); 12521 msg.arg1 = verificationId; 12522 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12523 } 12524 }, null, 0, null, null); 12525 12526 /* 12527 * We don't want the copy to proceed until verification 12528 * succeeds, so null out this field. 12529 */ 12530 mArgs = null; 12531 } 12532 } else { 12533 /* 12534 * No package verification is enabled, so immediately start 12535 * the remote call to initiate copy using temporary file. 12536 */ 12537 ret = args.copyApk(mContainerService, true); 12538 } 12539 } 12540 12541 mRet = ret; 12542 } 12543 12544 @Override 12545 void handleReturnCode() { 12546 // If mArgs is null, then MCS couldn't be reached. When it 12547 // reconnects, it will try again to install. At that point, this 12548 // will succeed. 12549 if (mArgs != null) { 12550 processPendingInstall(mArgs, mRet); 12551 } 12552 } 12553 12554 @Override 12555 void handleServiceError() { 12556 mArgs = createInstallArgs(this); 12557 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12558 } 12559 12560 public boolean isForwardLocked() { 12561 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12562 } 12563 } 12564 12565 /** 12566 * Used during creation of InstallArgs 12567 * 12568 * @param installFlags package installation flags 12569 * @return true if should be installed on external storage 12570 */ 12571 private static boolean installOnExternalAsec(int installFlags) { 12572 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12573 return false; 12574 } 12575 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12576 return true; 12577 } 12578 return false; 12579 } 12580 12581 /** 12582 * Used during creation of InstallArgs 12583 * 12584 * @param installFlags package installation flags 12585 * @return true if should be installed as forward locked 12586 */ 12587 private static boolean installForwardLocked(int installFlags) { 12588 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12589 } 12590 12591 private InstallArgs createInstallArgs(InstallParams params) { 12592 if (params.move != null) { 12593 return new MoveInstallArgs(params); 12594 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12595 return new AsecInstallArgs(params); 12596 } else { 12597 return new FileInstallArgs(params); 12598 } 12599 } 12600 12601 /** 12602 * Create args that describe an existing installed package. Typically used 12603 * when cleaning up old installs, or used as a move source. 12604 */ 12605 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12606 String resourcePath, String[] instructionSets) { 12607 final boolean isInAsec; 12608 if (installOnExternalAsec(installFlags)) { 12609 /* Apps on SD card are always in ASEC containers. */ 12610 isInAsec = true; 12611 } else if (installForwardLocked(installFlags) 12612 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12613 /* 12614 * Forward-locked apps are only in ASEC containers if they're the 12615 * new style 12616 */ 12617 isInAsec = true; 12618 } else { 12619 isInAsec = false; 12620 } 12621 12622 if (isInAsec) { 12623 return new AsecInstallArgs(codePath, instructionSets, 12624 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12625 } else { 12626 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12627 } 12628 } 12629 12630 static abstract class InstallArgs { 12631 /** @see InstallParams#origin */ 12632 final OriginInfo origin; 12633 /** @see InstallParams#move */ 12634 final MoveInfo move; 12635 12636 final IPackageInstallObserver2 observer; 12637 // Always refers to PackageManager flags only 12638 final int installFlags; 12639 final String installerPackageName; 12640 final String volumeUuid; 12641 final UserHandle user; 12642 final String abiOverride; 12643 final String[] installGrantPermissions; 12644 /** If non-null, drop an async trace when the install completes */ 12645 final String traceMethod; 12646 final int traceCookie; 12647 final Certificate[][] certificates; 12648 12649 // The list of instruction sets supported by this app. This is currently 12650 // only used during the rmdex() phase to clean up resources. We can get rid of this 12651 // if we move dex files under the common app path. 12652 /* nullable */ String[] instructionSets; 12653 12654 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12655 int installFlags, String installerPackageName, String volumeUuid, 12656 UserHandle user, String[] instructionSets, 12657 String abiOverride, String[] installGrantPermissions, 12658 String traceMethod, int traceCookie, Certificate[][] certificates) { 12659 this.origin = origin; 12660 this.move = move; 12661 this.installFlags = installFlags; 12662 this.observer = observer; 12663 this.installerPackageName = installerPackageName; 12664 this.volumeUuid = volumeUuid; 12665 this.user = user; 12666 this.instructionSets = instructionSets; 12667 this.abiOverride = abiOverride; 12668 this.installGrantPermissions = installGrantPermissions; 12669 this.traceMethod = traceMethod; 12670 this.traceCookie = traceCookie; 12671 this.certificates = certificates; 12672 } 12673 12674 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12675 abstract int doPreInstall(int status); 12676 12677 /** 12678 * Rename package into final resting place. All paths on the given 12679 * scanned package should be updated to reflect the rename. 12680 */ 12681 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12682 abstract int doPostInstall(int status, int uid); 12683 12684 /** @see PackageSettingBase#codePathString */ 12685 abstract String getCodePath(); 12686 /** @see PackageSettingBase#resourcePathString */ 12687 abstract String getResourcePath(); 12688 12689 // Need installer lock especially for dex file removal. 12690 abstract void cleanUpResourcesLI(); 12691 abstract boolean doPostDeleteLI(boolean delete); 12692 12693 /** 12694 * Called before the source arguments are copied. This is used mostly 12695 * for MoveParams when it needs to read the source file to put it in the 12696 * destination. 12697 */ 12698 int doPreCopy() { 12699 return PackageManager.INSTALL_SUCCEEDED; 12700 } 12701 12702 /** 12703 * Called after the source arguments are copied. This is used mostly for 12704 * MoveParams when it needs to read the source file to put it in the 12705 * destination. 12706 */ 12707 int doPostCopy(int uid) { 12708 return PackageManager.INSTALL_SUCCEEDED; 12709 } 12710 12711 protected boolean isFwdLocked() { 12712 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12713 } 12714 12715 protected boolean isExternalAsec() { 12716 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12717 } 12718 12719 protected boolean isEphemeral() { 12720 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12721 } 12722 12723 UserHandle getUser() { 12724 return user; 12725 } 12726 } 12727 12728 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12729 if (!allCodePaths.isEmpty()) { 12730 if (instructionSets == null) { 12731 throw new IllegalStateException("instructionSet == null"); 12732 } 12733 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12734 for (String codePath : allCodePaths) { 12735 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12736 try { 12737 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12738 } catch (InstallerException ignored) { 12739 } 12740 } 12741 } 12742 } 12743 } 12744 12745 /** 12746 * Logic to handle installation of non-ASEC applications, including copying 12747 * and renaming logic. 12748 */ 12749 class FileInstallArgs extends InstallArgs { 12750 private File codeFile; 12751 private File resourceFile; 12752 12753 // Example topology: 12754 // /data/app/com.example/base.apk 12755 // /data/app/com.example/split_foo.apk 12756 // /data/app/com.example/lib/arm/libfoo.so 12757 // /data/app/com.example/lib/arm64/libfoo.so 12758 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12759 12760 /** New install */ 12761 FileInstallArgs(InstallParams params) { 12762 super(params.origin, params.move, params.observer, params.installFlags, 12763 params.installerPackageName, params.volumeUuid, 12764 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12765 params.grantedRuntimePermissions, 12766 params.traceMethod, params.traceCookie, params.certificates); 12767 if (isFwdLocked()) { 12768 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12769 } 12770 } 12771 12772 /** Existing install */ 12773 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12774 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12775 null, null, null, 0, null /*certificates*/); 12776 this.codeFile = (codePath != null) ? new File(codePath) : null; 12777 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12778 } 12779 12780 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12782 try { 12783 return doCopyApk(imcs, temp); 12784 } finally { 12785 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12786 } 12787 } 12788 12789 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12790 if (origin.staged) { 12791 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12792 codeFile = origin.file; 12793 resourceFile = origin.file; 12794 return PackageManager.INSTALL_SUCCEEDED; 12795 } 12796 12797 try { 12798 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12799 final File tempDir = 12800 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12801 codeFile = tempDir; 12802 resourceFile = tempDir; 12803 } catch (IOException e) { 12804 Slog.w(TAG, "Failed to create copy file: " + e); 12805 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12806 } 12807 12808 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12809 @Override 12810 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12811 if (!FileUtils.isValidExtFilename(name)) { 12812 throw new IllegalArgumentException("Invalid filename: " + name); 12813 } 12814 try { 12815 final File file = new File(codeFile, name); 12816 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12817 O_RDWR | O_CREAT, 0644); 12818 Os.chmod(file.getAbsolutePath(), 0644); 12819 return new ParcelFileDescriptor(fd); 12820 } catch (ErrnoException e) { 12821 throw new RemoteException("Failed to open: " + e.getMessage()); 12822 } 12823 } 12824 }; 12825 12826 int ret = PackageManager.INSTALL_SUCCEEDED; 12827 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12828 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12829 Slog.e(TAG, "Failed to copy package"); 12830 return ret; 12831 } 12832 12833 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12834 NativeLibraryHelper.Handle handle = null; 12835 try { 12836 handle = NativeLibraryHelper.Handle.create(codeFile); 12837 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12838 abiOverride); 12839 } catch (IOException e) { 12840 Slog.e(TAG, "Copying native libraries failed", e); 12841 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12842 } finally { 12843 IoUtils.closeQuietly(handle); 12844 } 12845 12846 return ret; 12847 } 12848 12849 int doPreInstall(int status) { 12850 if (status != PackageManager.INSTALL_SUCCEEDED) { 12851 cleanUp(); 12852 } 12853 return status; 12854 } 12855 12856 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12857 if (status != PackageManager.INSTALL_SUCCEEDED) { 12858 cleanUp(); 12859 return false; 12860 } 12861 12862 final File targetDir = codeFile.getParentFile(); 12863 final File beforeCodeFile = codeFile; 12864 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12865 12866 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12867 try { 12868 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12869 } catch (ErrnoException e) { 12870 Slog.w(TAG, "Failed to rename", e); 12871 return false; 12872 } 12873 12874 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12875 Slog.w(TAG, "Failed to restorecon"); 12876 return false; 12877 } 12878 12879 // Reflect the rename internally 12880 codeFile = afterCodeFile; 12881 resourceFile = afterCodeFile; 12882 12883 // Reflect the rename in scanned details 12884 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12885 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12886 afterCodeFile, pkg.baseCodePath)); 12887 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12888 afterCodeFile, pkg.splitCodePaths)); 12889 12890 // Reflect the rename in app info 12891 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12892 pkg.setApplicationInfoCodePath(pkg.codePath); 12893 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12894 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12895 pkg.setApplicationInfoResourcePath(pkg.codePath); 12896 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12897 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12898 12899 return true; 12900 } 12901 12902 int doPostInstall(int status, int uid) { 12903 if (status != PackageManager.INSTALL_SUCCEEDED) { 12904 cleanUp(); 12905 } 12906 return status; 12907 } 12908 12909 @Override 12910 String getCodePath() { 12911 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12912 } 12913 12914 @Override 12915 String getResourcePath() { 12916 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12917 } 12918 12919 private boolean cleanUp() { 12920 if (codeFile == null || !codeFile.exists()) { 12921 return false; 12922 } 12923 12924 removeCodePathLI(codeFile); 12925 12926 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12927 resourceFile.delete(); 12928 } 12929 12930 return true; 12931 } 12932 12933 void cleanUpResourcesLI() { 12934 // Try enumerating all code paths before deleting 12935 List<String> allCodePaths = Collections.EMPTY_LIST; 12936 if (codeFile != null && codeFile.exists()) { 12937 try { 12938 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12939 allCodePaths = pkg.getAllCodePaths(); 12940 } catch (PackageParserException e) { 12941 // Ignored; we tried our best 12942 } 12943 } 12944 12945 cleanUp(); 12946 removeDexFiles(allCodePaths, instructionSets); 12947 } 12948 12949 boolean doPostDeleteLI(boolean delete) { 12950 // XXX err, shouldn't we respect the delete flag? 12951 cleanUpResourcesLI(); 12952 return true; 12953 } 12954 } 12955 12956 private boolean isAsecExternal(String cid) { 12957 final String asecPath = PackageHelper.getSdFilesystem(cid); 12958 return !asecPath.startsWith(mAsecInternalPath); 12959 } 12960 12961 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12962 PackageManagerException { 12963 if (copyRet < 0) { 12964 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12965 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12966 throw new PackageManagerException(copyRet, message); 12967 } 12968 } 12969 } 12970 12971 /** 12972 * Extract the MountService "container ID" from the full code path of an 12973 * .apk. 12974 */ 12975 static String cidFromCodePath(String fullCodePath) { 12976 int eidx = fullCodePath.lastIndexOf("/"); 12977 String subStr1 = fullCodePath.substring(0, eidx); 12978 int sidx = subStr1.lastIndexOf("/"); 12979 return subStr1.substring(sidx+1, eidx); 12980 } 12981 12982 /** 12983 * Logic to handle installation of ASEC applications, including copying and 12984 * renaming logic. 12985 */ 12986 class AsecInstallArgs extends InstallArgs { 12987 static final String RES_FILE_NAME = "pkg.apk"; 12988 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12989 12990 String cid; 12991 String packagePath; 12992 String resourcePath; 12993 12994 /** New install */ 12995 AsecInstallArgs(InstallParams params) { 12996 super(params.origin, params.move, params.observer, params.installFlags, 12997 params.installerPackageName, params.volumeUuid, 12998 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12999 params.grantedRuntimePermissions, 13000 params.traceMethod, params.traceCookie, params.certificates); 13001 } 13002 13003 /** Existing install */ 13004 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13005 boolean isExternal, boolean isForwardLocked) { 13006 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13007 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13008 instructionSets, null, null, null, 0, null /*certificates*/); 13009 // Hackily pretend we're still looking at a full code path 13010 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13011 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13012 } 13013 13014 // Extract cid from fullCodePath 13015 int eidx = fullCodePath.lastIndexOf("/"); 13016 String subStr1 = fullCodePath.substring(0, eidx); 13017 int sidx = subStr1.lastIndexOf("/"); 13018 cid = subStr1.substring(sidx+1, eidx); 13019 setMountPath(subStr1); 13020 } 13021 13022 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13023 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13024 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13025 instructionSets, null, null, null, 0, null /*certificates*/); 13026 this.cid = cid; 13027 setMountPath(PackageHelper.getSdDir(cid)); 13028 } 13029 13030 void createCopyFile() { 13031 cid = mInstallerService.allocateExternalStageCidLegacy(); 13032 } 13033 13034 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13035 if (origin.staged && origin.cid != null) { 13036 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13037 cid = origin.cid; 13038 setMountPath(PackageHelper.getSdDir(cid)); 13039 return PackageManager.INSTALL_SUCCEEDED; 13040 } 13041 13042 if (temp) { 13043 createCopyFile(); 13044 } else { 13045 /* 13046 * Pre-emptively destroy the container since it's destroyed if 13047 * copying fails due to it existing anyway. 13048 */ 13049 PackageHelper.destroySdDir(cid); 13050 } 13051 13052 final String newMountPath = imcs.copyPackageToContainer( 13053 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13054 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13055 13056 if (newMountPath != null) { 13057 setMountPath(newMountPath); 13058 return PackageManager.INSTALL_SUCCEEDED; 13059 } else { 13060 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13061 } 13062 } 13063 13064 @Override 13065 String getCodePath() { 13066 return packagePath; 13067 } 13068 13069 @Override 13070 String getResourcePath() { 13071 return resourcePath; 13072 } 13073 13074 int doPreInstall(int status) { 13075 if (status != PackageManager.INSTALL_SUCCEEDED) { 13076 // Destroy container 13077 PackageHelper.destroySdDir(cid); 13078 } else { 13079 boolean mounted = PackageHelper.isContainerMounted(cid); 13080 if (!mounted) { 13081 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13082 Process.SYSTEM_UID); 13083 if (newMountPath != null) { 13084 setMountPath(newMountPath); 13085 } else { 13086 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13087 } 13088 } 13089 } 13090 return status; 13091 } 13092 13093 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13094 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13095 String newMountPath = null; 13096 if (PackageHelper.isContainerMounted(cid)) { 13097 // Unmount the container 13098 if (!PackageHelper.unMountSdDir(cid)) { 13099 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13100 return false; 13101 } 13102 } 13103 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13104 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13105 " which might be stale. Will try to clean up."); 13106 // Clean up the stale container and proceed to recreate. 13107 if (!PackageHelper.destroySdDir(newCacheId)) { 13108 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13109 return false; 13110 } 13111 // Successfully cleaned up stale container. Try to rename again. 13112 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13113 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13114 + " inspite of cleaning it up."); 13115 return false; 13116 } 13117 } 13118 if (!PackageHelper.isContainerMounted(newCacheId)) { 13119 Slog.w(TAG, "Mounting container " + newCacheId); 13120 newMountPath = PackageHelper.mountSdDir(newCacheId, 13121 getEncryptKey(), Process.SYSTEM_UID); 13122 } else { 13123 newMountPath = PackageHelper.getSdDir(newCacheId); 13124 } 13125 if (newMountPath == null) { 13126 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13127 return false; 13128 } 13129 Log.i(TAG, "Succesfully renamed " + cid + 13130 " to " + newCacheId + 13131 " at new path: " + newMountPath); 13132 cid = newCacheId; 13133 13134 final File beforeCodeFile = new File(packagePath); 13135 setMountPath(newMountPath); 13136 final File afterCodeFile = new File(packagePath); 13137 13138 // Reflect the rename in scanned details 13139 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13140 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13141 afterCodeFile, pkg.baseCodePath)); 13142 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13143 afterCodeFile, pkg.splitCodePaths)); 13144 13145 // Reflect the rename in app info 13146 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13147 pkg.setApplicationInfoCodePath(pkg.codePath); 13148 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13149 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13150 pkg.setApplicationInfoResourcePath(pkg.codePath); 13151 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13152 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13153 13154 return true; 13155 } 13156 13157 private void setMountPath(String mountPath) { 13158 final File mountFile = new File(mountPath); 13159 13160 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13161 if (monolithicFile.exists()) { 13162 packagePath = monolithicFile.getAbsolutePath(); 13163 if (isFwdLocked()) { 13164 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13165 } else { 13166 resourcePath = packagePath; 13167 } 13168 } else { 13169 packagePath = mountFile.getAbsolutePath(); 13170 resourcePath = packagePath; 13171 } 13172 } 13173 13174 int doPostInstall(int status, int uid) { 13175 if (status != PackageManager.INSTALL_SUCCEEDED) { 13176 cleanUp(); 13177 } else { 13178 final int groupOwner; 13179 final String protectedFile; 13180 if (isFwdLocked()) { 13181 groupOwner = UserHandle.getSharedAppGid(uid); 13182 protectedFile = RES_FILE_NAME; 13183 } else { 13184 groupOwner = -1; 13185 protectedFile = null; 13186 } 13187 13188 if (uid < Process.FIRST_APPLICATION_UID 13189 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13190 Slog.e(TAG, "Failed to finalize " + cid); 13191 PackageHelper.destroySdDir(cid); 13192 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13193 } 13194 13195 boolean mounted = PackageHelper.isContainerMounted(cid); 13196 if (!mounted) { 13197 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13198 } 13199 } 13200 return status; 13201 } 13202 13203 private void cleanUp() { 13204 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13205 13206 // Destroy secure container 13207 PackageHelper.destroySdDir(cid); 13208 } 13209 13210 private List<String> getAllCodePaths() { 13211 final File codeFile = new File(getCodePath()); 13212 if (codeFile != null && codeFile.exists()) { 13213 try { 13214 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13215 return pkg.getAllCodePaths(); 13216 } catch (PackageParserException e) { 13217 // Ignored; we tried our best 13218 } 13219 } 13220 return Collections.EMPTY_LIST; 13221 } 13222 13223 void cleanUpResourcesLI() { 13224 // Enumerate all code paths before deleting 13225 cleanUpResourcesLI(getAllCodePaths()); 13226 } 13227 13228 private void cleanUpResourcesLI(List<String> allCodePaths) { 13229 cleanUp(); 13230 removeDexFiles(allCodePaths, instructionSets); 13231 } 13232 13233 String getPackageName() { 13234 return getAsecPackageName(cid); 13235 } 13236 13237 boolean doPostDeleteLI(boolean delete) { 13238 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13239 final List<String> allCodePaths = getAllCodePaths(); 13240 boolean mounted = PackageHelper.isContainerMounted(cid); 13241 if (mounted) { 13242 // Unmount first 13243 if (PackageHelper.unMountSdDir(cid)) { 13244 mounted = false; 13245 } 13246 } 13247 if (!mounted && delete) { 13248 cleanUpResourcesLI(allCodePaths); 13249 } 13250 return !mounted; 13251 } 13252 13253 @Override 13254 int doPreCopy() { 13255 if (isFwdLocked()) { 13256 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13257 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13258 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13259 } 13260 } 13261 13262 return PackageManager.INSTALL_SUCCEEDED; 13263 } 13264 13265 @Override 13266 int doPostCopy(int uid) { 13267 if (isFwdLocked()) { 13268 if (uid < Process.FIRST_APPLICATION_UID 13269 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13270 RES_FILE_NAME)) { 13271 Slog.e(TAG, "Failed to finalize " + cid); 13272 PackageHelper.destroySdDir(cid); 13273 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13274 } 13275 } 13276 13277 return PackageManager.INSTALL_SUCCEEDED; 13278 } 13279 } 13280 13281 /** 13282 * Logic to handle movement of existing installed applications. 13283 */ 13284 class MoveInstallArgs extends InstallArgs { 13285 private File codeFile; 13286 private File resourceFile; 13287 13288 /** New install */ 13289 MoveInstallArgs(InstallParams params) { 13290 super(params.origin, params.move, params.observer, params.installFlags, 13291 params.installerPackageName, params.volumeUuid, 13292 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13293 params.grantedRuntimePermissions, 13294 params.traceMethod, params.traceCookie, params.certificates); 13295 } 13296 13297 int copyApk(IMediaContainerService imcs, boolean temp) { 13298 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13299 + move.fromUuid + " to " + move.toUuid); 13300 synchronized (mInstaller) { 13301 try { 13302 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13303 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13304 } catch (InstallerException e) { 13305 Slog.w(TAG, "Failed to move app", e); 13306 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13307 } 13308 } 13309 13310 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13311 resourceFile = codeFile; 13312 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13313 13314 return PackageManager.INSTALL_SUCCEEDED; 13315 } 13316 13317 int doPreInstall(int status) { 13318 if (status != PackageManager.INSTALL_SUCCEEDED) { 13319 cleanUp(move.toUuid); 13320 } 13321 return status; 13322 } 13323 13324 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13325 if (status != PackageManager.INSTALL_SUCCEEDED) { 13326 cleanUp(move.toUuid); 13327 return false; 13328 } 13329 13330 // Reflect the move in app info 13331 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13332 pkg.setApplicationInfoCodePath(pkg.codePath); 13333 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13334 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13335 pkg.setApplicationInfoResourcePath(pkg.codePath); 13336 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13337 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13338 13339 return true; 13340 } 13341 13342 int doPostInstall(int status, int uid) { 13343 if (status == PackageManager.INSTALL_SUCCEEDED) { 13344 cleanUp(move.fromUuid); 13345 } else { 13346 cleanUp(move.toUuid); 13347 } 13348 return status; 13349 } 13350 13351 @Override 13352 String getCodePath() { 13353 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13354 } 13355 13356 @Override 13357 String getResourcePath() { 13358 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13359 } 13360 13361 private boolean cleanUp(String volumeUuid) { 13362 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13363 move.dataAppName); 13364 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13365 synchronized (mInstallLock) { 13366 // Clean up both app data and code 13367 // All package moves are frozen until finished 13368 removeDataDirsLIF(volumeUuid, move.packageName); 13369 removeCodePathLI(codeFile); 13370 } 13371 return true; 13372 } 13373 13374 void cleanUpResourcesLI() { 13375 throw new UnsupportedOperationException(); 13376 } 13377 13378 boolean doPostDeleteLI(boolean delete) { 13379 throw new UnsupportedOperationException(); 13380 } 13381 } 13382 13383 static String getAsecPackageName(String packageCid) { 13384 int idx = packageCid.lastIndexOf("-"); 13385 if (idx == -1) { 13386 return packageCid; 13387 } 13388 return packageCid.substring(0, idx); 13389 } 13390 13391 // Utility method used to create code paths based on package name and available index. 13392 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13393 String idxStr = ""; 13394 int idx = 1; 13395 // Fall back to default value of idx=1 if prefix is not 13396 // part of oldCodePath 13397 if (oldCodePath != null) { 13398 String subStr = oldCodePath; 13399 // Drop the suffix right away 13400 if (suffix != null && subStr.endsWith(suffix)) { 13401 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13402 } 13403 // If oldCodePath already contains prefix find out the 13404 // ending index to either increment or decrement. 13405 int sidx = subStr.lastIndexOf(prefix); 13406 if (sidx != -1) { 13407 subStr = subStr.substring(sidx + prefix.length()); 13408 if (subStr != null) { 13409 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13410 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13411 } 13412 try { 13413 idx = Integer.parseInt(subStr); 13414 if (idx <= 1) { 13415 idx++; 13416 } else { 13417 idx--; 13418 } 13419 } catch(NumberFormatException e) { 13420 } 13421 } 13422 } 13423 } 13424 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13425 return prefix + idxStr; 13426 } 13427 13428 private File getNextCodePath(File targetDir, String packageName) { 13429 int suffix = 1; 13430 File result; 13431 do { 13432 result = new File(targetDir, packageName + "-" + suffix); 13433 suffix++; 13434 } while (result.exists()); 13435 return result; 13436 } 13437 13438 // Utility method that returns the relative package path with respect 13439 // to the installation directory. Like say for /data/data/com.test-1.apk 13440 // string com.test-1 is returned. 13441 static String deriveCodePathName(String codePath) { 13442 if (codePath == null) { 13443 return null; 13444 } 13445 final File codeFile = new File(codePath); 13446 final String name = codeFile.getName(); 13447 if (codeFile.isDirectory()) { 13448 return name; 13449 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13450 final int lastDot = name.lastIndexOf('.'); 13451 return name.substring(0, lastDot); 13452 } else { 13453 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13454 return null; 13455 } 13456 } 13457 13458 static class PackageInstalledInfo { 13459 String name; 13460 int uid; 13461 // The set of users that originally had this package installed. 13462 int[] origUsers; 13463 // The set of users that now have this package installed. 13464 int[] newUsers; 13465 PackageParser.Package pkg; 13466 int returnCode; 13467 String returnMsg; 13468 PackageRemovedInfo removedInfo; 13469 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13470 13471 public void setError(int code, String msg) { 13472 setReturnCode(code); 13473 setReturnMessage(msg); 13474 Slog.w(TAG, msg); 13475 } 13476 13477 public void setError(String msg, PackageParserException e) { 13478 setReturnCode(e.error); 13479 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13480 Slog.w(TAG, msg, e); 13481 } 13482 13483 public void setError(String msg, PackageManagerException e) { 13484 returnCode = e.error; 13485 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13486 Slog.w(TAG, msg, e); 13487 } 13488 13489 public void setReturnCode(int returnCode) { 13490 this.returnCode = returnCode; 13491 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13492 for (int i = 0; i < childCount; i++) { 13493 addedChildPackages.valueAt(i).returnCode = returnCode; 13494 } 13495 } 13496 13497 private void setReturnMessage(String returnMsg) { 13498 this.returnMsg = returnMsg; 13499 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13500 for (int i = 0; i < childCount; i++) { 13501 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13502 } 13503 } 13504 13505 // In some error cases we want to convey more info back to the observer 13506 String origPackage; 13507 String origPermission; 13508 } 13509 13510 /* 13511 * Install a non-existing package. 13512 */ 13513 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13514 UserHandle user, String installerPackageName, String volumeUuid, 13515 PackageInstalledInfo res) { 13516 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13517 13518 // Remember this for later, in case we need to rollback this install 13519 String pkgName = pkg.packageName; 13520 13521 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13522 13523 synchronized(mPackages) { 13524 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13525 // A package with the same name is already installed, though 13526 // it has been renamed to an older name. The package we 13527 // are trying to install should be installed as an update to 13528 // the existing one, but that has not been requested, so bail. 13529 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13530 + " without first uninstalling package running as " 13531 + mSettings.mRenamedPackages.get(pkgName)); 13532 return; 13533 } 13534 if (mPackages.containsKey(pkgName)) { 13535 // Don't allow installation over an existing package with the same name. 13536 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13537 + " without first uninstalling."); 13538 return; 13539 } 13540 } 13541 13542 try { 13543 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13544 System.currentTimeMillis(), user); 13545 13546 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13547 13548 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13549 prepareAppDataAfterInstall(newPackage); 13550 13551 } else { 13552 // Remove package from internal structures, but keep around any 13553 // data that might have already existed 13554 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13555 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13556 } 13557 } catch (PackageManagerException e) { 13558 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13559 } 13560 13561 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13562 } 13563 13564 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13565 // Can't rotate keys during boot or if sharedUser. 13566 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13567 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13568 return false; 13569 } 13570 // app is using upgradeKeySets; make sure all are valid 13571 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13572 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13573 for (int i = 0; i < upgradeKeySets.length; i++) { 13574 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13575 Slog.wtf(TAG, "Package " 13576 + (oldPs.name != null ? oldPs.name : "<null>") 13577 + " contains upgrade-key-set reference to unknown key-set: " 13578 + upgradeKeySets[i] 13579 + " reverting to signatures check."); 13580 return false; 13581 } 13582 } 13583 return true; 13584 } 13585 13586 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13587 // Upgrade keysets are being used. Determine if new package has a superset of the 13588 // required keys. 13589 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13590 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13591 for (int i = 0; i < upgradeKeySets.length; i++) { 13592 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13593 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13594 return true; 13595 } 13596 } 13597 return false; 13598 } 13599 13600 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13601 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13602 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13603 13604 final PackageParser.Package oldPackage; 13605 final String pkgName = pkg.packageName; 13606 final int[] allUsers; 13607 13608 // First find the old package info and check signatures 13609 synchronized(mPackages) { 13610 oldPackage = mPackages.get(pkgName); 13611 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13612 if (isEphemeral && !oldIsEphemeral) { 13613 // can't downgrade from full to ephemeral 13614 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13615 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13616 return; 13617 } 13618 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13619 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13620 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13621 if (!checkUpgradeKeySetLP(ps, pkg)) { 13622 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13623 "New package not signed by keys specified by upgrade-keysets: " 13624 + pkgName); 13625 return; 13626 } 13627 } else { 13628 // default to original signature matching 13629 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13630 != PackageManager.SIGNATURE_MATCH) { 13631 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13632 "New package has a different signature: " + pkgName); 13633 return; 13634 } 13635 } 13636 13637 // In case of rollback, remember per-user/profile install state 13638 allUsers = sUserManager.getUserIds(); 13639 } 13640 13641 // Update what is removed 13642 res.removedInfo = new PackageRemovedInfo(); 13643 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13644 res.removedInfo.removedPackage = oldPackage.packageName; 13645 res.removedInfo.isUpdate = true; 13646 final int childCount = (oldPackage.childPackages != null) 13647 ? oldPackage.childPackages.size() : 0; 13648 for (int i = 0; i < childCount; i++) { 13649 boolean childPackageUpdated = false; 13650 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13651 if (res.addedChildPackages != null) { 13652 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13653 if (childRes != null) { 13654 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13655 childRes.removedInfo.removedPackage = childPkg.packageName; 13656 childRes.removedInfo.isUpdate = true; 13657 childPackageUpdated = true; 13658 } 13659 } 13660 if (!childPackageUpdated) { 13661 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13662 childRemovedRes.removedPackage = childPkg.packageName; 13663 childRemovedRes.isUpdate = false; 13664 childRemovedRes.dataRemoved = true; 13665 synchronized (mPackages) { 13666 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13667 if (childPs != null) { 13668 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13669 } 13670 } 13671 if (res.removedInfo.removedChildPackages == null) { 13672 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13673 } 13674 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13675 } 13676 } 13677 13678 boolean sysPkg = (isSystemApp(oldPackage)); 13679 if (sysPkg) { 13680 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13681 user, allUsers, installerPackageName, res); 13682 } else { 13683 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13684 user, allUsers, installerPackageName, res); 13685 } 13686 } 13687 13688 public List<String> getPreviousCodePaths(String packageName) { 13689 final PackageSetting ps = mSettings.mPackages.get(packageName); 13690 final List<String> result = new ArrayList<String>(); 13691 if (ps != null && ps.oldCodePaths != null) { 13692 result.addAll(ps.oldCodePaths); 13693 } 13694 return result; 13695 } 13696 13697 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13698 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13699 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13700 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13701 + deletedPackage); 13702 13703 String pkgName = deletedPackage.packageName; 13704 boolean deletedPkg = true; 13705 boolean addedPkg = false; 13706 boolean updatedSettings = false; 13707 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13708 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13709 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13710 13711 final long origUpdateTime = (pkg.mExtras != null) 13712 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13713 13714 // First delete the existing package while retaining the data directory 13715 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13716 res.removedInfo, true, pkg)) { 13717 // If the existing package wasn't successfully deleted 13718 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13719 deletedPkg = false; 13720 } else { 13721 // Successfully deleted the old package; proceed with replace. 13722 13723 // If deleted package lived in a container, give users a chance to 13724 // relinquish resources before killing. 13725 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13726 if (DEBUG_INSTALL) { 13727 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13728 } 13729 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13730 final ArrayList<String> pkgList = new ArrayList<String>(1); 13731 pkgList.add(deletedPackage.applicationInfo.packageName); 13732 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13733 } 13734 13735 deleteCodeCacheDirsLIF(pkg); 13736 deleteProfilesLIF(pkg, /*destroy*/ false); 13737 13738 try { 13739 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13740 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13741 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13742 13743 // Update the in-memory copy of the previous code paths. 13744 PackageSetting ps = mSettings.mPackages.get(pkgName); 13745 if (!killApp) { 13746 if (ps.oldCodePaths == null) { 13747 ps.oldCodePaths = new ArraySet<>(); 13748 } 13749 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13750 if (deletedPackage.splitCodePaths != null) { 13751 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13752 } 13753 } else { 13754 ps.oldCodePaths = null; 13755 } 13756 if (ps.childPackageNames != null) { 13757 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13758 final String childPkgName = ps.childPackageNames.get(i); 13759 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13760 childPs.oldCodePaths = ps.oldCodePaths; 13761 } 13762 } 13763 prepareAppDataAfterInstall(newPackage); 13764 addedPkg = true; 13765 } catch (PackageManagerException e) { 13766 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13767 } 13768 } 13769 13770 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13771 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13772 13773 // Revert all internal state mutations and added folders for the failed install 13774 if (addedPkg) { 13775 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13776 res.removedInfo, true, null); 13777 } 13778 13779 // Restore the old package 13780 if (deletedPkg) { 13781 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13782 File restoreFile = new File(deletedPackage.codePath); 13783 // Parse old package 13784 boolean oldExternal = isExternal(deletedPackage); 13785 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13786 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13787 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13788 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13789 try { 13790 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13791 null); 13792 } catch (PackageManagerException e) { 13793 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13794 + e.getMessage()); 13795 return; 13796 } 13797 13798 synchronized (mPackages) { 13799 // Ensure the installer package name up to date 13800 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13801 13802 // Update permissions for restored package 13803 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13804 13805 mSettings.writeLPr(); 13806 } 13807 13808 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13809 } 13810 } else { 13811 synchronized (mPackages) { 13812 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13813 if (ps != null) { 13814 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13815 if (res.removedInfo.removedChildPackages != null) { 13816 final int childCount = res.removedInfo.removedChildPackages.size(); 13817 // Iterate in reverse as we may modify the collection 13818 for (int i = childCount - 1; i >= 0; i--) { 13819 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13820 if (res.addedChildPackages.containsKey(childPackageName)) { 13821 res.removedInfo.removedChildPackages.removeAt(i); 13822 } else { 13823 PackageRemovedInfo childInfo = res.removedInfo 13824 .removedChildPackages.valueAt(i); 13825 childInfo.removedForAllUsers = mPackages.get( 13826 childInfo.removedPackage) == null; 13827 } 13828 } 13829 } 13830 } 13831 } 13832 } 13833 } 13834 13835 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13836 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13837 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13838 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13839 + ", old=" + deletedPackage); 13840 13841 final boolean disabledSystem; 13842 13843 // Set the system/privileged flags as needed 13844 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13845 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13846 != 0) { 13847 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13848 } 13849 13850 // Remove existing system package 13851 removePackageLI(deletedPackage, true); 13852 13853 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13854 if (!disabledSystem) { 13855 // We didn't need to disable the .apk as a current system package, 13856 // which means we are replacing another update that is already 13857 // installed. We need to make sure to delete the older one's .apk. 13858 res.removedInfo.args = createInstallArgsForExisting(0, 13859 deletedPackage.applicationInfo.getCodePath(), 13860 deletedPackage.applicationInfo.getResourcePath(), 13861 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13862 } else { 13863 res.removedInfo.args = null; 13864 } 13865 13866 // Successfully disabled the old package. Now proceed with re-installation 13867 deleteCodeCacheDirsLIF(pkg); 13868 deleteProfilesLIF(pkg, /*destroy*/ false); 13869 13870 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13871 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13872 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13873 13874 PackageParser.Package newPackage = null; 13875 try { 13876 // Add the package to the internal data structures 13877 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13878 13879 // Set the update and install times 13880 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13881 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13882 System.currentTimeMillis()); 13883 13884 // Check for shared user id changes 13885 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13886 deletedPackage, newPackage); 13887 if (invalidPackageName != null) { 13888 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13889 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13890 + " to " + invalidPackageName); 13891 } 13892 13893 // Update the package dynamic state if succeeded 13894 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13895 // Now that the install succeeded make sure we remove data 13896 // directories for any child package the update removed. 13897 final int deletedChildCount = (deletedPackage.childPackages != null) 13898 ? deletedPackage.childPackages.size() : 0; 13899 final int newChildCount = (newPackage.childPackages != null) 13900 ? newPackage.childPackages.size() : 0; 13901 for (int i = 0; i < deletedChildCount; i++) { 13902 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13903 boolean childPackageDeleted = true; 13904 for (int j = 0; j < newChildCount; j++) { 13905 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13906 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13907 childPackageDeleted = false; 13908 break; 13909 } 13910 } 13911 if (childPackageDeleted) { 13912 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13913 deletedChildPkg.packageName); 13914 if (ps != null && res.removedInfo.removedChildPackages != null) { 13915 PackageRemovedInfo removedChildRes = res.removedInfo 13916 .removedChildPackages.get(deletedChildPkg.packageName); 13917 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13918 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13919 } 13920 } 13921 } 13922 13923 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13924 prepareAppDataAfterInstall(newPackage); 13925 } 13926 } catch (PackageManagerException e) { 13927 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13928 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13929 } 13930 13931 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13932 // Re installation failed. Restore old information 13933 // Remove new pkg information 13934 if (newPackage != null) { 13935 removeInstalledPackageLI(newPackage, true); 13936 } 13937 // Add back the old system package 13938 try { 13939 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13940 } catch (PackageManagerException e) { 13941 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13942 } 13943 13944 synchronized (mPackages) { 13945 if (disabledSystem) { 13946 enableSystemPackageLPw(deletedPackage); 13947 } 13948 13949 // Ensure the installer package name up to date 13950 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13951 13952 // Update permissions for restored package 13953 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13954 13955 mSettings.writeLPr(); 13956 } 13957 13958 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13959 + " after failed upgrade"); 13960 } 13961 } 13962 13963 /** 13964 * Checks whether the parent or any of the child packages have a change shared 13965 * user. For a package to be a valid update the shred users of the parent and 13966 * the children should match. We may later support changing child shared users. 13967 * @param oldPkg The updated package. 13968 * @param newPkg The update package. 13969 * @return The shared user that change between the versions. 13970 */ 13971 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13972 PackageParser.Package newPkg) { 13973 // Check parent shared user 13974 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13975 return newPkg.packageName; 13976 } 13977 // Check child shared users 13978 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13979 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13980 for (int i = 0; i < newChildCount; i++) { 13981 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13982 // If this child was present, did it have the same shared user? 13983 for (int j = 0; j < oldChildCount; j++) { 13984 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13985 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13986 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13987 return newChildPkg.packageName; 13988 } 13989 } 13990 } 13991 return null; 13992 } 13993 13994 private void removeNativeBinariesLI(PackageSetting ps) { 13995 // Remove the lib path for the parent package 13996 if (ps != null) { 13997 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13998 // Remove the lib path for the child packages 13999 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14000 for (int i = 0; i < childCount; i++) { 14001 PackageSetting childPs = null; 14002 synchronized (mPackages) { 14003 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14004 } 14005 if (childPs != null) { 14006 NativeLibraryHelper.removeNativeBinariesLI(childPs 14007 .legacyNativeLibraryPathString); 14008 } 14009 } 14010 } 14011 } 14012 14013 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14014 // Enable the parent package 14015 mSettings.enableSystemPackageLPw(pkg.packageName); 14016 // Enable the child packages 14017 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14018 for (int i = 0; i < childCount; i++) { 14019 PackageParser.Package childPkg = pkg.childPackages.get(i); 14020 mSettings.enableSystemPackageLPw(childPkg.packageName); 14021 } 14022 } 14023 14024 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14025 PackageParser.Package newPkg) { 14026 // Disable the parent package (parent always replaced) 14027 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14028 // Disable the child packages 14029 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14030 for (int i = 0; i < childCount; i++) { 14031 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14032 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14033 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14034 } 14035 return disabled; 14036 } 14037 14038 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14039 String installerPackageName) { 14040 // Enable the parent package 14041 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14042 // Enable the child packages 14043 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14044 for (int i = 0; i < childCount; i++) { 14045 PackageParser.Package childPkg = pkg.childPackages.get(i); 14046 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14047 } 14048 } 14049 14050 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14051 // Collect all used permissions in the UID 14052 ArraySet<String> usedPermissions = new ArraySet<>(); 14053 final int packageCount = su.packages.size(); 14054 for (int i = 0; i < packageCount; i++) { 14055 PackageSetting ps = su.packages.valueAt(i); 14056 if (ps.pkg == null) { 14057 continue; 14058 } 14059 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14060 for (int j = 0; j < requestedPermCount; j++) { 14061 String permission = ps.pkg.requestedPermissions.get(j); 14062 BasePermission bp = mSettings.mPermissions.get(permission); 14063 if (bp != null) { 14064 usedPermissions.add(permission); 14065 } 14066 } 14067 } 14068 14069 PermissionsState permissionsState = su.getPermissionsState(); 14070 // Prune install permissions 14071 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14072 final int installPermCount = installPermStates.size(); 14073 for (int i = installPermCount - 1; i >= 0; i--) { 14074 PermissionState permissionState = installPermStates.get(i); 14075 if (!usedPermissions.contains(permissionState.getName())) { 14076 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14077 if (bp != null) { 14078 permissionsState.revokeInstallPermission(bp); 14079 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14080 PackageManager.MASK_PERMISSION_FLAGS, 0); 14081 } 14082 } 14083 } 14084 14085 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14086 14087 // Prune runtime permissions 14088 for (int userId : allUserIds) { 14089 List<PermissionState> runtimePermStates = permissionsState 14090 .getRuntimePermissionStates(userId); 14091 final int runtimePermCount = runtimePermStates.size(); 14092 for (int i = runtimePermCount - 1; i >= 0; i--) { 14093 PermissionState permissionState = runtimePermStates.get(i); 14094 if (!usedPermissions.contains(permissionState.getName())) { 14095 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14096 if (bp != null) { 14097 permissionsState.revokeRuntimePermission(bp, userId); 14098 permissionsState.updatePermissionFlags(bp, userId, 14099 PackageManager.MASK_PERMISSION_FLAGS, 0); 14100 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14101 runtimePermissionChangedUserIds, userId); 14102 } 14103 } 14104 } 14105 } 14106 14107 return runtimePermissionChangedUserIds; 14108 } 14109 14110 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14111 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14112 // Update the parent package setting 14113 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14114 res, user); 14115 // Update the child packages setting 14116 final int childCount = (newPackage.childPackages != null) 14117 ? newPackage.childPackages.size() : 0; 14118 for (int i = 0; i < childCount; i++) { 14119 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14120 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14121 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14122 childRes.origUsers, childRes, user); 14123 } 14124 } 14125 14126 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14127 String installerPackageName, int[] allUsers, int[] installedForUsers, 14128 PackageInstalledInfo res, UserHandle user) { 14129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14130 14131 String pkgName = newPackage.packageName; 14132 synchronized (mPackages) { 14133 //write settings. the installStatus will be incomplete at this stage. 14134 //note that the new package setting would have already been 14135 //added to mPackages. It hasn't been persisted yet. 14136 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14137 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14138 mSettings.writeLPr(); 14139 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14140 } 14141 14142 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14143 synchronized (mPackages) { 14144 updatePermissionsLPw(newPackage.packageName, newPackage, 14145 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14146 ? UPDATE_PERMISSIONS_ALL : 0)); 14147 // For system-bundled packages, we assume that installing an upgraded version 14148 // of the package implies that the user actually wants to run that new code, 14149 // so we enable the package. 14150 PackageSetting ps = mSettings.mPackages.get(pkgName); 14151 final int userId = user.getIdentifier(); 14152 if (ps != null) { 14153 if (isSystemApp(newPackage)) { 14154 if (DEBUG_INSTALL) { 14155 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14156 } 14157 // Enable system package for requested users 14158 if (res.origUsers != null) { 14159 for (int origUserId : res.origUsers) { 14160 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14161 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14162 origUserId, installerPackageName); 14163 } 14164 } 14165 } 14166 // Also convey the prior install/uninstall state 14167 if (allUsers != null && installedForUsers != null) { 14168 for (int currentUserId : allUsers) { 14169 final boolean installed = ArrayUtils.contains( 14170 installedForUsers, currentUserId); 14171 if (DEBUG_INSTALL) { 14172 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14173 } 14174 ps.setInstalled(installed, currentUserId); 14175 } 14176 // these install state changes will be persisted in the 14177 // upcoming call to mSettings.writeLPr(). 14178 } 14179 } 14180 // It's implied that when a user requests installation, they want the app to be 14181 // installed and enabled. 14182 if (userId != UserHandle.USER_ALL) { 14183 ps.setInstalled(true, userId); 14184 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14185 } 14186 } 14187 res.name = pkgName; 14188 res.uid = newPackage.applicationInfo.uid; 14189 res.pkg = newPackage; 14190 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14191 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14192 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14193 //to update install status 14194 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14195 mSettings.writeLPr(); 14196 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14197 } 14198 14199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14200 } 14201 14202 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14203 try { 14204 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14205 installPackageLI(args, res); 14206 } finally { 14207 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14208 } 14209 } 14210 14211 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14212 final int installFlags = args.installFlags; 14213 final String installerPackageName = args.installerPackageName; 14214 final String volumeUuid = args.volumeUuid; 14215 final File tmpPackageFile = new File(args.getCodePath()); 14216 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14217 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14218 || (args.volumeUuid != null)); 14219 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14220 boolean replace = false; 14221 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14222 if (args.move != null) { 14223 // moving a complete application; perform an initial scan on the new install location 14224 scanFlags |= SCAN_INITIAL; 14225 } 14226 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14227 scanFlags |= SCAN_DONT_KILL_APP; 14228 } 14229 14230 // Result object to be returned 14231 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14232 14233 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14234 14235 // Sanity check 14236 if (ephemeral && (forwardLocked || onExternal)) { 14237 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14238 + " external=" + onExternal); 14239 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14240 return; 14241 } 14242 14243 // Retrieve PackageSettings and parse package 14244 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14245 | PackageParser.PARSE_ENFORCE_CODE 14246 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14247 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14248 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14249 PackageParser pp = new PackageParser(); 14250 pp.setSeparateProcesses(mSeparateProcesses); 14251 pp.setDisplayMetrics(mMetrics); 14252 14253 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14254 final PackageParser.Package pkg; 14255 try { 14256 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14257 } catch (PackageParserException e) { 14258 res.setError("Failed parse during installPackageLI", e); 14259 return; 14260 } finally { 14261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14262 } 14263 14264 // If we are installing a clustered package add results for the children 14265 if (pkg.childPackages != null) { 14266 synchronized (mPackages) { 14267 final int childCount = pkg.childPackages.size(); 14268 for (int i = 0; i < childCount; i++) { 14269 PackageParser.Package childPkg = pkg.childPackages.get(i); 14270 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14271 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14272 childRes.pkg = childPkg; 14273 childRes.name = childPkg.packageName; 14274 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14275 if (childPs != null) { 14276 childRes.origUsers = childPs.queryInstalledUsers( 14277 sUserManager.getUserIds(), true); 14278 } 14279 if ((mPackages.containsKey(childPkg.packageName))) { 14280 childRes.removedInfo = new PackageRemovedInfo(); 14281 childRes.removedInfo.removedPackage = childPkg.packageName; 14282 } 14283 if (res.addedChildPackages == null) { 14284 res.addedChildPackages = new ArrayMap<>(); 14285 } 14286 res.addedChildPackages.put(childPkg.packageName, childRes); 14287 } 14288 } 14289 } 14290 14291 // If package doesn't declare API override, mark that we have an install 14292 // time CPU ABI override. 14293 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14294 pkg.cpuAbiOverride = args.abiOverride; 14295 } 14296 14297 String pkgName = res.name = pkg.packageName; 14298 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14299 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14300 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14301 return; 14302 } 14303 } 14304 14305 try { 14306 // either use what we've been given or parse directly from the APK 14307 if (args.certificates != null) { 14308 try { 14309 PackageParser.populateCertificates(pkg, args.certificates); 14310 } catch (PackageParserException e) { 14311 // there was something wrong with the certificates we were given; 14312 // try to pull them from the APK 14313 PackageParser.collectCertificates(pkg, parseFlags); 14314 } 14315 } else { 14316 PackageParser.collectCertificates(pkg, parseFlags); 14317 } 14318 } catch (PackageParserException e) { 14319 res.setError("Failed collect during installPackageLI", e); 14320 return; 14321 } 14322 14323 // Get rid of all references to package scan path via parser. 14324 pp = null; 14325 String oldCodePath = null; 14326 boolean systemApp = false; 14327 synchronized (mPackages) { 14328 // Check if installing already existing package 14329 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14330 String oldName = mSettings.mRenamedPackages.get(pkgName); 14331 if (pkg.mOriginalPackages != null 14332 && pkg.mOriginalPackages.contains(oldName) 14333 && mPackages.containsKey(oldName)) { 14334 // This package is derived from an original package, 14335 // and this device has been updating from that original 14336 // name. We must continue using the original name, so 14337 // rename the new package here. 14338 pkg.setPackageName(oldName); 14339 pkgName = pkg.packageName; 14340 replace = true; 14341 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14342 + oldName + " pkgName=" + pkgName); 14343 } else if (mPackages.containsKey(pkgName)) { 14344 // This package, under its official name, already exists 14345 // on the device; we should replace it. 14346 replace = true; 14347 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14348 } 14349 14350 // Child packages are installed through the parent package 14351 if (pkg.parentPackage != null) { 14352 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14353 "Package " + pkg.packageName + " is child of package " 14354 + pkg.parentPackage.parentPackage + ". Child packages " 14355 + "can be updated only through the parent package."); 14356 return; 14357 } 14358 14359 if (replace) { 14360 // Prevent apps opting out from runtime permissions 14361 PackageParser.Package oldPackage = mPackages.get(pkgName); 14362 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14363 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14364 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14365 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14366 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14367 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14368 + " doesn't support runtime permissions but the old" 14369 + " target SDK " + oldTargetSdk + " does."); 14370 return; 14371 } 14372 14373 // Prevent installing of child packages 14374 if (oldPackage.parentPackage != null) { 14375 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14376 "Package " + pkg.packageName + " is child of package " 14377 + oldPackage.parentPackage + ". Child packages " 14378 + "can be updated only through the parent package."); 14379 return; 14380 } 14381 } 14382 } 14383 14384 PackageSetting ps = mSettings.mPackages.get(pkgName); 14385 if (ps != null) { 14386 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14387 14388 // Quick sanity check that we're signed correctly if updating; 14389 // we'll check this again later when scanning, but we want to 14390 // bail early here before tripping over redefined permissions. 14391 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14392 if (!checkUpgradeKeySetLP(ps, pkg)) { 14393 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14394 + pkg.packageName + " upgrade keys do not match the " 14395 + "previously installed version"); 14396 return; 14397 } 14398 } else { 14399 try { 14400 verifySignaturesLP(ps, pkg); 14401 } catch (PackageManagerException e) { 14402 res.setError(e.error, e.getMessage()); 14403 return; 14404 } 14405 } 14406 14407 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14408 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14409 systemApp = (ps.pkg.applicationInfo.flags & 14410 ApplicationInfo.FLAG_SYSTEM) != 0; 14411 } 14412 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14413 } 14414 14415 // Check whether the newly-scanned package wants to define an already-defined perm 14416 int N = pkg.permissions.size(); 14417 for (int i = N-1; i >= 0; i--) { 14418 PackageParser.Permission perm = pkg.permissions.get(i); 14419 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14420 if (bp != null) { 14421 // If the defining package is signed with our cert, it's okay. This 14422 // also includes the "updating the same package" case, of course. 14423 // "updating same package" could also involve key-rotation. 14424 final boolean sigsOk; 14425 if (bp.sourcePackage.equals(pkg.packageName) 14426 && (bp.packageSetting instanceof PackageSetting) 14427 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14428 scanFlags))) { 14429 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14430 } else { 14431 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14432 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14433 } 14434 if (!sigsOk) { 14435 // If the owning package is the system itself, we log but allow 14436 // install to proceed; we fail the install on all other permission 14437 // redefinitions. 14438 if (!bp.sourcePackage.equals("android")) { 14439 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14440 + pkg.packageName + " attempting to redeclare permission " 14441 + perm.info.name + " already owned by " + bp.sourcePackage); 14442 res.origPermission = perm.info.name; 14443 res.origPackage = bp.sourcePackage; 14444 return; 14445 } else { 14446 Slog.w(TAG, "Package " + pkg.packageName 14447 + " attempting to redeclare system permission " 14448 + perm.info.name + "; ignoring new declaration"); 14449 pkg.permissions.remove(i); 14450 } 14451 } 14452 } 14453 } 14454 } 14455 14456 if (systemApp) { 14457 if (onExternal) { 14458 // Abort update; system app can't be replaced with app on sdcard 14459 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14460 "Cannot install updates to system apps on sdcard"); 14461 return; 14462 } else if (ephemeral) { 14463 // Abort update; system app can't be replaced with an ephemeral app 14464 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14465 "Cannot update a system app with an ephemeral app"); 14466 return; 14467 } 14468 } 14469 14470 if (args.move != null) { 14471 // We did an in-place move, so dex is ready to roll 14472 scanFlags |= SCAN_NO_DEX; 14473 scanFlags |= SCAN_MOVE; 14474 14475 synchronized (mPackages) { 14476 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14477 if (ps == null) { 14478 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14479 "Missing settings for moved package " + pkgName); 14480 } 14481 14482 // We moved the entire application as-is, so bring over the 14483 // previously derived ABI information. 14484 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14485 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14486 } 14487 14488 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14489 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14490 scanFlags |= SCAN_NO_DEX; 14491 14492 try { 14493 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14494 args.abiOverride : pkg.cpuAbiOverride); 14495 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14496 true /* extract libs */); 14497 } catch (PackageManagerException pme) { 14498 Slog.e(TAG, "Error deriving application ABI", pme); 14499 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14500 return; 14501 } 14502 14503 14504 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14505 // Do not run PackageDexOptimizer through the local performDexOpt 14506 // method because `pkg` is not in `mPackages` yet. 14507 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14508 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14509 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14510 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14511 String msg = "Extracking package failed for " + pkgName; 14512 res.setError(INSTALL_FAILED_DEXOPT, msg); 14513 return; 14514 } 14515 } 14516 14517 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14518 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14519 return; 14520 } 14521 14522 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14523 14524 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14525 "installPackageLI")) { 14526 if (replace) { 14527 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14528 installerPackageName, res); 14529 } else { 14530 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14531 args.user, installerPackageName, volumeUuid, res); 14532 } 14533 } 14534 synchronized (mPackages) { 14535 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14536 if (ps != null) { 14537 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14538 } 14539 14540 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14541 for (int i = 0; i < childCount; i++) { 14542 PackageParser.Package childPkg = pkg.childPackages.get(i); 14543 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14544 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14545 if (childPs != null) { 14546 childRes.newUsers = childPs.queryInstalledUsers( 14547 sUserManager.getUserIds(), true); 14548 } 14549 } 14550 } 14551 } 14552 14553 private void startIntentFilterVerifications(int userId, boolean replacing, 14554 PackageParser.Package pkg) { 14555 if (mIntentFilterVerifierComponent == null) { 14556 Slog.w(TAG, "No IntentFilter verification will not be done as " 14557 + "there is no IntentFilterVerifier available!"); 14558 return; 14559 } 14560 14561 final int verifierUid = getPackageUid( 14562 mIntentFilterVerifierComponent.getPackageName(), 14563 MATCH_DEBUG_TRIAGED_MISSING, 14564 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14565 14566 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14567 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14568 mHandler.sendMessage(msg); 14569 14570 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14571 for (int i = 0; i < childCount; i++) { 14572 PackageParser.Package childPkg = pkg.childPackages.get(i); 14573 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14574 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14575 mHandler.sendMessage(msg); 14576 } 14577 } 14578 14579 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14580 PackageParser.Package pkg) { 14581 int size = pkg.activities.size(); 14582 if (size == 0) { 14583 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14584 "No activity, so no need to verify any IntentFilter!"); 14585 return; 14586 } 14587 14588 final boolean hasDomainURLs = hasDomainURLs(pkg); 14589 if (!hasDomainURLs) { 14590 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14591 "No domain URLs, so no need to verify any IntentFilter!"); 14592 return; 14593 } 14594 14595 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14596 + " if any IntentFilter from the " + size 14597 + " Activities needs verification ..."); 14598 14599 int count = 0; 14600 final String packageName = pkg.packageName; 14601 14602 synchronized (mPackages) { 14603 // If this is a new install and we see that we've already run verification for this 14604 // package, we have nothing to do: it means the state was restored from backup. 14605 if (!replacing) { 14606 IntentFilterVerificationInfo ivi = 14607 mSettings.getIntentFilterVerificationLPr(packageName); 14608 if (ivi != null) { 14609 if (DEBUG_DOMAIN_VERIFICATION) { 14610 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14611 + ivi.getStatusString()); 14612 } 14613 return; 14614 } 14615 } 14616 14617 // If any filters need to be verified, then all need to be. 14618 boolean needToVerify = false; 14619 for (PackageParser.Activity a : pkg.activities) { 14620 for (ActivityIntentInfo filter : a.intents) { 14621 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14622 if (DEBUG_DOMAIN_VERIFICATION) { 14623 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14624 } 14625 needToVerify = true; 14626 break; 14627 } 14628 } 14629 } 14630 14631 if (needToVerify) { 14632 final int verificationId = mIntentFilterVerificationToken++; 14633 for (PackageParser.Activity a : pkg.activities) { 14634 for (ActivityIntentInfo filter : a.intents) { 14635 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14636 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14637 "Verification needed for IntentFilter:" + filter.toString()); 14638 mIntentFilterVerifier.addOneIntentFilterVerification( 14639 verifierUid, userId, verificationId, filter, packageName); 14640 count++; 14641 } 14642 } 14643 } 14644 } 14645 } 14646 14647 if (count > 0) { 14648 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14649 + " IntentFilter verification" + (count > 1 ? "s" : "") 14650 + " for userId:" + userId); 14651 mIntentFilterVerifier.startVerifications(userId); 14652 } else { 14653 if (DEBUG_DOMAIN_VERIFICATION) { 14654 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14655 } 14656 } 14657 } 14658 14659 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14660 final ComponentName cn = filter.activity.getComponentName(); 14661 final String packageName = cn.getPackageName(); 14662 14663 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14664 packageName); 14665 if (ivi == null) { 14666 return true; 14667 } 14668 int status = ivi.getStatus(); 14669 switch (status) { 14670 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14671 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14672 return true; 14673 14674 default: 14675 // Nothing to do 14676 return false; 14677 } 14678 } 14679 14680 private static boolean isMultiArch(ApplicationInfo info) { 14681 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14682 } 14683 14684 private static boolean isExternal(PackageParser.Package pkg) { 14685 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14686 } 14687 14688 private static boolean isExternal(PackageSetting ps) { 14689 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14690 } 14691 14692 private static boolean isEphemeral(PackageParser.Package pkg) { 14693 return pkg.applicationInfo.isEphemeralApp(); 14694 } 14695 14696 private static boolean isEphemeral(PackageSetting ps) { 14697 return ps.pkg != null && isEphemeral(ps.pkg); 14698 } 14699 14700 private static boolean isSystemApp(PackageParser.Package pkg) { 14701 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14702 } 14703 14704 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14705 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14706 } 14707 14708 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14709 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14710 } 14711 14712 private static boolean isSystemApp(PackageSetting ps) { 14713 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14714 } 14715 14716 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14717 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14718 } 14719 14720 private int packageFlagsToInstallFlags(PackageSetting ps) { 14721 int installFlags = 0; 14722 if (isEphemeral(ps)) { 14723 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14724 } 14725 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14726 // This existing package was an external ASEC install when we have 14727 // the external flag without a UUID 14728 installFlags |= PackageManager.INSTALL_EXTERNAL; 14729 } 14730 if (ps.isForwardLocked()) { 14731 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14732 } 14733 return installFlags; 14734 } 14735 14736 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14737 if (isExternal(pkg)) { 14738 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14739 return StorageManager.UUID_PRIMARY_PHYSICAL; 14740 } else { 14741 return pkg.volumeUuid; 14742 } 14743 } else { 14744 return StorageManager.UUID_PRIVATE_INTERNAL; 14745 } 14746 } 14747 14748 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14749 if (isExternal(pkg)) { 14750 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14751 return mSettings.getExternalVersion(); 14752 } else { 14753 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14754 } 14755 } else { 14756 return mSettings.getInternalVersion(); 14757 } 14758 } 14759 14760 private void deleteTempPackageFiles() { 14761 final FilenameFilter filter = new FilenameFilter() { 14762 public boolean accept(File dir, String name) { 14763 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14764 } 14765 }; 14766 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14767 file.delete(); 14768 } 14769 } 14770 14771 @Override 14772 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14773 int flags) { 14774 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14775 flags); 14776 } 14777 14778 @Override 14779 public void deletePackage(final String packageName, 14780 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14781 mContext.enforceCallingOrSelfPermission( 14782 android.Manifest.permission.DELETE_PACKAGES, null); 14783 Preconditions.checkNotNull(packageName); 14784 Preconditions.checkNotNull(observer); 14785 final int uid = Binder.getCallingUid(); 14786 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14787 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14788 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14789 mContext.enforceCallingOrSelfPermission( 14790 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14791 "deletePackage for user " + userId); 14792 } 14793 14794 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14795 try { 14796 observer.onPackageDeleted(packageName, 14797 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14798 } catch (RemoteException re) { 14799 } 14800 return; 14801 } 14802 14803 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14804 try { 14805 observer.onPackageDeleted(packageName, 14806 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14807 } catch (RemoteException re) { 14808 } 14809 return; 14810 } 14811 14812 if (DEBUG_REMOVE) { 14813 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14814 + " deleteAllUsers: " + deleteAllUsers ); 14815 } 14816 // Queue up an async operation since the package deletion may take a little while. 14817 mHandler.post(new Runnable() { 14818 public void run() { 14819 mHandler.removeCallbacks(this); 14820 int returnCode; 14821 if (!deleteAllUsers) { 14822 returnCode = deletePackageX(packageName, userId, deleteFlags); 14823 } else { 14824 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14825 // If nobody is blocking uninstall, proceed with delete for all users 14826 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14827 returnCode = deletePackageX(packageName, userId, deleteFlags); 14828 } else { 14829 // Otherwise uninstall individually for users with blockUninstalls=false 14830 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14831 for (int userId : users) { 14832 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14833 returnCode = deletePackageX(packageName, userId, userFlags); 14834 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14835 Slog.w(TAG, "Package delete failed for user " + userId 14836 + ", returnCode " + returnCode); 14837 } 14838 } 14839 } 14840 // The app has only been marked uninstalled for certain users. 14841 // We still need to report that delete was blocked 14842 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14843 } 14844 } 14845 try { 14846 observer.onPackageDeleted(packageName, returnCode, null); 14847 } catch (RemoteException e) { 14848 Log.i(TAG, "Observer no longer exists."); 14849 } //end catch 14850 } //end run 14851 }); 14852 } 14853 14854 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14855 int[] result = EMPTY_INT_ARRAY; 14856 for (int userId : userIds) { 14857 if (getBlockUninstallForUser(packageName, userId)) { 14858 result = ArrayUtils.appendInt(result, userId); 14859 } 14860 } 14861 return result; 14862 } 14863 14864 @Override 14865 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14866 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14867 } 14868 14869 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14870 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14871 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14872 try { 14873 if (dpm != null) { 14874 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14875 /* callingUserOnly =*/ false); 14876 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14877 : deviceOwnerComponentName.getPackageName(); 14878 // Does the package contains the device owner? 14879 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14880 // this check is probably not needed, since DO should be registered as a device 14881 // admin on some user too. (Original bug for this: b/17657954) 14882 if (packageName.equals(deviceOwnerPackageName)) { 14883 return true; 14884 } 14885 // Does it contain a device admin for any user? 14886 int[] users; 14887 if (userId == UserHandle.USER_ALL) { 14888 users = sUserManager.getUserIds(); 14889 } else { 14890 users = new int[]{userId}; 14891 } 14892 for (int i = 0; i < users.length; ++i) { 14893 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14894 return true; 14895 } 14896 } 14897 } 14898 } catch (RemoteException e) { 14899 } 14900 return false; 14901 } 14902 14903 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14904 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14905 } 14906 14907 /** 14908 * This method is an internal method that could be get invoked either 14909 * to delete an installed package or to clean up a failed installation. 14910 * After deleting an installed package, a broadcast is sent to notify any 14911 * listeners that the package has been removed. For cleaning up a failed 14912 * installation, the broadcast is not necessary since the package's 14913 * installation wouldn't have sent the initial broadcast either 14914 * The key steps in deleting a package are 14915 * deleting the package information in internal structures like mPackages, 14916 * deleting the packages base directories through installd 14917 * updating mSettings to reflect current status 14918 * persisting settings for later use 14919 * sending a broadcast if necessary 14920 */ 14921 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14922 final PackageRemovedInfo info = new PackageRemovedInfo(); 14923 final boolean res; 14924 14925 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14926 ? UserHandle.ALL : new UserHandle(userId); 14927 14928 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14929 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14930 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14931 } 14932 14933 PackageSetting uninstalledPs = null; 14934 14935 // for the uninstall-updates case and restricted profiles, remember the per- 14936 // user handle installed state 14937 int[] allUsers; 14938 synchronized (mPackages) { 14939 uninstalledPs = mSettings.mPackages.get(packageName); 14940 if (uninstalledPs == null) { 14941 Slog.w(TAG, "Not removing non-existent package " + packageName); 14942 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14943 } 14944 allUsers = sUserManager.getUserIds(); 14945 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14946 } 14947 14948 synchronized (mInstallLock) { 14949 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14950 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14951 "deletePackageX")) { 14952 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14953 deleteFlags | REMOVE_CHATTY, info, true, null); 14954 } 14955 synchronized (mPackages) { 14956 if (res) { 14957 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14958 } 14959 } 14960 } 14961 14962 if (res) { 14963 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 14964 info.sendPackageRemovedBroadcasts(killApp); 14965 info.sendSystemPackageUpdatedBroadcasts(); 14966 info.sendSystemPackageAppearedBroadcasts(); 14967 } 14968 // Force a gc here. 14969 Runtime.getRuntime().gc(); 14970 // Delete the resources here after sending the broadcast to let 14971 // other processes clean up before deleting resources. 14972 if (info.args != null) { 14973 synchronized (mInstallLock) { 14974 info.args.doPostDeleteLI(true); 14975 } 14976 } 14977 14978 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14979 } 14980 14981 class PackageRemovedInfo { 14982 String removedPackage; 14983 int uid = -1; 14984 int removedAppId = -1; 14985 int[] origUsers; 14986 int[] removedUsers = null; 14987 boolean isRemovedPackageSystemUpdate = false; 14988 boolean isUpdate; 14989 boolean dataRemoved; 14990 boolean removedForAllUsers; 14991 // Clean up resources deleted packages. 14992 InstallArgs args = null; 14993 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14994 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14995 14996 void sendPackageRemovedBroadcasts(boolean killApp) { 14997 sendPackageRemovedBroadcastInternal(killApp); 14998 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14999 for (int i = 0; i < childCount; i++) { 15000 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15001 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15002 } 15003 } 15004 15005 void sendSystemPackageUpdatedBroadcasts() { 15006 if (isRemovedPackageSystemUpdate) { 15007 sendSystemPackageUpdatedBroadcastsInternal(); 15008 final int childCount = (removedChildPackages != null) 15009 ? removedChildPackages.size() : 0; 15010 for (int i = 0; i < childCount; i++) { 15011 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15012 if (childInfo.isRemovedPackageSystemUpdate) { 15013 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15014 } 15015 } 15016 } 15017 } 15018 15019 void sendSystemPackageAppearedBroadcasts() { 15020 final int packageCount = (appearedChildPackages != null) 15021 ? appearedChildPackages.size() : 0; 15022 for (int i = 0; i < packageCount; i++) { 15023 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15024 for (int userId : installedInfo.newUsers) { 15025 sendPackageAddedForUser(installedInfo.name, true, 15026 UserHandle.getAppId(installedInfo.uid), userId); 15027 } 15028 } 15029 } 15030 15031 private void sendSystemPackageUpdatedBroadcastsInternal() { 15032 Bundle extras = new Bundle(2); 15033 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15034 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15035 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15036 extras, 0, null, null, null); 15037 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15038 extras, 0, null, null, null); 15039 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15040 null, 0, removedPackage, null, null); 15041 } 15042 15043 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15044 Bundle extras = new Bundle(2); 15045 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15046 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15047 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15048 if (isUpdate || isRemovedPackageSystemUpdate) { 15049 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15050 } 15051 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15052 if (removedPackage != null) { 15053 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15054 extras, 0, null, null, removedUsers); 15055 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15056 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15057 removedPackage, extras, 0, null, null, removedUsers); 15058 } 15059 } 15060 if (removedAppId >= 0) { 15061 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15062 removedUsers); 15063 } 15064 } 15065 } 15066 15067 /* 15068 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15069 * flag is not set, the data directory is removed as well. 15070 * make sure this flag is set for partially installed apps. If not its meaningless to 15071 * delete a partially installed application. 15072 */ 15073 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15074 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15075 String packageName = ps.name; 15076 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15077 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 15078 // Retrieve object to delete permissions for shared user later on 15079 final PackageSetting deletedPs; 15080 // reader 15081 synchronized (mPackages) { 15082 deletedPs = mSettings.mPackages.get(packageName); 15083 if (outInfo != null) { 15084 outInfo.removedPackage = packageName; 15085 outInfo.removedUsers = deletedPs != null 15086 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15087 : null; 15088 } 15089 } 15090 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15091 removeDataDirsLIF(ps.volumeUuid, ps.name); 15092 if (outInfo != null) { 15093 outInfo.dataRemoved = true; 15094 } 15095 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15096 } 15097 // writer 15098 synchronized (mPackages) { 15099 if (deletedPs != null) { 15100 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15101 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15102 clearDefaultBrowserIfNeeded(packageName); 15103 if (outInfo != null) { 15104 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15105 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15106 } 15107 updatePermissionsLPw(deletedPs.name, null, 0); 15108 if (deletedPs.sharedUser != null) { 15109 // Remove permissions associated with package. Since runtime 15110 // permissions are per user we have to kill the removed package 15111 // or packages running under the shared user of the removed 15112 // package if revoking the permissions requested only by the removed 15113 // package is successful and this causes a change in gids. 15114 for (int userId : UserManagerService.getInstance().getUserIds()) { 15115 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15116 userId); 15117 if (userIdToKill == UserHandle.USER_ALL 15118 || userIdToKill >= UserHandle.USER_SYSTEM) { 15119 // If gids changed for this user, kill all affected packages. 15120 mHandler.post(new Runnable() { 15121 @Override 15122 public void run() { 15123 // This has to happen with no lock held. 15124 killApplication(deletedPs.name, deletedPs.appId, 15125 KILL_APP_REASON_GIDS_CHANGED); 15126 } 15127 }); 15128 break; 15129 } 15130 } 15131 } 15132 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15133 } 15134 // make sure to preserve per-user disabled state if this removal was just 15135 // a downgrade of a system app to the factory package 15136 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15137 if (DEBUG_REMOVE) { 15138 Slog.d(TAG, "Propagating install state across downgrade"); 15139 } 15140 for (int userId : allUserHandles) { 15141 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15142 if (DEBUG_REMOVE) { 15143 Slog.d(TAG, " user " + userId + " => " + installed); 15144 } 15145 ps.setInstalled(installed, userId); 15146 } 15147 } 15148 } 15149 // can downgrade to reader 15150 if (writeSettings) { 15151 // Save settings now 15152 mSettings.writeLPr(); 15153 } 15154 } 15155 if (outInfo != null) { 15156 // A user ID was deleted here. Go through all users and remove it 15157 // from KeyStore. 15158 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15159 } 15160 } 15161 15162 static boolean locationIsPrivileged(File path) { 15163 try { 15164 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15165 .getCanonicalPath(); 15166 return path.getCanonicalPath().startsWith(privilegedAppDir); 15167 } catch (IOException e) { 15168 Slog.e(TAG, "Unable to access code path " + path); 15169 } 15170 return false; 15171 } 15172 15173 /* 15174 * Tries to delete system package. 15175 */ 15176 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15177 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15178 boolean writeSettings) { 15179 if (deletedPs.parentPackageName != null) { 15180 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15181 return false; 15182 } 15183 15184 final boolean applyUserRestrictions 15185 = (allUserHandles != null) && (outInfo.origUsers != null); 15186 final PackageSetting disabledPs; 15187 // Confirm if the system package has been updated 15188 // An updated system app can be deleted. This will also have to restore 15189 // the system pkg from system partition 15190 // reader 15191 synchronized (mPackages) { 15192 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15193 } 15194 15195 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15196 + " disabledPs=" + disabledPs); 15197 15198 if (disabledPs == null) { 15199 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15200 return false; 15201 } else if (DEBUG_REMOVE) { 15202 Slog.d(TAG, "Deleting system pkg from data partition"); 15203 } 15204 15205 if (DEBUG_REMOVE) { 15206 if (applyUserRestrictions) { 15207 Slog.d(TAG, "Remembering install states:"); 15208 for (int userId : allUserHandles) { 15209 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15210 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15211 } 15212 } 15213 } 15214 15215 // Delete the updated package 15216 outInfo.isRemovedPackageSystemUpdate = true; 15217 if (outInfo.removedChildPackages != null) { 15218 final int childCount = (deletedPs.childPackageNames != null) 15219 ? deletedPs.childPackageNames.size() : 0; 15220 for (int i = 0; i < childCount; i++) { 15221 String childPackageName = deletedPs.childPackageNames.get(i); 15222 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15223 .contains(childPackageName)) { 15224 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15225 childPackageName); 15226 if (childInfo != null) { 15227 childInfo.isRemovedPackageSystemUpdate = true; 15228 } 15229 } 15230 } 15231 } 15232 15233 if (disabledPs.versionCode < deletedPs.versionCode) { 15234 // Delete data for downgrades 15235 flags &= ~PackageManager.DELETE_KEEP_DATA; 15236 } else { 15237 // Preserve data by setting flag 15238 flags |= PackageManager.DELETE_KEEP_DATA; 15239 } 15240 15241 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15242 outInfo, writeSettings, disabledPs.pkg); 15243 if (!ret) { 15244 return false; 15245 } 15246 15247 // writer 15248 synchronized (mPackages) { 15249 // Reinstate the old system package 15250 enableSystemPackageLPw(disabledPs.pkg); 15251 // Remove any native libraries from the upgraded package. 15252 removeNativeBinariesLI(deletedPs); 15253 } 15254 15255 // Install the system package 15256 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15257 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15258 if (locationIsPrivileged(disabledPs.codePath)) { 15259 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15260 } 15261 15262 final PackageParser.Package newPkg; 15263 try { 15264 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15265 } catch (PackageManagerException e) { 15266 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15267 + e.getMessage()); 15268 return false; 15269 } 15270 15271 prepareAppDataAfterInstall(newPkg); 15272 15273 // writer 15274 synchronized (mPackages) { 15275 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15276 15277 // Propagate the permissions state as we do not want to drop on the floor 15278 // runtime permissions. The update permissions method below will take 15279 // care of removing obsolete permissions and grant install permissions. 15280 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15281 updatePermissionsLPw(newPkg.packageName, newPkg, 15282 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15283 15284 if (applyUserRestrictions) { 15285 if (DEBUG_REMOVE) { 15286 Slog.d(TAG, "Propagating install state across reinstall"); 15287 } 15288 for (int userId : allUserHandles) { 15289 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15290 if (DEBUG_REMOVE) { 15291 Slog.d(TAG, " user " + userId + " => " + installed); 15292 } 15293 ps.setInstalled(installed, userId); 15294 15295 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15296 } 15297 // Regardless of writeSettings we need to ensure that this restriction 15298 // state propagation is persisted 15299 mSettings.writeAllUsersPackageRestrictionsLPr(); 15300 } 15301 // can downgrade to reader here 15302 if (writeSettings) { 15303 mSettings.writeLPr(); 15304 } 15305 } 15306 return true; 15307 } 15308 15309 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15310 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15311 PackageRemovedInfo outInfo, boolean writeSettings, 15312 PackageParser.Package replacingPackage) { 15313 synchronized (mPackages) { 15314 if (outInfo != null) { 15315 outInfo.uid = ps.appId; 15316 } 15317 15318 if (outInfo != null && outInfo.removedChildPackages != null) { 15319 final int childCount = (ps.childPackageNames != null) 15320 ? ps.childPackageNames.size() : 0; 15321 for (int i = 0; i < childCount; i++) { 15322 String childPackageName = ps.childPackageNames.get(i); 15323 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15324 if (childPs == null) { 15325 return false; 15326 } 15327 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15328 childPackageName); 15329 if (childInfo != null) { 15330 childInfo.uid = childPs.appId; 15331 } 15332 } 15333 } 15334 } 15335 15336 // Delete package data from internal structures and also remove data if flag is set 15337 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15338 15339 // Delete the child packages data 15340 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15341 for (int i = 0; i < childCount; i++) { 15342 PackageSetting childPs; 15343 synchronized (mPackages) { 15344 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15345 } 15346 if (childPs != null) { 15347 PackageRemovedInfo childOutInfo = (outInfo != null 15348 && outInfo.removedChildPackages != null) 15349 ? outInfo.removedChildPackages.get(childPs.name) : null; 15350 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15351 && (replacingPackage != null 15352 && !replacingPackage.hasChildPackage(childPs.name)) 15353 ? flags & ~DELETE_KEEP_DATA : flags; 15354 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15355 deleteFlags, writeSettings); 15356 } 15357 } 15358 15359 // Delete application code and resources only for parent packages 15360 if (ps.parentPackageName == null) { 15361 if (deleteCodeAndResources && (outInfo != null)) { 15362 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15363 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15364 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15365 } 15366 } 15367 15368 return true; 15369 } 15370 15371 @Override 15372 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15373 int userId) { 15374 mContext.enforceCallingOrSelfPermission( 15375 android.Manifest.permission.DELETE_PACKAGES, null); 15376 synchronized (mPackages) { 15377 PackageSetting ps = mSettings.mPackages.get(packageName); 15378 if (ps == null) { 15379 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15380 return false; 15381 } 15382 if (!ps.getInstalled(userId)) { 15383 // Can't block uninstall for an app that is not installed or enabled. 15384 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15385 return false; 15386 } 15387 ps.setBlockUninstall(blockUninstall, userId); 15388 mSettings.writePackageRestrictionsLPr(userId); 15389 } 15390 return true; 15391 } 15392 15393 @Override 15394 public boolean getBlockUninstallForUser(String packageName, int userId) { 15395 synchronized (mPackages) { 15396 PackageSetting ps = mSettings.mPackages.get(packageName); 15397 if (ps == null) { 15398 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15399 return false; 15400 } 15401 return ps.getBlockUninstall(userId); 15402 } 15403 } 15404 15405 @Override 15406 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15407 int callingUid = Binder.getCallingUid(); 15408 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15409 throw new SecurityException( 15410 "setRequiredForSystemUser can only be run by the system or root"); 15411 } 15412 synchronized (mPackages) { 15413 PackageSetting ps = mSettings.mPackages.get(packageName); 15414 if (ps == null) { 15415 Log.w(TAG, "Package doesn't exist: " + packageName); 15416 return false; 15417 } 15418 if (systemUserApp) { 15419 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15420 } else { 15421 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15422 } 15423 mSettings.writeLPr(); 15424 } 15425 return true; 15426 } 15427 15428 /* 15429 * This method handles package deletion in general 15430 */ 15431 private boolean deletePackageLIF(String packageName, UserHandle user, 15432 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15433 PackageRemovedInfo outInfo, boolean writeSettings, 15434 PackageParser.Package replacingPackage) { 15435 if (packageName == null) { 15436 Slog.w(TAG, "Attempt to delete null packageName."); 15437 return false; 15438 } 15439 15440 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15441 15442 PackageSetting ps; 15443 15444 synchronized (mPackages) { 15445 ps = mSettings.mPackages.get(packageName); 15446 if (ps == null) { 15447 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15448 return false; 15449 } 15450 15451 if (ps.parentPackageName != null && (!isSystemApp(ps) 15452 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15453 if (DEBUG_REMOVE) { 15454 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15455 + ((user == null) ? UserHandle.USER_ALL : user)); 15456 } 15457 final int removedUserId = (user != null) ? user.getIdentifier() 15458 : UserHandle.USER_ALL; 15459 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15460 return false; 15461 } 15462 markPackageUninstalledForUserLPw(ps, user); 15463 scheduleWritePackageRestrictionsLocked(user); 15464 return true; 15465 } 15466 } 15467 15468 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15469 && user.getIdentifier() != UserHandle.USER_ALL)) { 15470 // The caller is asking that the package only be deleted for a single 15471 // user. To do this, we just mark its uninstalled state and delete 15472 // its data. If this is a system app, we only allow this to happen if 15473 // they have set the special DELETE_SYSTEM_APP which requests different 15474 // semantics than normal for uninstalling system apps. 15475 markPackageUninstalledForUserLPw(ps, user); 15476 15477 if (!isSystemApp(ps)) { 15478 // Do not uninstall the APK if an app should be cached 15479 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15480 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15481 // Other user still have this package installed, so all 15482 // we need to do is clear this user's data and save that 15483 // it is uninstalled. 15484 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15485 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15486 return false; 15487 } 15488 scheduleWritePackageRestrictionsLocked(user); 15489 return true; 15490 } else { 15491 // We need to set it back to 'installed' so the uninstall 15492 // broadcasts will be sent correctly. 15493 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15494 ps.setInstalled(true, user.getIdentifier()); 15495 } 15496 } else { 15497 // This is a system app, so we assume that the 15498 // other users still have this package installed, so all 15499 // we need to do is clear this user's data and save that 15500 // it is uninstalled. 15501 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15502 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15503 return false; 15504 } 15505 scheduleWritePackageRestrictionsLocked(user); 15506 return true; 15507 } 15508 } 15509 15510 // If we are deleting a composite package for all users, keep track 15511 // of result for each child. 15512 if (ps.childPackageNames != null && outInfo != null) { 15513 synchronized (mPackages) { 15514 final int childCount = ps.childPackageNames.size(); 15515 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15516 for (int i = 0; i < childCount; i++) { 15517 String childPackageName = ps.childPackageNames.get(i); 15518 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15519 childInfo.removedPackage = childPackageName; 15520 outInfo.removedChildPackages.put(childPackageName, childInfo); 15521 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15522 if (childPs != null) { 15523 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15524 } 15525 } 15526 } 15527 } 15528 15529 boolean ret = false; 15530 if (isSystemApp(ps)) { 15531 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15532 // When an updated system application is deleted we delete the existing resources 15533 // as well and fall back to existing code in system partition 15534 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15535 } else { 15536 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15537 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15538 outInfo, writeSettings, replacingPackage); 15539 } 15540 15541 // Take a note whether we deleted the package for all users 15542 if (outInfo != null) { 15543 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15544 if (outInfo.removedChildPackages != null) { 15545 synchronized (mPackages) { 15546 final int childCount = outInfo.removedChildPackages.size(); 15547 for (int i = 0; i < childCount; i++) { 15548 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15549 if (childInfo != null) { 15550 childInfo.removedForAllUsers = mPackages.get( 15551 childInfo.removedPackage) == null; 15552 } 15553 } 15554 } 15555 } 15556 // If we uninstalled an update to a system app there may be some 15557 // child packages that appeared as they are declared in the system 15558 // app but were not declared in the update. 15559 if (isSystemApp(ps)) { 15560 synchronized (mPackages) { 15561 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15562 final int childCount = (updatedPs.childPackageNames != null) 15563 ? updatedPs.childPackageNames.size() : 0; 15564 for (int i = 0; i < childCount; i++) { 15565 String childPackageName = updatedPs.childPackageNames.get(i); 15566 if (outInfo.removedChildPackages == null 15567 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15568 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15569 if (childPs == null) { 15570 continue; 15571 } 15572 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15573 installRes.name = childPackageName; 15574 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15575 installRes.pkg = mPackages.get(childPackageName); 15576 installRes.uid = childPs.pkg.applicationInfo.uid; 15577 if (outInfo.appearedChildPackages == null) { 15578 outInfo.appearedChildPackages = new ArrayMap<>(); 15579 } 15580 outInfo.appearedChildPackages.put(childPackageName, installRes); 15581 } 15582 } 15583 } 15584 } 15585 } 15586 15587 return ret; 15588 } 15589 15590 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15591 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15592 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15593 for (int nextUserId : userIds) { 15594 if (DEBUG_REMOVE) { 15595 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15596 } 15597 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15598 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15599 false /*hidden*/, false /*suspended*/, null, null, null, 15600 false /*blockUninstall*/, 15601 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15602 } 15603 } 15604 15605 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15606 PackageRemovedInfo outInfo) { 15607 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15608 : new int[] {userId}; 15609 for (int nextUserId : userIds) { 15610 if (DEBUG_REMOVE) { 15611 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15612 + nextUserId); 15613 } 15614 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15615 try { 15616 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15617 } catch (InstallerException e) { 15618 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15619 return false; 15620 } 15621 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15622 schedulePackageCleaning(ps.name, nextUserId, false); 15623 synchronized (mPackages) { 15624 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15625 scheduleWritePackageRestrictionsLocked(nextUserId); 15626 } 15627 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15628 } 15629 } 15630 15631 if (outInfo != null) { 15632 outInfo.removedPackage = ps.name; 15633 outInfo.removedAppId = ps.appId; 15634 outInfo.removedUsers = userIds; 15635 } 15636 15637 return true; 15638 } 15639 15640 private final class ClearStorageConnection implements ServiceConnection { 15641 IMediaContainerService mContainerService; 15642 15643 @Override 15644 public void onServiceConnected(ComponentName name, IBinder service) { 15645 synchronized (this) { 15646 mContainerService = IMediaContainerService.Stub.asInterface(service); 15647 notifyAll(); 15648 } 15649 } 15650 15651 @Override 15652 public void onServiceDisconnected(ComponentName name) { 15653 } 15654 } 15655 15656 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15657 final boolean mounted; 15658 if (Environment.isExternalStorageEmulated()) { 15659 mounted = true; 15660 } else { 15661 final String status = Environment.getExternalStorageState(); 15662 15663 mounted = status.equals(Environment.MEDIA_MOUNTED) 15664 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15665 } 15666 15667 if (!mounted) { 15668 return; 15669 } 15670 15671 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15672 int[] users; 15673 if (userId == UserHandle.USER_ALL) { 15674 users = sUserManager.getUserIds(); 15675 } else { 15676 users = new int[] { userId }; 15677 } 15678 final ClearStorageConnection conn = new ClearStorageConnection(); 15679 if (mContext.bindServiceAsUser( 15680 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15681 try { 15682 for (int curUser : users) { 15683 long timeout = SystemClock.uptimeMillis() + 5000; 15684 synchronized (conn) { 15685 long now = SystemClock.uptimeMillis(); 15686 while (conn.mContainerService == null && now < timeout) { 15687 try { 15688 conn.wait(timeout - now); 15689 } catch (InterruptedException e) { 15690 } 15691 } 15692 } 15693 if (conn.mContainerService == null) { 15694 return; 15695 } 15696 15697 final UserEnvironment userEnv = new UserEnvironment(curUser); 15698 clearDirectory(conn.mContainerService, 15699 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15700 if (allData) { 15701 clearDirectory(conn.mContainerService, 15702 userEnv.buildExternalStorageAppDataDirs(packageName)); 15703 clearDirectory(conn.mContainerService, 15704 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15705 } 15706 } 15707 } finally { 15708 mContext.unbindService(conn); 15709 } 15710 } 15711 } 15712 15713 @Override 15714 public void clearApplicationProfileData(String packageName) { 15715 enforceSystemOrRoot("Only the system can clear all profile data"); 15716 synchronized (mInstallLock) { 15717 try (PackageFreezer freezer = freezePackage(packageName, 15718 "clearApplicationProfileData")) { 15719 try { 15720 mInstaller.clearAppProfiles(packageName); 15721 } catch (InstallerException ex) { 15722 Log.e(TAG, "Could not clear profile data of package " + packageName); 15723 } 15724 } 15725 } 15726 } 15727 15728 @Override 15729 public void clearApplicationUserData(final String packageName, 15730 final IPackageDataObserver observer, final int userId) { 15731 mContext.enforceCallingOrSelfPermission( 15732 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15733 15734 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15735 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15736 15737 final DevicePolicyManagerInternal dpmi = LocalServices 15738 .getService(DevicePolicyManagerInternal.class); 15739 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15740 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15741 } 15742 // Queue up an async operation since the package deletion may take a little while. 15743 mHandler.post(new Runnable() { 15744 public void run() { 15745 mHandler.removeCallbacks(this); 15746 final boolean succeeded; 15747 synchronized (mInstallLock) { 15748 try (PackageFreezer freezer = freezePackage(packageName, 15749 "clearApplicationUserData")) { 15750 succeeded = clearApplicationUserDataLIF(packageName, userId); 15751 } 15752 } 15753 clearExternalStorageDataSync(packageName, userId, true); 15754 if (succeeded) { 15755 // invoke DeviceStorageMonitor's update method to clear any notifications 15756 DeviceStorageMonitorInternal dsm = LocalServices 15757 .getService(DeviceStorageMonitorInternal.class); 15758 if (dsm != null) { 15759 dsm.checkMemory(); 15760 } 15761 } 15762 if(observer != null) { 15763 try { 15764 observer.onRemoveCompleted(packageName, succeeded); 15765 } catch (RemoteException e) { 15766 Log.i(TAG, "Observer no longer exists."); 15767 } 15768 } //end if observer 15769 } //end run 15770 }); 15771 } 15772 15773 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15774 if (packageName == null) { 15775 Slog.w(TAG, "Attempt to delete null packageName."); 15776 return false; 15777 } 15778 15779 // Try finding details about the requested package 15780 PackageParser.Package pkg; 15781 synchronized (mPackages) { 15782 pkg = mPackages.get(packageName); 15783 if (pkg == null) { 15784 final PackageSetting ps = mSettings.mPackages.get(packageName); 15785 if (ps != null) { 15786 pkg = ps.pkg; 15787 } 15788 } 15789 15790 if (pkg == null) { 15791 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15792 return false; 15793 } 15794 15795 PackageSetting ps = (PackageSetting) pkg.mExtras; 15796 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15797 } 15798 15799 // Always delete data directories for package, even if we found no other 15800 // record of app. This helps users recover from UID mismatches without 15801 // resorting to a full data wipe. 15802 // TODO: triage flags as part of 26466827 15803 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15804 try { 15805 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15806 } catch (InstallerException e) { 15807 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15808 return false; 15809 } 15810 15811 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15812 removeKeystoreDataIfNeeded(userId, appId); 15813 15814 // Create a native library symlink only if we have native libraries 15815 // and if the native libraries are 32 bit libraries. We do not provide 15816 // this symlink for 64 bit libraries. 15817 if (pkg.applicationInfo.primaryCpuAbi != null && 15818 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15819 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15820 try { 15821 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15822 nativeLibPath, userId); 15823 } catch (InstallerException e) { 15824 Slog.w(TAG, "Failed linking native library dir", e); 15825 return false; 15826 } 15827 } 15828 15829 return true; 15830 } 15831 15832 /** 15833 * Reverts user permission state changes (permissions and flags) in 15834 * all packages for a given user. 15835 * 15836 * @param userId The device user for which to do a reset. 15837 */ 15838 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15839 final int packageCount = mPackages.size(); 15840 for (int i = 0; i < packageCount; i++) { 15841 PackageParser.Package pkg = mPackages.valueAt(i); 15842 PackageSetting ps = (PackageSetting) pkg.mExtras; 15843 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15844 } 15845 } 15846 15847 /** 15848 * Reverts user permission state changes (permissions and flags). 15849 * 15850 * @param ps The package for which to reset. 15851 * @param userId The device user for which to do a reset. 15852 */ 15853 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15854 final PackageSetting ps, final int userId) { 15855 if (ps.pkg == null) { 15856 return; 15857 } 15858 15859 // These are flags that can change base on user actions. 15860 final int userSettableMask = FLAG_PERMISSION_USER_SET 15861 | FLAG_PERMISSION_USER_FIXED 15862 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15863 | FLAG_PERMISSION_REVIEW_REQUIRED; 15864 15865 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15866 | FLAG_PERMISSION_POLICY_FIXED; 15867 15868 boolean writeInstallPermissions = false; 15869 boolean writeRuntimePermissions = false; 15870 15871 final int permissionCount = ps.pkg.requestedPermissions.size(); 15872 for (int i = 0; i < permissionCount; i++) { 15873 String permission = ps.pkg.requestedPermissions.get(i); 15874 15875 BasePermission bp = mSettings.mPermissions.get(permission); 15876 if (bp == null) { 15877 continue; 15878 } 15879 15880 // If shared user we just reset the state to which only this app contributed. 15881 if (ps.sharedUser != null) { 15882 boolean used = false; 15883 final int packageCount = ps.sharedUser.packages.size(); 15884 for (int j = 0; j < packageCount; j++) { 15885 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15886 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15887 && pkg.pkg.requestedPermissions.contains(permission)) { 15888 used = true; 15889 break; 15890 } 15891 } 15892 if (used) { 15893 continue; 15894 } 15895 } 15896 15897 PermissionsState permissionsState = ps.getPermissionsState(); 15898 15899 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15900 15901 // Always clear the user settable flags. 15902 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15903 bp.name) != null; 15904 // If permission review is enabled and this is a legacy app, mark the 15905 // permission as requiring a review as this is the initial state. 15906 int flags = 0; 15907 if (Build.PERMISSIONS_REVIEW_REQUIRED 15908 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15909 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15910 } 15911 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15912 if (hasInstallState) { 15913 writeInstallPermissions = true; 15914 } else { 15915 writeRuntimePermissions = true; 15916 } 15917 } 15918 15919 // Below is only runtime permission handling. 15920 if (!bp.isRuntime()) { 15921 continue; 15922 } 15923 15924 // Never clobber system or policy. 15925 if ((oldFlags & policyOrSystemFlags) != 0) { 15926 continue; 15927 } 15928 15929 // If this permission was granted by default, make sure it is. 15930 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15931 if (permissionsState.grantRuntimePermission(bp, userId) 15932 != PERMISSION_OPERATION_FAILURE) { 15933 writeRuntimePermissions = true; 15934 } 15935 // If permission review is enabled the permissions for a legacy apps 15936 // are represented as constantly granted runtime ones, so don't revoke. 15937 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15938 // Otherwise, reset the permission. 15939 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15940 switch (revokeResult) { 15941 case PERMISSION_OPERATION_SUCCESS: 15942 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15943 writeRuntimePermissions = true; 15944 final int appId = ps.appId; 15945 mHandler.post(new Runnable() { 15946 @Override 15947 public void run() { 15948 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15949 } 15950 }); 15951 } break; 15952 } 15953 } 15954 } 15955 15956 // Synchronously write as we are taking permissions away. 15957 if (writeRuntimePermissions) { 15958 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15959 } 15960 15961 // Synchronously write as we are taking permissions away. 15962 if (writeInstallPermissions) { 15963 mSettings.writeLPr(); 15964 } 15965 } 15966 15967 /** 15968 * Remove entries from the keystore daemon. Will only remove it if the 15969 * {@code appId} is valid. 15970 */ 15971 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15972 if (appId < 0) { 15973 return; 15974 } 15975 15976 final KeyStore keyStore = KeyStore.getInstance(); 15977 if (keyStore != null) { 15978 if (userId == UserHandle.USER_ALL) { 15979 for (final int individual : sUserManager.getUserIds()) { 15980 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15981 } 15982 } else { 15983 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15984 } 15985 } else { 15986 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15987 } 15988 } 15989 15990 @Override 15991 public void deleteApplicationCacheFiles(final String packageName, 15992 final IPackageDataObserver observer) { 15993 mContext.enforceCallingOrSelfPermission( 15994 android.Manifest.permission.DELETE_CACHE_FILES, null); 15995 // Queue up an async operation since the package deletion may take a little while. 15996 final int userId = UserHandle.getCallingUserId(); 15997 mHandler.post(new Runnable() { 15998 public void run() { 15999 mHandler.removeCallbacks(this); 16000 final boolean succeded; 16001 synchronized (mInstallLock) { 16002 succeded = deleteApplicationCacheFilesLI(packageName, userId); 16003 } 16004 clearExternalStorageDataSync(packageName, userId, false); 16005 if (observer != null) { 16006 try { 16007 observer.onRemoveCompleted(packageName, succeded); 16008 } catch (RemoteException e) { 16009 Log.i(TAG, "Observer no longer exists."); 16010 } 16011 } //end if observer 16012 } //end run 16013 }); 16014 } 16015 16016 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 16017 if (packageName == null) { 16018 Slog.w(TAG, "Attempt to delete null packageName."); 16019 return false; 16020 } 16021 PackageParser.Package p; 16022 synchronized (mPackages) { 16023 p = mPackages.get(packageName); 16024 } 16025 if (p == null) { 16026 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16027 return false; 16028 } 16029 final ApplicationInfo applicationInfo = p.applicationInfo; 16030 if (applicationInfo == null) { 16031 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16032 return false; 16033 } 16034 // TODO: triage flags as part of 26466827 16035 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16036 try { 16037 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 16038 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16039 } catch (InstallerException e) { 16040 Slog.w(TAG, "Couldn't remove cache files for package " 16041 + packageName + " u" + userId, e); 16042 return false; 16043 } 16044 return true; 16045 } 16046 16047 @Override 16048 public void getPackageSizeInfo(final String packageName, int userHandle, 16049 final IPackageStatsObserver observer) { 16050 mContext.enforceCallingOrSelfPermission( 16051 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16052 if (packageName == null) { 16053 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16054 } 16055 16056 PackageStats stats = new PackageStats(packageName, userHandle); 16057 16058 /* 16059 * Queue up an async operation since the package measurement may take a 16060 * little while. 16061 */ 16062 Message msg = mHandler.obtainMessage(INIT_COPY); 16063 msg.obj = new MeasureParams(stats, observer); 16064 mHandler.sendMessage(msg); 16065 } 16066 16067 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 16068 PackageStats pStats) { 16069 if (packageName == null) { 16070 Slog.w(TAG, "Attempt to get size of null packageName."); 16071 return false; 16072 } 16073 PackageParser.Package p; 16074 boolean dataOnly = false; 16075 String libDirRoot = null; 16076 String asecPath = null; 16077 PackageSetting ps = null; 16078 synchronized (mPackages) { 16079 p = mPackages.get(packageName); 16080 ps = mSettings.mPackages.get(packageName); 16081 if(p == null) { 16082 dataOnly = true; 16083 if((ps == null) || (ps.pkg == null)) { 16084 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16085 return false; 16086 } 16087 p = ps.pkg; 16088 } 16089 if (ps != null) { 16090 libDirRoot = ps.legacyNativeLibraryPathString; 16091 } 16092 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16093 final long token = Binder.clearCallingIdentity(); 16094 try { 16095 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16096 if (secureContainerId != null) { 16097 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16098 } 16099 } finally { 16100 Binder.restoreCallingIdentity(token); 16101 } 16102 } 16103 } 16104 String publicSrcDir = null; 16105 if(!dataOnly) { 16106 final ApplicationInfo applicationInfo = p.applicationInfo; 16107 if (applicationInfo == null) { 16108 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16109 return false; 16110 } 16111 if (p.isForwardLocked()) { 16112 publicSrcDir = applicationInfo.getBaseResourcePath(); 16113 } 16114 } 16115 // TODO: extend to measure size of split APKs 16116 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16117 // not just the first level. 16118 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16119 // just the primary. 16120 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16121 16122 String apkPath; 16123 File packageDir = new File(p.codePath); 16124 16125 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16126 apkPath = packageDir.getAbsolutePath(); 16127 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16128 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16129 libDirRoot = null; 16130 } 16131 } else { 16132 apkPath = p.baseCodePath; 16133 } 16134 16135 // TODO: triage flags as part of 26466827 16136 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16137 try { 16138 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16139 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16140 } catch (InstallerException e) { 16141 return false; 16142 } 16143 16144 // Fix-up for forward-locked applications in ASEC containers. 16145 if (!isExternal(p)) { 16146 pStats.codeSize += pStats.externalCodeSize; 16147 pStats.externalCodeSize = 0L; 16148 } 16149 16150 return true; 16151 } 16152 16153 private int getUidTargetSdkVersionLockedLPr(int uid) { 16154 Object obj = mSettings.getUserIdLPr(uid); 16155 if (obj instanceof SharedUserSetting) { 16156 final SharedUserSetting sus = (SharedUserSetting) obj; 16157 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16158 final Iterator<PackageSetting> it = sus.packages.iterator(); 16159 while (it.hasNext()) { 16160 final PackageSetting ps = it.next(); 16161 if (ps.pkg != null) { 16162 int v = ps.pkg.applicationInfo.targetSdkVersion; 16163 if (v < vers) vers = v; 16164 } 16165 } 16166 return vers; 16167 } else if (obj instanceof PackageSetting) { 16168 final PackageSetting ps = (PackageSetting) obj; 16169 if (ps.pkg != null) { 16170 return ps.pkg.applicationInfo.targetSdkVersion; 16171 } 16172 } 16173 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16174 } 16175 16176 @Override 16177 public void addPreferredActivity(IntentFilter filter, int match, 16178 ComponentName[] set, ComponentName activity, int userId) { 16179 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16180 "Adding preferred"); 16181 } 16182 16183 private void addPreferredActivityInternal(IntentFilter filter, int match, 16184 ComponentName[] set, ComponentName activity, boolean always, int userId, 16185 String opname) { 16186 // writer 16187 int callingUid = Binder.getCallingUid(); 16188 enforceCrossUserPermission(callingUid, userId, 16189 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16190 if (filter.countActions() == 0) { 16191 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16192 return; 16193 } 16194 synchronized (mPackages) { 16195 if (mContext.checkCallingOrSelfPermission( 16196 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16197 != PackageManager.PERMISSION_GRANTED) { 16198 if (getUidTargetSdkVersionLockedLPr(callingUid) 16199 < Build.VERSION_CODES.FROYO) { 16200 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16201 + callingUid); 16202 return; 16203 } 16204 mContext.enforceCallingOrSelfPermission( 16205 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16206 } 16207 16208 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16209 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16210 + userId + ":"); 16211 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16212 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16213 scheduleWritePackageRestrictionsLocked(userId); 16214 } 16215 } 16216 16217 @Override 16218 public void replacePreferredActivity(IntentFilter filter, int match, 16219 ComponentName[] set, ComponentName activity, int userId) { 16220 if (filter.countActions() != 1) { 16221 throw new IllegalArgumentException( 16222 "replacePreferredActivity expects filter to have only 1 action."); 16223 } 16224 if (filter.countDataAuthorities() != 0 16225 || filter.countDataPaths() != 0 16226 || filter.countDataSchemes() > 1 16227 || filter.countDataTypes() != 0) { 16228 throw new IllegalArgumentException( 16229 "replacePreferredActivity expects filter to have no data authorities, " + 16230 "paths, or types; and at most one scheme."); 16231 } 16232 16233 final int callingUid = Binder.getCallingUid(); 16234 enforceCrossUserPermission(callingUid, userId, 16235 true /* requireFullPermission */, false /* checkShell */, 16236 "replace preferred activity"); 16237 synchronized (mPackages) { 16238 if (mContext.checkCallingOrSelfPermission( 16239 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16240 != PackageManager.PERMISSION_GRANTED) { 16241 if (getUidTargetSdkVersionLockedLPr(callingUid) 16242 < Build.VERSION_CODES.FROYO) { 16243 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16244 + Binder.getCallingUid()); 16245 return; 16246 } 16247 mContext.enforceCallingOrSelfPermission( 16248 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16249 } 16250 16251 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16252 if (pir != null) { 16253 // Get all of the existing entries that exactly match this filter. 16254 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16255 if (existing != null && existing.size() == 1) { 16256 PreferredActivity cur = existing.get(0); 16257 if (DEBUG_PREFERRED) { 16258 Slog.i(TAG, "Checking replace of preferred:"); 16259 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16260 if (!cur.mPref.mAlways) { 16261 Slog.i(TAG, " -- CUR; not mAlways!"); 16262 } else { 16263 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16264 Slog.i(TAG, " -- CUR: mSet=" 16265 + Arrays.toString(cur.mPref.mSetComponents)); 16266 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16267 Slog.i(TAG, " -- NEW: mMatch=" 16268 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16269 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16270 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16271 } 16272 } 16273 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16274 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16275 && cur.mPref.sameSet(set)) { 16276 // Setting the preferred activity to what it happens to be already 16277 if (DEBUG_PREFERRED) { 16278 Slog.i(TAG, "Replacing with same preferred activity " 16279 + cur.mPref.mShortComponent + " for user " 16280 + userId + ":"); 16281 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16282 } 16283 return; 16284 } 16285 } 16286 16287 if (existing != null) { 16288 if (DEBUG_PREFERRED) { 16289 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16290 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16291 } 16292 for (int i = 0; i < existing.size(); i++) { 16293 PreferredActivity pa = existing.get(i); 16294 if (DEBUG_PREFERRED) { 16295 Slog.i(TAG, "Removing existing preferred activity " 16296 + pa.mPref.mComponent + ":"); 16297 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16298 } 16299 pir.removeFilter(pa); 16300 } 16301 } 16302 } 16303 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16304 "Replacing preferred"); 16305 } 16306 } 16307 16308 @Override 16309 public void clearPackagePreferredActivities(String packageName) { 16310 final int uid = Binder.getCallingUid(); 16311 // writer 16312 synchronized (mPackages) { 16313 PackageParser.Package pkg = mPackages.get(packageName); 16314 if (pkg == null || pkg.applicationInfo.uid != uid) { 16315 if (mContext.checkCallingOrSelfPermission( 16316 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16317 != PackageManager.PERMISSION_GRANTED) { 16318 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16319 < Build.VERSION_CODES.FROYO) { 16320 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16321 + Binder.getCallingUid()); 16322 return; 16323 } 16324 mContext.enforceCallingOrSelfPermission( 16325 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16326 } 16327 } 16328 16329 int user = UserHandle.getCallingUserId(); 16330 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16331 scheduleWritePackageRestrictionsLocked(user); 16332 } 16333 } 16334 } 16335 16336 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16337 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16338 ArrayList<PreferredActivity> removed = null; 16339 boolean changed = false; 16340 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16341 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16342 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16343 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16344 continue; 16345 } 16346 Iterator<PreferredActivity> it = pir.filterIterator(); 16347 while (it.hasNext()) { 16348 PreferredActivity pa = it.next(); 16349 // Mark entry for removal only if it matches the package name 16350 // and the entry is of type "always". 16351 if (packageName == null || 16352 (pa.mPref.mComponent.getPackageName().equals(packageName) 16353 && pa.mPref.mAlways)) { 16354 if (removed == null) { 16355 removed = new ArrayList<PreferredActivity>(); 16356 } 16357 removed.add(pa); 16358 } 16359 } 16360 if (removed != null) { 16361 for (int j=0; j<removed.size(); j++) { 16362 PreferredActivity pa = removed.get(j); 16363 pir.removeFilter(pa); 16364 } 16365 changed = true; 16366 } 16367 } 16368 return changed; 16369 } 16370 16371 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16372 private void clearIntentFilterVerificationsLPw(int userId) { 16373 final int packageCount = mPackages.size(); 16374 for (int i = 0; i < packageCount; i++) { 16375 PackageParser.Package pkg = mPackages.valueAt(i); 16376 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16377 } 16378 } 16379 16380 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16381 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16382 if (userId == UserHandle.USER_ALL) { 16383 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16384 sUserManager.getUserIds())) { 16385 for (int oneUserId : sUserManager.getUserIds()) { 16386 scheduleWritePackageRestrictionsLocked(oneUserId); 16387 } 16388 } 16389 } else { 16390 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16391 scheduleWritePackageRestrictionsLocked(userId); 16392 } 16393 } 16394 } 16395 16396 void clearDefaultBrowserIfNeeded(String packageName) { 16397 for (int oneUserId : sUserManager.getUserIds()) { 16398 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16399 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16400 if (packageName.equals(defaultBrowserPackageName)) { 16401 setDefaultBrowserPackageName(null, oneUserId); 16402 } 16403 } 16404 } 16405 16406 @Override 16407 public void resetApplicationPreferences(int userId) { 16408 mContext.enforceCallingOrSelfPermission( 16409 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16410 // writer 16411 synchronized (mPackages) { 16412 final long identity = Binder.clearCallingIdentity(); 16413 try { 16414 clearPackagePreferredActivitiesLPw(null, userId); 16415 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16416 // TODO: We have to reset the default SMS and Phone. This requires 16417 // significant refactoring to keep all default apps in the package 16418 // manager (cleaner but more work) or have the services provide 16419 // callbacks to the package manager to request a default app reset. 16420 applyFactoryDefaultBrowserLPw(userId); 16421 clearIntentFilterVerificationsLPw(userId); 16422 primeDomainVerificationsLPw(userId); 16423 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16424 scheduleWritePackageRestrictionsLocked(userId); 16425 } finally { 16426 Binder.restoreCallingIdentity(identity); 16427 } 16428 } 16429 } 16430 16431 @Override 16432 public int getPreferredActivities(List<IntentFilter> outFilters, 16433 List<ComponentName> outActivities, String packageName) { 16434 16435 int num = 0; 16436 final int userId = UserHandle.getCallingUserId(); 16437 // reader 16438 synchronized (mPackages) { 16439 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16440 if (pir != null) { 16441 final Iterator<PreferredActivity> it = pir.filterIterator(); 16442 while (it.hasNext()) { 16443 final PreferredActivity pa = it.next(); 16444 if (packageName == null 16445 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16446 && pa.mPref.mAlways)) { 16447 if (outFilters != null) { 16448 outFilters.add(new IntentFilter(pa)); 16449 } 16450 if (outActivities != null) { 16451 outActivities.add(pa.mPref.mComponent); 16452 } 16453 } 16454 } 16455 } 16456 } 16457 16458 return num; 16459 } 16460 16461 @Override 16462 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16463 int userId) { 16464 int callingUid = Binder.getCallingUid(); 16465 if (callingUid != Process.SYSTEM_UID) { 16466 throw new SecurityException( 16467 "addPersistentPreferredActivity can only be run by the system"); 16468 } 16469 if (filter.countActions() == 0) { 16470 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16471 return; 16472 } 16473 synchronized (mPackages) { 16474 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16475 ":"); 16476 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16477 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16478 new PersistentPreferredActivity(filter, activity)); 16479 scheduleWritePackageRestrictionsLocked(userId); 16480 } 16481 } 16482 16483 @Override 16484 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16485 int callingUid = Binder.getCallingUid(); 16486 if (callingUid != Process.SYSTEM_UID) { 16487 throw new SecurityException( 16488 "clearPackagePersistentPreferredActivities can only be run by the system"); 16489 } 16490 ArrayList<PersistentPreferredActivity> removed = null; 16491 boolean changed = false; 16492 synchronized (mPackages) { 16493 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16494 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16495 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16496 .valueAt(i); 16497 if (userId != thisUserId) { 16498 continue; 16499 } 16500 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16501 while (it.hasNext()) { 16502 PersistentPreferredActivity ppa = it.next(); 16503 // Mark entry for removal only if it matches the package name. 16504 if (ppa.mComponent.getPackageName().equals(packageName)) { 16505 if (removed == null) { 16506 removed = new ArrayList<PersistentPreferredActivity>(); 16507 } 16508 removed.add(ppa); 16509 } 16510 } 16511 if (removed != null) { 16512 for (int j=0; j<removed.size(); j++) { 16513 PersistentPreferredActivity ppa = removed.get(j); 16514 ppir.removeFilter(ppa); 16515 } 16516 changed = true; 16517 } 16518 } 16519 16520 if (changed) { 16521 scheduleWritePackageRestrictionsLocked(userId); 16522 } 16523 } 16524 } 16525 16526 /** 16527 * Common machinery for picking apart a restored XML blob and passing 16528 * it to a caller-supplied functor to be applied to the running system. 16529 */ 16530 private void restoreFromXml(XmlPullParser parser, int userId, 16531 String expectedStartTag, BlobXmlRestorer functor) 16532 throws IOException, XmlPullParserException { 16533 int type; 16534 while ((type = parser.next()) != XmlPullParser.START_TAG 16535 && type != XmlPullParser.END_DOCUMENT) { 16536 } 16537 if (type != XmlPullParser.START_TAG) { 16538 // oops didn't find a start tag?! 16539 if (DEBUG_BACKUP) { 16540 Slog.e(TAG, "Didn't find start tag during restore"); 16541 } 16542 return; 16543 } 16544Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16545 // this is supposed to be TAG_PREFERRED_BACKUP 16546 if (!expectedStartTag.equals(parser.getName())) { 16547 if (DEBUG_BACKUP) { 16548 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16549 } 16550 return; 16551 } 16552 16553 // skip interfering stuff, then we're aligned with the backing implementation 16554 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16555Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16556 functor.apply(parser, userId); 16557 } 16558 16559 private interface BlobXmlRestorer { 16560 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16561 } 16562 16563 /** 16564 * Non-Binder method, support for the backup/restore mechanism: write the 16565 * full set of preferred activities in its canonical XML format. Returns the 16566 * XML output as a byte array, or null if there is none. 16567 */ 16568 @Override 16569 public byte[] getPreferredActivityBackup(int userId) { 16570 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16571 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16572 } 16573 16574 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16575 try { 16576 final XmlSerializer serializer = new FastXmlSerializer(); 16577 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16578 serializer.startDocument(null, true); 16579 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16580 16581 synchronized (mPackages) { 16582 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16583 } 16584 16585 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16586 serializer.endDocument(); 16587 serializer.flush(); 16588 } catch (Exception e) { 16589 if (DEBUG_BACKUP) { 16590 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16591 } 16592 return null; 16593 } 16594 16595 return dataStream.toByteArray(); 16596 } 16597 16598 @Override 16599 public void restorePreferredActivities(byte[] backup, int userId) { 16600 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16601 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16602 } 16603 16604 try { 16605 final XmlPullParser parser = Xml.newPullParser(); 16606 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16607 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16608 new BlobXmlRestorer() { 16609 @Override 16610 public void apply(XmlPullParser parser, int userId) 16611 throws XmlPullParserException, IOException { 16612 synchronized (mPackages) { 16613 mSettings.readPreferredActivitiesLPw(parser, userId); 16614 } 16615 } 16616 } ); 16617 } catch (Exception e) { 16618 if (DEBUG_BACKUP) { 16619 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16620 } 16621 } 16622 } 16623 16624 /** 16625 * Non-Binder method, support for the backup/restore mechanism: write the 16626 * default browser (etc) settings in its canonical XML format. Returns the default 16627 * browser XML representation as a byte array, or null if there is none. 16628 */ 16629 @Override 16630 public byte[] getDefaultAppsBackup(int userId) { 16631 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16632 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16633 } 16634 16635 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16636 try { 16637 final XmlSerializer serializer = new FastXmlSerializer(); 16638 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16639 serializer.startDocument(null, true); 16640 serializer.startTag(null, TAG_DEFAULT_APPS); 16641 16642 synchronized (mPackages) { 16643 mSettings.writeDefaultAppsLPr(serializer, userId); 16644 } 16645 16646 serializer.endTag(null, TAG_DEFAULT_APPS); 16647 serializer.endDocument(); 16648 serializer.flush(); 16649 } catch (Exception e) { 16650 if (DEBUG_BACKUP) { 16651 Slog.e(TAG, "Unable to write default apps for backup", e); 16652 } 16653 return null; 16654 } 16655 16656 return dataStream.toByteArray(); 16657 } 16658 16659 @Override 16660 public void restoreDefaultApps(byte[] backup, int userId) { 16661 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16662 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16663 } 16664 16665 try { 16666 final XmlPullParser parser = Xml.newPullParser(); 16667 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16668 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16669 new BlobXmlRestorer() { 16670 @Override 16671 public void apply(XmlPullParser parser, int userId) 16672 throws XmlPullParserException, IOException { 16673 synchronized (mPackages) { 16674 mSettings.readDefaultAppsLPw(parser, userId); 16675 } 16676 } 16677 } ); 16678 } catch (Exception e) { 16679 if (DEBUG_BACKUP) { 16680 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16681 } 16682 } 16683 } 16684 16685 @Override 16686 public byte[] getIntentFilterVerificationBackup(int userId) { 16687 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16688 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16689 } 16690 16691 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16692 try { 16693 final XmlSerializer serializer = new FastXmlSerializer(); 16694 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16695 serializer.startDocument(null, true); 16696 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16697 16698 synchronized (mPackages) { 16699 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16700 } 16701 16702 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16703 serializer.endDocument(); 16704 serializer.flush(); 16705 } catch (Exception e) { 16706 if (DEBUG_BACKUP) { 16707 Slog.e(TAG, "Unable to write default apps for backup", e); 16708 } 16709 return null; 16710 } 16711 16712 return dataStream.toByteArray(); 16713 } 16714 16715 @Override 16716 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16717 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16718 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16719 } 16720 16721 try { 16722 final XmlPullParser parser = Xml.newPullParser(); 16723 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16724 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16725 new BlobXmlRestorer() { 16726 @Override 16727 public void apply(XmlPullParser parser, int userId) 16728 throws XmlPullParserException, IOException { 16729 synchronized (mPackages) { 16730 mSettings.readAllDomainVerificationsLPr(parser, userId); 16731 mSettings.writeLPr(); 16732 } 16733 } 16734 } ); 16735 } catch (Exception e) { 16736 if (DEBUG_BACKUP) { 16737 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16738 } 16739 } 16740 } 16741 16742 @Override 16743 public byte[] getPermissionGrantBackup(int userId) { 16744 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16745 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16746 } 16747 16748 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16749 try { 16750 final XmlSerializer serializer = new FastXmlSerializer(); 16751 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16752 serializer.startDocument(null, true); 16753 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16754 16755 synchronized (mPackages) { 16756 serializeRuntimePermissionGrantsLPr(serializer, userId); 16757 } 16758 16759 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16760 serializer.endDocument(); 16761 serializer.flush(); 16762 } catch (Exception e) { 16763 if (DEBUG_BACKUP) { 16764 Slog.e(TAG, "Unable to write default apps for backup", e); 16765 } 16766 return null; 16767 } 16768 16769 return dataStream.toByteArray(); 16770 } 16771 16772 @Override 16773 public void restorePermissionGrants(byte[] backup, int userId) { 16774 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16775 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16776 } 16777 16778 try { 16779 final XmlPullParser parser = Xml.newPullParser(); 16780 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16781 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16782 new BlobXmlRestorer() { 16783 @Override 16784 public void apply(XmlPullParser parser, int userId) 16785 throws XmlPullParserException, IOException { 16786 synchronized (mPackages) { 16787 processRestoredPermissionGrantsLPr(parser, userId); 16788 } 16789 } 16790 } ); 16791 } catch (Exception e) { 16792 if (DEBUG_BACKUP) { 16793 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16794 } 16795 } 16796 } 16797 16798 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16799 throws IOException { 16800 serializer.startTag(null, TAG_ALL_GRANTS); 16801 16802 final int N = mSettings.mPackages.size(); 16803 for (int i = 0; i < N; i++) { 16804 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16805 boolean pkgGrantsKnown = false; 16806 16807 PermissionsState packagePerms = ps.getPermissionsState(); 16808 16809 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16810 final int grantFlags = state.getFlags(); 16811 // only look at grants that are not system/policy fixed 16812 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16813 final boolean isGranted = state.isGranted(); 16814 // And only back up the user-twiddled state bits 16815 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16816 final String packageName = mSettings.mPackages.keyAt(i); 16817 if (!pkgGrantsKnown) { 16818 serializer.startTag(null, TAG_GRANT); 16819 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16820 pkgGrantsKnown = true; 16821 } 16822 16823 final boolean userSet = 16824 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16825 final boolean userFixed = 16826 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16827 final boolean revoke = 16828 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16829 16830 serializer.startTag(null, TAG_PERMISSION); 16831 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16832 if (isGranted) { 16833 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16834 } 16835 if (userSet) { 16836 serializer.attribute(null, ATTR_USER_SET, "true"); 16837 } 16838 if (userFixed) { 16839 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16840 } 16841 if (revoke) { 16842 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16843 } 16844 serializer.endTag(null, TAG_PERMISSION); 16845 } 16846 } 16847 } 16848 16849 if (pkgGrantsKnown) { 16850 serializer.endTag(null, TAG_GRANT); 16851 } 16852 } 16853 16854 serializer.endTag(null, TAG_ALL_GRANTS); 16855 } 16856 16857 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16858 throws XmlPullParserException, IOException { 16859 String pkgName = null; 16860 int outerDepth = parser.getDepth(); 16861 int type; 16862 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16863 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16864 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16865 continue; 16866 } 16867 16868 final String tagName = parser.getName(); 16869 if (tagName.equals(TAG_GRANT)) { 16870 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16871 if (DEBUG_BACKUP) { 16872 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16873 } 16874 } else if (tagName.equals(TAG_PERMISSION)) { 16875 16876 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16877 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16878 16879 int newFlagSet = 0; 16880 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16881 newFlagSet |= FLAG_PERMISSION_USER_SET; 16882 } 16883 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16884 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16885 } 16886 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16887 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16888 } 16889 if (DEBUG_BACKUP) { 16890 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16891 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16892 } 16893 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16894 if (ps != null) { 16895 // Already installed so we apply the grant immediately 16896 if (DEBUG_BACKUP) { 16897 Slog.v(TAG, " + already installed; applying"); 16898 } 16899 PermissionsState perms = ps.getPermissionsState(); 16900 BasePermission bp = mSettings.mPermissions.get(permName); 16901 if (bp != null) { 16902 if (isGranted) { 16903 perms.grantRuntimePermission(bp, userId); 16904 } 16905 if (newFlagSet != 0) { 16906 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16907 } 16908 } 16909 } else { 16910 // Need to wait for post-restore install to apply the grant 16911 if (DEBUG_BACKUP) { 16912 Slog.v(TAG, " - not yet installed; saving for later"); 16913 } 16914 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16915 isGranted, newFlagSet, userId); 16916 } 16917 } else { 16918 PackageManagerService.reportSettingsProblem(Log.WARN, 16919 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16920 XmlUtils.skipCurrentTag(parser); 16921 } 16922 } 16923 16924 scheduleWriteSettingsLocked(); 16925 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16926 } 16927 16928 @Override 16929 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16930 int sourceUserId, int targetUserId, int flags) { 16931 mContext.enforceCallingOrSelfPermission( 16932 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16933 int callingUid = Binder.getCallingUid(); 16934 enforceOwnerRights(ownerPackage, callingUid); 16935 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16936 if (intentFilter.countActions() == 0) { 16937 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16938 return; 16939 } 16940 synchronized (mPackages) { 16941 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16942 ownerPackage, targetUserId, flags); 16943 CrossProfileIntentResolver resolver = 16944 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16945 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16946 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16947 if (existing != null) { 16948 int size = existing.size(); 16949 for (int i = 0; i < size; i++) { 16950 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16951 return; 16952 } 16953 } 16954 } 16955 resolver.addFilter(newFilter); 16956 scheduleWritePackageRestrictionsLocked(sourceUserId); 16957 } 16958 } 16959 16960 @Override 16961 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16962 mContext.enforceCallingOrSelfPermission( 16963 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16964 int callingUid = Binder.getCallingUid(); 16965 enforceOwnerRights(ownerPackage, callingUid); 16966 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16967 synchronized (mPackages) { 16968 CrossProfileIntentResolver resolver = 16969 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16970 ArraySet<CrossProfileIntentFilter> set = 16971 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16972 for (CrossProfileIntentFilter filter : set) { 16973 if (filter.getOwnerPackage().equals(ownerPackage)) { 16974 resolver.removeFilter(filter); 16975 } 16976 } 16977 scheduleWritePackageRestrictionsLocked(sourceUserId); 16978 } 16979 } 16980 16981 // Enforcing that callingUid is owning pkg on userId 16982 private void enforceOwnerRights(String pkg, int callingUid) { 16983 // The system owns everything. 16984 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16985 return; 16986 } 16987 int callingUserId = UserHandle.getUserId(callingUid); 16988 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16989 if (pi == null) { 16990 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16991 + callingUserId); 16992 } 16993 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16994 throw new SecurityException("Calling uid " + callingUid 16995 + " does not own package " + pkg); 16996 } 16997 } 16998 16999 @Override 17000 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17001 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17002 } 17003 17004 private Intent getHomeIntent() { 17005 Intent intent = new Intent(Intent.ACTION_MAIN); 17006 intent.addCategory(Intent.CATEGORY_HOME); 17007 return intent; 17008 } 17009 17010 private IntentFilter getHomeFilter() { 17011 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17012 filter.addCategory(Intent.CATEGORY_HOME); 17013 filter.addCategory(Intent.CATEGORY_DEFAULT); 17014 return filter; 17015 } 17016 17017 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17018 int userId) { 17019 Intent intent = getHomeIntent(); 17020 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17021 PackageManager.GET_META_DATA, userId); 17022 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17023 true, false, false, userId); 17024 17025 allHomeCandidates.clear(); 17026 if (list != null) { 17027 for (ResolveInfo ri : list) { 17028 allHomeCandidates.add(ri); 17029 } 17030 } 17031 return (preferred == null || preferred.activityInfo == null) 17032 ? null 17033 : new ComponentName(preferred.activityInfo.packageName, 17034 preferred.activityInfo.name); 17035 } 17036 17037 @Override 17038 public void setHomeActivity(ComponentName comp, int userId) { 17039 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17040 getHomeActivitiesAsUser(homeActivities, userId); 17041 17042 boolean found = false; 17043 17044 final int size = homeActivities.size(); 17045 final ComponentName[] set = new ComponentName[size]; 17046 for (int i = 0; i < size; i++) { 17047 final ResolveInfo candidate = homeActivities.get(i); 17048 final ActivityInfo info = candidate.activityInfo; 17049 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17050 set[i] = activityName; 17051 if (!found && activityName.equals(comp)) { 17052 found = true; 17053 } 17054 } 17055 if (!found) { 17056 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17057 + userId); 17058 } 17059 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17060 set, comp, userId); 17061 } 17062 17063 private @Nullable String getSetupWizardPackageName() { 17064 final Intent intent = new Intent(Intent.ACTION_MAIN); 17065 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17066 17067 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17068 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17069 | MATCH_DISABLED_COMPONENTS, 17070 UserHandle.myUserId()); 17071 if (matches.size() == 1) { 17072 return matches.get(0).getComponentInfo().packageName; 17073 } else { 17074 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17075 + ": matches=" + matches); 17076 return null; 17077 } 17078 } 17079 17080 @Override 17081 public void setApplicationEnabledSetting(String appPackageName, 17082 int newState, int flags, int userId, String callingPackage) { 17083 if (!sUserManager.exists(userId)) return; 17084 if (callingPackage == null) { 17085 callingPackage = Integer.toString(Binder.getCallingUid()); 17086 } 17087 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17088 } 17089 17090 @Override 17091 public void setComponentEnabledSetting(ComponentName componentName, 17092 int newState, int flags, int userId) { 17093 if (!sUserManager.exists(userId)) return; 17094 setEnabledSetting(componentName.getPackageName(), 17095 componentName.getClassName(), newState, flags, userId, null); 17096 } 17097 17098 private void setEnabledSetting(final String packageName, String className, int newState, 17099 final int flags, int userId, String callingPackage) { 17100 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17101 || newState == COMPONENT_ENABLED_STATE_ENABLED 17102 || newState == COMPONENT_ENABLED_STATE_DISABLED 17103 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17104 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17105 throw new IllegalArgumentException("Invalid new component state: " 17106 + newState); 17107 } 17108 PackageSetting pkgSetting; 17109 final int uid = Binder.getCallingUid(); 17110 final int permission = mContext.checkCallingOrSelfPermission( 17111 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17112 enforceCrossUserPermission(uid, userId, 17113 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17114 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17115 boolean sendNow = false; 17116 boolean isApp = (className == null); 17117 String componentName = isApp ? packageName : className; 17118 int packageUid = -1; 17119 ArrayList<String> components; 17120 17121 // writer 17122 synchronized (mPackages) { 17123 pkgSetting = mSettings.mPackages.get(packageName); 17124 if (pkgSetting == null) { 17125 if (className == null) { 17126 throw new IllegalArgumentException("Unknown package: " + packageName); 17127 } 17128 throw new IllegalArgumentException( 17129 "Unknown component: " + packageName + "/" + className); 17130 } 17131 // Allow root and verify that userId is not being specified by a different user 17132 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17133 throw new SecurityException( 17134 "Permission Denial: attempt to change component state from pid=" 17135 + Binder.getCallingPid() 17136 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17137 } 17138 if (className == null) { 17139 // We're dealing with an application/package level state change 17140 if (pkgSetting.getEnabled(userId) == newState) { 17141 // Nothing to do 17142 return; 17143 } 17144 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17145 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17146 // Don't care about who enables an app. 17147 callingPackage = null; 17148 } 17149 pkgSetting.setEnabled(newState, userId, callingPackage); 17150 // pkgSetting.pkg.mSetEnabled = newState; 17151 } else { 17152 // We're dealing with a component level state change 17153 // First, verify that this is a valid class name. 17154 PackageParser.Package pkg = pkgSetting.pkg; 17155 if (pkg == null || !pkg.hasComponentClassName(className)) { 17156 if (pkg != null && 17157 pkg.applicationInfo.targetSdkVersion >= 17158 Build.VERSION_CODES.JELLY_BEAN) { 17159 throw new IllegalArgumentException("Component class " + className 17160 + " does not exist in " + packageName); 17161 } else { 17162 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17163 + className + " does not exist in " + packageName); 17164 } 17165 } 17166 switch (newState) { 17167 case COMPONENT_ENABLED_STATE_ENABLED: 17168 if (!pkgSetting.enableComponentLPw(className, userId)) { 17169 return; 17170 } 17171 break; 17172 case COMPONENT_ENABLED_STATE_DISABLED: 17173 if (!pkgSetting.disableComponentLPw(className, userId)) { 17174 return; 17175 } 17176 break; 17177 case COMPONENT_ENABLED_STATE_DEFAULT: 17178 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17179 return; 17180 } 17181 break; 17182 default: 17183 Slog.e(TAG, "Invalid new component state: " + newState); 17184 return; 17185 } 17186 } 17187 scheduleWritePackageRestrictionsLocked(userId); 17188 components = mPendingBroadcasts.get(userId, packageName); 17189 final boolean newPackage = components == null; 17190 if (newPackage) { 17191 components = new ArrayList<String>(); 17192 } 17193 if (!components.contains(componentName)) { 17194 components.add(componentName); 17195 } 17196 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17197 sendNow = true; 17198 // Purge entry from pending broadcast list if another one exists already 17199 // since we are sending one right away. 17200 mPendingBroadcasts.remove(userId, packageName); 17201 } else { 17202 if (newPackage) { 17203 mPendingBroadcasts.put(userId, packageName, components); 17204 } 17205 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17206 // Schedule a message 17207 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17208 } 17209 } 17210 } 17211 17212 long callingId = Binder.clearCallingIdentity(); 17213 try { 17214 if (sendNow) { 17215 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17216 sendPackageChangedBroadcast(packageName, 17217 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17218 } 17219 } finally { 17220 Binder.restoreCallingIdentity(callingId); 17221 } 17222 } 17223 17224 @Override 17225 public void flushPackageRestrictionsAsUser(int userId) { 17226 if (!sUserManager.exists(userId)) { 17227 return; 17228 } 17229 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17230 false /* checkShell */, "flushPackageRestrictions"); 17231 synchronized (mPackages) { 17232 mSettings.writePackageRestrictionsLPr(userId); 17233 mDirtyUsers.remove(userId); 17234 if (mDirtyUsers.isEmpty()) { 17235 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17236 } 17237 } 17238 } 17239 17240 private void sendPackageChangedBroadcast(String packageName, 17241 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17242 if (DEBUG_INSTALL) 17243 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17244 + componentNames); 17245 Bundle extras = new Bundle(4); 17246 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17247 String nameList[] = new String[componentNames.size()]; 17248 componentNames.toArray(nameList); 17249 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17250 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17251 extras.putInt(Intent.EXTRA_UID, packageUid); 17252 // If this is not reporting a change of the overall package, then only send it 17253 // to registered receivers. We don't want to launch a swath of apps for every 17254 // little component state change. 17255 final int flags = !componentNames.contains(packageName) 17256 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17257 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17258 new int[] {UserHandle.getUserId(packageUid)}); 17259 } 17260 17261 @Override 17262 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17263 if (!sUserManager.exists(userId)) return; 17264 final int uid = Binder.getCallingUid(); 17265 final int permission = mContext.checkCallingOrSelfPermission( 17266 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17267 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17268 enforceCrossUserPermission(uid, userId, 17269 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17270 // writer 17271 synchronized (mPackages) { 17272 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17273 allowedByPermission, uid, userId)) { 17274 scheduleWritePackageRestrictionsLocked(userId); 17275 } 17276 } 17277 } 17278 17279 @Override 17280 public String getInstallerPackageName(String packageName) { 17281 // reader 17282 synchronized (mPackages) { 17283 return mSettings.getInstallerPackageNameLPr(packageName); 17284 } 17285 } 17286 17287 @Override 17288 public int getApplicationEnabledSetting(String packageName, int userId) { 17289 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17290 int uid = Binder.getCallingUid(); 17291 enforceCrossUserPermission(uid, userId, 17292 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17293 // reader 17294 synchronized (mPackages) { 17295 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17296 } 17297 } 17298 17299 @Override 17300 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17301 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17302 int uid = Binder.getCallingUid(); 17303 enforceCrossUserPermission(uid, userId, 17304 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17305 // reader 17306 synchronized (mPackages) { 17307 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17308 } 17309 } 17310 17311 @Override 17312 public void enterSafeMode() { 17313 enforceSystemOrRoot("Only the system can request entering safe mode"); 17314 17315 if (!mSystemReady) { 17316 mSafeMode = true; 17317 } 17318 } 17319 17320 @Override 17321 public void systemReady() { 17322 mSystemReady = true; 17323 17324 // Read the compatibilty setting when the system is ready. 17325 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17326 mContext.getContentResolver(), 17327 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17328 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17329 if (DEBUG_SETTINGS) { 17330 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17331 } 17332 17333 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17334 17335 synchronized (mPackages) { 17336 // Verify that all of the preferred activity components actually 17337 // exist. It is possible for applications to be updated and at 17338 // that point remove a previously declared activity component that 17339 // had been set as a preferred activity. We try to clean this up 17340 // the next time we encounter that preferred activity, but it is 17341 // possible for the user flow to never be able to return to that 17342 // situation so here we do a sanity check to make sure we haven't 17343 // left any junk around. 17344 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17345 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17346 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17347 removed.clear(); 17348 for (PreferredActivity pa : pir.filterSet()) { 17349 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17350 removed.add(pa); 17351 } 17352 } 17353 if (removed.size() > 0) { 17354 for (int r=0; r<removed.size(); r++) { 17355 PreferredActivity pa = removed.get(r); 17356 Slog.w(TAG, "Removing dangling preferred activity: " 17357 + pa.mPref.mComponent); 17358 pir.removeFilter(pa); 17359 } 17360 mSettings.writePackageRestrictionsLPr( 17361 mSettings.mPreferredActivities.keyAt(i)); 17362 } 17363 } 17364 17365 for (int userId : UserManagerService.getInstance().getUserIds()) { 17366 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17367 grantPermissionsUserIds = ArrayUtils.appendInt( 17368 grantPermissionsUserIds, userId); 17369 } 17370 } 17371 } 17372 sUserManager.systemReady(); 17373 17374 // If we upgraded grant all default permissions before kicking off. 17375 for (int userId : grantPermissionsUserIds) { 17376 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17377 } 17378 17379 // Kick off any messages waiting for system ready 17380 if (mPostSystemReadyMessages != null) { 17381 for (Message msg : mPostSystemReadyMessages) { 17382 msg.sendToTarget(); 17383 } 17384 mPostSystemReadyMessages = null; 17385 } 17386 17387 // Watch for external volumes that come and go over time 17388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17389 storage.registerListener(mStorageListener); 17390 17391 mInstallerService.systemReady(); 17392 mPackageDexOptimizer.systemReady(); 17393 17394 MountServiceInternal mountServiceInternal = LocalServices.getService( 17395 MountServiceInternal.class); 17396 mountServiceInternal.addExternalStoragePolicy( 17397 new MountServiceInternal.ExternalStorageMountPolicy() { 17398 @Override 17399 public int getMountMode(int uid, String packageName) { 17400 if (Process.isIsolated(uid)) { 17401 return Zygote.MOUNT_EXTERNAL_NONE; 17402 } 17403 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17404 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17405 } 17406 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17407 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17408 } 17409 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17410 return Zygote.MOUNT_EXTERNAL_READ; 17411 } 17412 return Zygote.MOUNT_EXTERNAL_WRITE; 17413 } 17414 17415 @Override 17416 public boolean hasExternalStorage(int uid, String packageName) { 17417 return true; 17418 } 17419 }); 17420 } 17421 17422 @Override 17423 public boolean isSafeMode() { 17424 return mSafeMode; 17425 } 17426 17427 @Override 17428 public boolean hasSystemUidErrors() { 17429 return mHasSystemUidErrors; 17430 } 17431 17432 static String arrayToString(int[] array) { 17433 StringBuffer buf = new StringBuffer(128); 17434 buf.append('['); 17435 if (array != null) { 17436 for (int i=0; i<array.length; i++) { 17437 if (i > 0) buf.append(", "); 17438 buf.append(array[i]); 17439 } 17440 } 17441 buf.append(']'); 17442 return buf.toString(); 17443 } 17444 17445 static class DumpState { 17446 public static final int DUMP_LIBS = 1 << 0; 17447 public static final int DUMP_FEATURES = 1 << 1; 17448 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17449 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17450 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17451 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17452 public static final int DUMP_PERMISSIONS = 1 << 6; 17453 public static final int DUMP_PACKAGES = 1 << 7; 17454 public static final int DUMP_SHARED_USERS = 1 << 8; 17455 public static final int DUMP_MESSAGES = 1 << 9; 17456 public static final int DUMP_PROVIDERS = 1 << 10; 17457 public static final int DUMP_VERIFIERS = 1 << 11; 17458 public static final int DUMP_PREFERRED = 1 << 12; 17459 public static final int DUMP_PREFERRED_XML = 1 << 13; 17460 public static final int DUMP_KEYSETS = 1 << 14; 17461 public static final int DUMP_VERSION = 1 << 15; 17462 public static final int DUMP_INSTALLS = 1 << 16; 17463 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17464 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17465 public static final int DUMP_FROZEN = 1 << 19; 17466 17467 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17468 17469 private int mTypes; 17470 17471 private int mOptions; 17472 17473 private boolean mTitlePrinted; 17474 17475 private SharedUserSetting mSharedUser; 17476 17477 public boolean isDumping(int type) { 17478 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17479 return true; 17480 } 17481 17482 return (mTypes & type) != 0; 17483 } 17484 17485 public void setDump(int type) { 17486 mTypes |= type; 17487 } 17488 17489 public boolean isOptionEnabled(int option) { 17490 return (mOptions & option) != 0; 17491 } 17492 17493 public void setOptionEnabled(int option) { 17494 mOptions |= option; 17495 } 17496 17497 public boolean onTitlePrinted() { 17498 final boolean printed = mTitlePrinted; 17499 mTitlePrinted = true; 17500 return printed; 17501 } 17502 17503 public boolean getTitlePrinted() { 17504 return mTitlePrinted; 17505 } 17506 17507 public void setTitlePrinted(boolean enabled) { 17508 mTitlePrinted = enabled; 17509 } 17510 17511 public SharedUserSetting getSharedUser() { 17512 return mSharedUser; 17513 } 17514 17515 public void setSharedUser(SharedUserSetting user) { 17516 mSharedUser = user; 17517 } 17518 } 17519 17520 @Override 17521 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17522 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17523 (new PackageManagerShellCommand(this)).exec( 17524 this, in, out, err, args, resultReceiver); 17525 } 17526 17527 @Override 17528 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17529 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17530 != PackageManager.PERMISSION_GRANTED) { 17531 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17532 + Binder.getCallingPid() 17533 + ", uid=" + Binder.getCallingUid() 17534 + " without permission " 17535 + android.Manifest.permission.DUMP); 17536 return; 17537 } 17538 17539 DumpState dumpState = new DumpState(); 17540 boolean fullPreferred = false; 17541 boolean checkin = false; 17542 17543 String packageName = null; 17544 ArraySet<String> permissionNames = null; 17545 17546 int opti = 0; 17547 while (opti < args.length) { 17548 String opt = args[opti]; 17549 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17550 break; 17551 } 17552 opti++; 17553 17554 if ("-a".equals(opt)) { 17555 // Right now we only know how to print all. 17556 } else if ("-h".equals(opt)) { 17557 pw.println("Package manager dump options:"); 17558 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17559 pw.println(" --checkin: dump for a checkin"); 17560 pw.println(" -f: print details of intent filters"); 17561 pw.println(" -h: print this help"); 17562 pw.println(" cmd may be one of:"); 17563 pw.println(" l[ibraries]: list known shared libraries"); 17564 pw.println(" f[eatures]: list device features"); 17565 pw.println(" k[eysets]: print known keysets"); 17566 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17567 pw.println(" perm[issions]: dump permissions"); 17568 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17569 pw.println(" pref[erred]: print preferred package settings"); 17570 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17571 pw.println(" prov[iders]: dump content providers"); 17572 pw.println(" p[ackages]: dump installed packages"); 17573 pw.println(" s[hared-users]: dump shared user IDs"); 17574 pw.println(" m[essages]: print collected runtime messages"); 17575 pw.println(" v[erifiers]: print package verifier info"); 17576 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17577 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17578 pw.println(" version: print database version info"); 17579 pw.println(" write: write current settings now"); 17580 pw.println(" installs: details about install sessions"); 17581 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17582 pw.println(" <package.name>: info about given package"); 17583 return; 17584 } else if ("--checkin".equals(opt)) { 17585 checkin = true; 17586 } else if ("-f".equals(opt)) { 17587 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17588 } else { 17589 pw.println("Unknown argument: " + opt + "; use -h for help"); 17590 } 17591 } 17592 17593 // Is the caller requesting to dump a particular piece of data? 17594 if (opti < args.length) { 17595 String cmd = args[opti]; 17596 opti++; 17597 // Is this a package name? 17598 if ("android".equals(cmd) || cmd.contains(".")) { 17599 packageName = cmd; 17600 // When dumping a single package, we always dump all of its 17601 // filter information since the amount of data will be reasonable. 17602 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17603 } else if ("check-permission".equals(cmd)) { 17604 if (opti >= args.length) { 17605 pw.println("Error: check-permission missing permission argument"); 17606 return; 17607 } 17608 String perm = args[opti]; 17609 opti++; 17610 if (opti >= args.length) { 17611 pw.println("Error: check-permission missing package argument"); 17612 return; 17613 } 17614 String pkg = args[opti]; 17615 opti++; 17616 int user = UserHandle.getUserId(Binder.getCallingUid()); 17617 if (opti < args.length) { 17618 try { 17619 user = Integer.parseInt(args[opti]); 17620 } catch (NumberFormatException e) { 17621 pw.println("Error: check-permission user argument is not a number: " 17622 + args[opti]); 17623 return; 17624 } 17625 } 17626 pw.println(checkPermission(perm, pkg, user)); 17627 return; 17628 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17629 dumpState.setDump(DumpState.DUMP_LIBS); 17630 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17631 dumpState.setDump(DumpState.DUMP_FEATURES); 17632 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17633 if (opti >= args.length) { 17634 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17635 | DumpState.DUMP_SERVICE_RESOLVERS 17636 | DumpState.DUMP_RECEIVER_RESOLVERS 17637 | DumpState.DUMP_CONTENT_RESOLVERS); 17638 } else { 17639 while (opti < args.length) { 17640 String name = args[opti]; 17641 if ("a".equals(name) || "activity".equals(name)) { 17642 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17643 } else if ("s".equals(name) || "service".equals(name)) { 17644 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17645 } else if ("r".equals(name) || "receiver".equals(name)) { 17646 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17647 } else if ("c".equals(name) || "content".equals(name)) { 17648 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17649 } else { 17650 pw.println("Error: unknown resolver table type: " + name); 17651 return; 17652 } 17653 opti++; 17654 } 17655 } 17656 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17657 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17658 } else if ("permission".equals(cmd)) { 17659 if (opti >= args.length) { 17660 pw.println("Error: permission requires permission name"); 17661 return; 17662 } 17663 permissionNames = new ArraySet<>(); 17664 while (opti < args.length) { 17665 permissionNames.add(args[opti]); 17666 opti++; 17667 } 17668 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17669 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17670 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17671 dumpState.setDump(DumpState.DUMP_PREFERRED); 17672 } else if ("preferred-xml".equals(cmd)) { 17673 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17674 if (opti < args.length && "--full".equals(args[opti])) { 17675 fullPreferred = true; 17676 opti++; 17677 } 17678 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17679 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17680 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17681 dumpState.setDump(DumpState.DUMP_PACKAGES); 17682 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17683 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17684 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17685 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17686 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17687 dumpState.setDump(DumpState.DUMP_MESSAGES); 17688 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17689 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17690 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17691 || "intent-filter-verifiers".equals(cmd)) { 17692 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17693 } else if ("version".equals(cmd)) { 17694 dumpState.setDump(DumpState.DUMP_VERSION); 17695 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17696 dumpState.setDump(DumpState.DUMP_KEYSETS); 17697 } else if ("installs".equals(cmd)) { 17698 dumpState.setDump(DumpState.DUMP_INSTALLS); 17699 } else if ("frozen".equals(cmd)) { 17700 dumpState.setDump(DumpState.DUMP_FROZEN); 17701 } else if ("write".equals(cmd)) { 17702 synchronized (mPackages) { 17703 mSettings.writeLPr(); 17704 pw.println("Settings written."); 17705 return; 17706 } 17707 } 17708 } 17709 17710 if (checkin) { 17711 pw.println("vers,1"); 17712 } 17713 17714 // reader 17715 synchronized (mPackages) { 17716 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17717 if (!checkin) { 17718 if (dumpState.onTitlePrinted()) 17719 pw.println(); 17720 pw.println("Database versions:"); 17721 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17722 } 17723 } 17724 17725 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17726 if (!checkin) { 17727 if (dumpState.onTitlePrinted()) 17728 pw.println(); 17729 pw.println("Verifiers:"); 17730 pw.print(" Required: "); 17731 pw.print(mRequiredVerifierPackage); 17732 pw.print(" (uid="); 17733 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17734 UserHandle.USER_SYSTEM)); 17735 pw.println(")"); 17736 } else if (mRequiredVerifierPackage != null) { 17737 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17738 pw.print(","); 17739 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17740 UserHandle.USER_SYSTEM)); 17741 } 17742 } 17743 17744 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17745 packageName == null) { 17746 if (mIntentFilterVerifierComponent != null) { 17747 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17748 if (!checkin) { 17749 if (dumpState.onTitlePrinted()) 17750 pw.println(); 17751 pw.println("Intent Filter Verifier:"); 17752 pw.print(" Using: "); 17753 pw.print(verifierPackageName); 17754 pw.print(" (uid="); 17755 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17756 UserHandle.USER_SYSTEM)); 17757 pw.println(")"); 17758 } else if (verifierPackageName != null) { 17759 pw.print("ifv,"); pw.print(verifierPackageName); 17760 pw.print(","); 17761 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17762 UserHandle.USER_SYSTEM)); 17763 } 17764 } else { 17765 pw.println(); 17766 pw.println("No Intent Filter Verifier available!"); 17767 } 17768 } 17769 17770 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17771 boolean printedHeader = false; 17772 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17773 while (it.hasNext()) { 17774 String name = it.next(); 17775 SharedLibraryEntry ent = mSharedLibraries.get(name); 17776 if (!checkin) { 17777 if (!printedHeader) { 17778 if (dumpState.onTitlePrinted()) 17779 pw.println(); 17780 pw.println("Libraries:"); 17781 printedHeader = true; 17782 } 17783 pw.print(" "); 17784 } else { 17785 pw.print("lib,"); 17786 } 17787 pw.print(name); 17788 if (!checkin) { 17789 pw.print(" -> "); 17790 } 17791 if (ent.path != null) { 17792 if (!checkin) { 17793 pw.print("(jar) "); 17794 pw.print(ent.path); 17795 } else { 17796 pw.print(",jar,"); 17797 pw.print(ent.path); 17798 } 17799 } else { 17800 if (!checkin) { 17801 pw.print("(apk) "); 17802 pw.print(ent.apk); 17803 } else { 17804 pw.print(",apk,"); 17805 pw.print(ent.apk); 17806 } 17807 } 17808 pw.println(); 17809 } 17810 } 17811 17812 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17813 if (dumpState.onTitlePrinted()) 17814 pw.println(); 17815 if (!checkin) { 17816 pw.println("Features:"); 17817 } 17818 17819 for (FeatureInfo feat : mAvailableFeatures.values()) { 17820 if (checkin) { 17821 pw.print("feat,"); 17822 pw.print(feat.name); 17823 pw.print(","); 17824 pw.println(feat.version); 17825 } else { 17826 pw.print(" "); 17827 pw.print(feat.name); 17828 if (feat.version > 0) { 17829 pw.print(" version="); 17830 pw.print(feat.version); 17831 } 17832 pw.println(); 17833 } 17834 } 17835 } 17836 17837 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17838 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17839 : "Activity Resolver Table:", " ", packageName, 17840 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17841 dumpState.setTitlePrinted(true); 17842 } 17843 } 17844 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17845 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17846 : "Receiver Resolver Table:", " ", packageName, 17847 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17848 dumpState.setTitlePrinted(true); 17849 } 17850 } 17851 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17852 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17853 : "Service Resolver Table:", " ", packageName, 17854 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17855 dumpState.setTitlePrinted(true); 17856 } 17857 } 17858 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17859 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17860 : "Provider Resolver Table:", " ", packageName, 17861 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17862 dumpState.setTitlePrinted(true); 17863 } 17864 } 17865 17866 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17867 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17868 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17869 int user = mSettings.mPreferredActivities.keyAt(i); 17870 if (pir.dump(pw, 17871 dumpState.getTitlePrinted() 17872 ? "\nPreferred Activities User " + user + ":" 17873 : "Preferred Activities User " + user + ":", " ", 17874 packageName, true, false)) { 17875 dumpState.setTitlePrinted(true); 17876 } 17877 } 17878 } 17879 17880 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17881 pw.flush(); 17882 FileOutputStream fout = new FileOutputStream(fd); 17883 BufferedOutputStream str = new BufferedOutputStream(fout); 17884 XmlSerializer serializer = new FastXmlSerializer(); 17885 try { 17886 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17887 serializer.startDocument(null, true); 17888 serializer.setFeature( 17889 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17890 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17891 serializer.endDocument(); 17892 serializer.flush(); 17893 } catch (IllegalArgumentException e) { 17894 pw.println("Failed writing: " + e); 17895 } catch (IllegalStateException e) { 17896 pw.println("Failed writing: " + e); 17897 } catch (IOException e) { 17898 pw.println("Failed writing: " + e); 17899 } 17900 } 17901 17902 if (!checkin 17903 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17904 && packageName == null) { 17905 pw.println(); 17906 int count = mSettings.mPackages.size(); 17907 if (count == 0) { 17908 pw.println("No applications!"); 17909 pw.println(); 17910 } else { 17911 final String prefix = " "; 17912 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17913 if (allPackageSettings.size() == 0) { 17914 pw.println("No domain preferred apps!"); 17915 pw.println(); 17916 } else { 17917 pw.println("App verification status:"); 17918 pw.println(); 17919 count = 0; 17920 for (PackageSetting ps : allPackageSettings) { 17921 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17922 if (ivi == null || ivi.getPackageName() == null) continue; 17923 pw.println(prefix + "Package: " + ivi.getPackageName()); 17924 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17925 pw.println(prefix + "Status: " + ivi.getStatusString()); 17926 pw.println(); 17927 count++; 17928 } 17929 if (count == 0) { 17930 pw.println(prefix + "No app verification established."); 17931 pw.println(); 17932 } 17933 for (int userId : sUserManager.getUserIds()) { 17934 pw.println("App linkages for user " + userId + ":"); 17935 pw.println(); 17936 count = 0; 17937 for (PackageSetting ps : allPackageSettings) { 17938 final long status = ps.getDomainVerificationStatusForUser(userId); 17939 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17940 continue; 17941 } 17942 pw.println(prefix + "Package: " + ps.name); 17943 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17944 String statusStr = IntentFilterVerificationInfo. 17945 getStatusStringFromValue(status); 17946 pw.println(prefix + "Status: " + statusStr); 17947 pw.println(); 17948 count++; 17949 } 17950 if (count == 0) { 17951 pw.println(prefix + "No configured app linkages."); 17952 pw.println(); 17953 } 17954 } 17955 } 17956 } 17957 } 17958 17959 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17960 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17961 if (packageName == null && permissionNames == null) { 17962 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17963 if (iperm == 0) { 17964 if (dumpState.onTitlePrinted()) 17965 pw.println(); 17966 pw.println("AppOp Permissions:"); 17967 } 17968 pw.print(" AppOp Permission "); 17969 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17970 pw.println(":"); 17971 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17972 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17973 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17974 } 17975 } 17976 } 17977 } 17978 17979 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17980 boolean printedSomething = false; 17981 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17982 if (packageName != null && !packageName.equals(p.info.packageName)) { 17983 continue; 17984 } 17985 if (!printedSomething) { 17986 if (dumpState.onTitlePrinted()) 17987 pw.println(); 17988 pw.println("Registered ContentProviders:"); 17989 printedSomething = true; 17990 } 17991 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17992 pw.print(" "); pw.println(p.toString()); 17993 } 17994 printedSomething = false; 17995 for (Map.Entry<String, PackageParser.Provider> entry : 17996 mProvidersByAuthority.entrySet()) { 17997 PackageParser.Provider p = entry.getValue(); 17998 if (packageName != null && !packageName.equals(p.info.packageName)) { 17999 continue; 18000 } 18001 if (!printedSomething) { 18002 if (dumpState.onTitlePrinted()) 18003 pw.println(); 18004 pw.println("ContentProvider Authorities:"); 18005 printedSomething = true; 18006 } 18007 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18008 pw.print(" "); pw.println(p.toString()); 18009 if (p.info != null && p.info.applicationInfo != null) { 18010 final String appInfo = p.info.applicationInfo.toString(); 18011 pw.print(" applicationInfo="); pw.println(appInfo); 18012 } 18013 } 18014 } 18015 18016 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18017 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18018 } 18019 18020 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18021 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18022 } 18023 18024 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18025 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18026 } 18027 18028 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18029 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18030 } 18031 18032 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18033 // XXX should handle packageName != null by dumping only install data that 18034 // the given package is involved with. 18035 if (dumpState.onTitlePrinted()) pw.println(); 18036 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18037 } 18038 18039 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18040 // XXX should handle packageName != null by dumping only install data that 18041 // the given package is involved with. 18042 if (dumpState.onTitlePrinted()) pw.println(); 18043 18044 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18045 ipw.println(); 18046 ipw.println("Frozen packages:"); 18047 ipw.increaseIndent(); 18048 if (mFrozenPackages.size() == 0) { 18049 ipw.println("(none)"); 18050 } else { 18051 for (int i = 0; i < mFrozenPackages.size(); i++) { 18052 ipw.println(mFrozenPackages.valueAt(i)); 18053 } 18054 } 18055 ipw.decreaseIndent(); 18056 } 18057 18058 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18059 if (dumpState.onTitlePrinted()) pw.println(); 18060 mSettings.dumpReadMessagesLPr(pw, dumpState); 18061 18062 pw.println(); 18063 pw.println("Package warning messages:"); 18064 BufferedReader in = null; 18065 String line = null; 18066 try { 18067 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18068 while ((line = in.readLine()) != null) { 18069 if (line.contains("ignored: updated version")) continue; 18070 pw.println(line); 18071 } 18072 } catch (IOException ignored) { 18073 } finally { 18074 IoUtils.closeQuietly(in); 18075 } 18076 } 18077 18078 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18079 BufferedReader in = null; 18080 String line = null; 18081 try { 18082 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18083 while ((line = in.readLine()) != null) { 18084 if (line.contains("ignored: updated version")) continue; 18085 pw.print("msg,"); 18086 pw.println(line); 18087 } 18088 } catch (IOException ignored) { 18089 } finally { 18090 IoUtils.closeQuietly(in); 18091 } 18092 } 18093 } 18094 } 18095 18096 private String dumpDomainString(String packageName) { 18097 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18098 .getList(); 18099 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18100 18101 ArraySet<String> result = new ArraySet<>(); 18102 if (iviList.size() > 0) { 18103 for (IntentFilterVerificationInfo ivi : iviList) { 18104 for (String host : ivi.getDomains()) { 18105 result.add(host); 18106 } 18107 } 18108 } 18109 if (filters != null && filters.size() > 0) { 18110 for (IntentFilter filter : filters) { 18111 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18112 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18113 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18114 result.addAll(filter.getHostsList()); 18115 } 18116 } 18117 } 18118 18119 StringBuilder sb = new StringBuilder(result.size() * 16); 18120 for (String domain : result) { 18121 if (sb.length() > 0) sb.append(" "); 18122 sb.append(domain); 18123 } 18124 return sb.toString(); 18125 } 18126 18127 // ------- apps on sdcard specific code ------- 18128 static final boolean DEBUG_SD_INSTALL = false; 18129 18130 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18131 18132 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18133 18134 private boolean mMediaMounted = false; 18135 18136 static String getEncryptKey() { 18137 try { 18138 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18139 SD_ENCRYPTION_KEYSTORE_NAME); 18140 if (sdEncKey == null) { 18141 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18142 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18143 if (sdEncKey == null) { 18144 Slog.e(TAG, "Failed to create encryption keys"); 18145 return null; 18146 } 18147 } 18148 return sdEncKey; 18149 } catch (NoSuchAlgorithmException nsae) { 18150 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18151 return null; 18152 } catch (IOException ioe) { 18153 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18154 return null; 18155 } 18156 } 18157 18158 /* 18159 * Update media status on PackageManager. 18160 */ 18161 @Override 18162 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18163 int callingUid = Binder.getCallingUid(); 18164 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18165 throw new SecurityException("Media status can only be updated by the system"); 18166 } 18167 // reader; this apparently protects mMediaMounted, but should probably 18168 // be a different lock in that case. 18169 synchronized (mPackages) { 18170 Log.i(TAG, "Updating external media status from " 18171 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18172 + (mediaStatus ? "mounted" : "unmounted")); 18173 if (DEBUG_SD_INSTALL) 18174 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18175 + ", mMediaMounted=" + mMediaMounted); 18176 if (mediaStatus == mMediaMounted) { 18177 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18178 : 0, -1); 18179 mHandler.sendMessage(msg); 18180 return; 18181 } 18182 mMediaMounted = mediaStatus; 18183 } 18184 // Queue up an async operation since the package installation may take a 18185 // little while. 18186 mHandler.post(new Runnable() { 18187 public void run() { 18188 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18189 } 18190 }); 18191 } 18192 18193 /** 18194 * Called by MountService when the initial ASECs to scan are available. 18195 * Should block until all the ASEC containers are finished being scanned. 18196 */ 18197 public void scanAvailableAsecs() { 18198 updateExternalMediaStatusInner(true, false, false); 18199 } 18200 18201 /* 18202 * Collect information of applications on external media, map them against 18203 * existing containers and update information based on current mount status. 18204 * Please note that we always have to report status if reportStatus has been 18205 * set to true especially when unloading packages. 18206 */ 18207 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18208 boolean externalStorage) { 18209 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18210 int[] uidArr = EmptyArray.INT; 18211 18212 final String[] list = PackageHelper.getSecureContainerList(); 18213 if (ArrayUtils.isEmpty(list)) { 18214 Log.i(TAG, "No secure containers found"); 18215 } else { 18216 // Process list of secure containers and categorize them 18217 // as active or stale based on their package internal state. 18218 18219 // reader 18220 synchronized (mPackages) { 18221 for (String cid : list) { 18222 // Leave stages untouched for now; installer service owns them 18223 if (PackageInstallerService.isStageName(cid)) continue; 18224 18225 if (DEBUG_SD_INSTALL) 18226 Log.i(TAG, "Processing container " + cid); 18227 String pkgName = getAsecPackageName(cid); 18228 if (pkgName == null) { 18229 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18230 continue; 18231 } 18232 if (DEBUG_SD_INSTALL) 18233 Log.i(TAG, "Looking for pkg : " + pkgName); 18234 18235 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18236 if (ps == null) { 18237 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18238 continue; 18239 } 18240 18241 /* 18242 * Skip packages that are not external if we're unmounting 18243 * external storage. 18244 */ 18245 if (externalStorage && !isMounted && !isExternal(ps)) { 18246 continue; 18247 } 18248 18249 final AsecInstallArgs args = new AsecInstallArgs(cid, 18250 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18251 // The package status is changed only if the code path 18252 // matches between settings and the container id. 18253 if (ps.codePathString != null 18254 && ps.codePathString.startsWith(args.getCodePath())) { 18255 if (DEBUG_SD_INSTALL) { 18256 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18257 + " at code path: " + ps.codePathString); 18258 } 18259 18260 // We do have a valid package installed on sdcard 18261 processCids.put(args, ps.codePathString); 18262 final int uid = ps.appId; 18263 if (uid != -1) { 18264 uidArr = ArrayUtils.appendInt(uidArr, uid); 18265 } 18266 } else { 18267 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18268 + ps.codePathString); 18269 } 18270 } 18271 } 18272 18273 Arrays.sort(uidArr); 18274 } 18275 18276 // Process packages with valid entries. 18277 if (isMounted) { 18278 if (DEBUG_SD_INSTALL) 18279 Log.i(TAG, "Loading packages"); 18280 loadMediaPackages(processCids, uidArr, externalStorage); 18281 startCleaningPackages(); 18282 mInstallerService.onSecureContainersAvailable(); 18283 } else { 18284 if (DEBUG_SD_INSTALL) 18285 Log.i(TAG, "Unloading packages"); 18286 unloadMediaPackages(processCids, uidArr, reportStatus); 18287 } 18288 } 18289 18290 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18291 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18292 final int size = infos.size(); 18293 final String[] packageNames = new String[size]; 18294 final int[] packageUids = new int[size]; 18295 for (int i = 0; i < size; i++) { 18296 final ApplicationInfo info = infos.get(i); 18297 packageNames[i] = info.packageName; 18298 packageUids[i] = info.uid; 18299 } 18300 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18301 finishedReceiver); 18302 } 18303 18304 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18305 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18306 sendResourcesChangedBroadcast(mediaStatus, replacing, 18307 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18308 } 18309 18310 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18311 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18312 int size = pkgList.length; 18313 if (size > 0) { 18314 // Send broadcasts here 18315 Bundle extras = new Bundle(); 18316 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18317 if (uidArr != null) { 18318 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18319 } 18320 if (replacing) { 18321 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18322 } 18323 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18324 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18325 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18326 } 18327 } 18328 18329 /* 18330 * Look at potentially valid container ids from processCids If package 18331 * information doesn't match the one on record or package scanning fails, 18332 * the cid is added to list of removeCids. We currently don't delete stale 18333 * containers. 18334 */ 18335 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18336 boolean externalStorage) { 18337 ArrayList<String> pkgList = new ArrayList<String>(); 18338 Set<AsecInstallArgs> keys = processCids.keySet(); 18339 18340 for (AsecInstallArgs args : keys) { 18341 String codePath = processCids.get(args); 18342 if (DEBUG_SD_INSTALL) 18343 Log.i(TAG, "Loading container : " + args.cid); 18344 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18345 try { 18346 // Make sure there are no container errors first. 18347 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18348 Slog.e(TAG, "Failed to mount cid : " + args.cid 18349 + " when installing from sdcard"); 18350 continue; 18351 } 18352 // Check code path here. 18353 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18354 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18355 + " does not match one in settings " + codePath); 18356 continue; 18357 } 18358 // Parse package 18359 int parseFlags = mDefParseFlags; 18360 if (args.isExternalAsec()) { 18361 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18362 } 18363 if (args.isFwdLocked()) { 18364 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18365 } 18366 18367 synchronized (mInstallLock) { 18368 PackageParser.Package pkg = null; 18369 try { 18370 // Sadly we don't know the package name yet to freeze it 18371 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18372 SCAN_IGNORE_FROZEN, 0, null); 18373 } catch (PackageManagerException e) { 18374 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18375 } 18376 // Scan the package 18377 if (pkg != null) { 18378 /* 18379 * TODO why is the lock being held? doPostInstall is 18380 * called in other places without the lock. This needs 18381 * to be straightened out. 18382 */ 18383 // writer 18384 synchronized (mPackages) { 18385 retCode = PackageManager.INSTALL_SUCCEEDED; 18386 pkgList.add(pkg.packageName); 18387 // Post process args 18388 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18389 pkg.applicationInfo.uid); 18390 } 18391 } else { 18392 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18393 } 18394 } 18395 18396 } finally { 18397 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18398 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18399 } 18400 } 18401 } 18402 // writer 18403 synchronized (mPackages) { 18404 // If the platform SDK has changed since the last time we booted, 18405 // we need to re-grant app permission to catch any new ones that 18406 // appear. This is really a hack, and means that apps can in some 18407 // cases get permissions that the user didn't initially explicitly 18408 // allow... it would be nice to have some better way to handle 18409 // this situation. 18410 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18411 : mSettings.getInternalVersion(); 18412 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18413 : StorageManager.UUID_PRIVATE_INTERNAL; 18414 18415 int updateFlags = UPDATE_PERMISSIONS_ALL; 18416 if (ver.sdkVersion != mSdkVersion) { 18417 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18418 + mSdkVersion + "; regranting permissions for external"); 18419 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18420 } 18421 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18422 18423 // Yay, everything is now upgraded 18424 ver.forceCurrent(); 18425 18426 // can downgrade to reader 18427 // Persist settings 18428 mSettings.writeLPr(); 18429 } 18430 // Send a broadcast to let everyone know we are done processing 18431 if (pkgList.size() > 0) { 18432 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18433 } 18434 } 18435 18436 /* 18437 * Utility method to unload a list of specified containers 18438 */ 18439 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18440 // Just unmount all valid containers. 18441 for (AsecInstallArgs arg : cidArgs) { 18442 synchronized (mInstallLock) { 18443 arg.doPostDeleteLI(false); 18444 } 18445 } 18446 } 18447 18448 /* 18449 * Unload packages mounted on external media. This involves deleting package 18450 * data from internal structures, sending broadcasts about disabled packages, 18451 * gc'ing to free up references, unmounting all secure containers 18452 * corresponding to packages on external media, and posting a 18453 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18454 * that we always have to post this message if status has been requested no 18455 * matter what. 18456 */ 18457 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18458 final boolean reportStatus) { 18459 if (DEBUG_SD_INSTALL) 18460 Log.i(TAG, "unloading media packages"); 18461 ArrayList<String> pkgList = new ArrayList<String>(); 18462 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18463 final Set<AsecInstallArgs> keys = processCids.keySet(); 18464 for (AsecInstallArgs args : keys) { 18465 String pkgName = args.getPackageName(); 18466 if (DEBUG_SD_INSTALL) 18467 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18468 // Delete package internally 18469 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18470 synchronized (mInstallLock) { 18471 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18472 final boolean res; 18473 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18474 "unloadMediaPackages")) { 18475 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18476 null); 18477 } 18478 if (res) { 18479 pkgList.add(pkgName); 18480 } else { 18481 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18482 failedList.add(args); 18483 } 18484 } 18485 } 18486 18487 // reader 18488 synchronized (mPackages) { 18489 // We didn't update the settings after removing each package; 18490 // write them now for all packages. 18491 mSettings.writeLPr(); 18492 } 18493 18494 // We have to absolutely send UPDATED_MEDIA_STATUS only 18495 // after confirming that all the receivers processed the ordered 18496 // broadcast when packages get disabled, force a gc to clean things up. 18497 // and unload all the containers. 18498 if (pkgList.size() > 0) { 18499 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18500 new IIntentReceiver.Stub() { 18501 public void performReceive(Intent intent, int resultCode, String data, 18502 Bundle extras, boolean ordered, boolean sticky, 18503 int sendingUser) throws RemoteException { 18504 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18505 reportStatus ? 1 : 0, 1, keys); 18506 mHandler.sendMessage(msg); 18507 } 18508 }); 18509 } else { 18510 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18511 keys); 18512 mHandler.sendMessage(msg); 18513 } 18514 } 18515 18516 private void loadPrivatePackages(final VolumeInfo vol) { 18517 mHandler.post(new Runnable() { 18518 @Override 18519 public void run() { 18520 loadPrivatePackagesInner(vol); 18521 } 18522 }); 18523 } 18524 18525 private void loadPrivatePackagesInner(VolumeInfo vol) { 18526 final String volumeUuid = vol.fsUuid; 18527 if (TextUtils.isEmpty(volumeUuid)) { 18528 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18529 return; 18530 } 18531 18532 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18533 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18534 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18535 18536 final VersionInfo ver; 18537 final List<PackageSetting> packages; 18538 synchronized (mPackages) { 18539 ver = mSettings.findOrCreateVersion(volumeUuid); 18540 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18541 } 18542 18543 for (PackageSetting ps : packages) { 18544 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18545 synchronized (mInstallLock) { 18546 final PackageParser.Package pkg; 18547 try { 18548 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18549 loaded.add(pkg.applicationInfo); 18550 18551 } catch (PackageManagerException e) { 18552 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18553 } 18554 18555 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18556 deleteCodeCacheDirsLIF(ps.volumeUuid, ps.name); 18557 } 18558 } 18559 } 18560 18561 // Reconcile app data for all started/unlocked users 18562 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18563 final UserManager um = mContext.getSystemService(UserManager.class); 18564 for (UserInfo user : um.getUsers()) { 18565 final int flags; 18566 if (um.isUserUnlocked(user.id)) { 18567 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18568 } else if (um.isUserRunning(user.id)) { 18569 flags = StorageManager.FLAG_STORAGE_DE; 18570 } else { 18571 continue; 18572 } 18573 18574 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18575 reconcileAppsData(volumeUuid, user.id, flags); 18576 } 18577 18578 synchronized (mPackages) { 18579 int updateFlags = UPDATE_PERMISSIONS_ALL; 18580 if (ver.sdkVersion != mSdkVersion) { 18581 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18582 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18583 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18584 } 18585 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18586 18587 // Yay, everything is now upgraded 18588 ver.forceCurrent(); 18589 18590 mSettings.writeLPr(); 18591 } 18592 18593 for (PackageFreezer freezer : freezers) { 18594 freezer.close(); 18595 } 18596 18597 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18598 sendResourcesChangedBroadcast(true, false, loaded, null); 18599 } 18600 18601 private void unloadPrivatePackages(final VolumeInfo vol) { 18602 mHandler.post(new Runnable() { 18603 @Override 18604 public void run() { 18605 unloadPrivatePackagesInner(vol); 18606 } 18607 }); 18608 } 18609 18610 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18611 final String volumeUuid = vol.fsUuid; 18612 if (TextUtils.isEmpty(volumeUuid)) { 18613 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18614 return; 18615 } 18616 18617 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18618 synchronized (mInstallLock) { 18619 synchronized (mPackages) { 18620 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18621 for (PackageSetting ps : packages) { 18622 if (ps.pkg == null) continue; 18623 18624 final ApplicationInfo info = ps.pkg.applicationInfo; 18625 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18626 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18627 18628 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18629 "unloadPrivatePackagesInner")) { 18630 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18631 false, null)) { 18632 unloaded.add(info); 18633 } else { 18634 Slog.w(TAG, "Failed to unload " + ps.codePath); 18635 } 18636 } 18637 } 18638 18639 mSettings.writeLPr(); 18640 } 18641 } 18642 18643 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18644 sendResourcesChangedBroadcast(false, false, unloaded, null); 18645 } 18646 18647 /** 18648 * Examine all users present on given mounted volume, and destroy data 18649 * belonging to users that are no longer valid, or whose user ID has been 18650 * recycled. 18651 */ 18652 private void reconcileUsers(String volumeUuid) { 18653 // TODO: also reconcile DE directories 18654 final File[] files = FileUtils 18655 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18656 for (File file : files) { 18657 if (!file.isDirectory()) continue; 18658 18659 final int userId; 18660 final UserInfo info; 18661 try { 18662 userId = Integer.parseInt(file.getName()); 18663 info = sUserManager.getUserInfo(userId); 18664 } catch (NumberFormatException e) { 18665 Slog.w(TAG, "Invalid user directory " + file); 18666 continue; 18667 } 18668 18669 boolean destroyUser = false; 18670 if (info == null) { 18671 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18672 + " because no matching user was found"); 18673 destroyUser = true; 18674 } else { 18675 try { 18676 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18677 } catch (IOException e) { 18678 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18679 + " because we failed to enforce serial number: " + e); 18680 destroyUser = true; 18681 } 18682 } 18683 18684 if (destroyUser) { 18685 synchronized (mInstallLock) { 18686 try { 18687 mInstaller.removeUserDataDirs(volumeUuid, userId); 18688 } catch (InstallerException e) { 18689 Slog.w(TAG, "Failed to clean up user dirs", e); 18690 } 18691 } 18692 } 18693 } 18694 } 18695 18696 private void assertPackageKnown(String volumeUuid, String packageName) 18697 throws PackageManagerException { 18698 synchronized (mPackages) { 18699 final PackageSetting ps = mSettings.mPackages.get(packageName); 18700 if (ps == null) { 18701 throw new PackageManagerException("Package " + packageName + " is unknown"); 18702 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18703 throw new PackageManagerException( 18704 "Package " + packageName + " found on unknown volume " + volumeUuid 18705 + "; expected volume " + ps.volumeUuid); 18706 } 18707 } 18708 } 18709 18710 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18711 throws PackageManagerException { 18712 synchronized (mPackages) { 18713 final PackageSetting ps = mSettings.mPackages.get(packageName); 18714 if (ps == null) { 18715 throw new PackageManagerException("Package " + packageName + " is unknown"); 18716 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18717 throw new PackageManagerException( 18718 "Package " + packageName + " found on unknown volume " + volumeUuid 18719 + "; expected volume " + ps.volumeUuid); 18720 } else if (!ps.getInstalled(userId)) { 18721 throw new PackageManagerException( 18722 "Package " + packageName + " not installed for user " + userId); 18723 } 18724 } 18725 } 18726 18727 /** 18728 * Examine all apps present on given mounted volume, and destroy apps that 18729 * aren't expected, either due to uninstallation or reinstallation on 18730 * another volume. 18731 */ 18732 private void reconcileApps(String volumeUuid) { 18733 final File[] files = FileUtils 18734 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18735 for (File file : files) { 18736 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18737 && !PackageInstallerService.isStageName(file.getName()); 18738 if (!isPackage) { 18739 // Ignore entries which are not packages 18740 continue; 18741 } 18742 18743 try { 18744 final PackageLite pkg = PackageParser.parsePackageLite(file, 18745 PackageParser.PARSE_MUST_BE_APK); 18746 assertPackageKnown(volumeUuid, pkg.packageName); 18747 18748 } catch (PackageParserException | PackageManagerException e) { 18749 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18750 synchronized (mInstallLock) { 18751 removeCodePathLI(file); 18752 } 18753 } 18754 } 18755 } 18756 18757 /** 18758 * Reconcile all app data for the given user. 18759 * <p> 18760 * Verifies that directories exist and that ownership and labeling is 18761 * correct for all installed apps on all mounted volumes. 18762 */ 18763 void reconcileAppsData(int userId, int flags) { 18764 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18765 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18766 final String volumeUuid = vol.getFsUuid(); 18767 reconcileAppsData(volumeUuid, userId, flags); 18768 } 18769 } 18770 18771 /** 18772 * Reconcile all app data on given mounted volume. 18773 * <p> 18774 * Destroys app data that isn't expected, either due to uninstallation or 18775 * reinstallation on another volume. 18776 * <p> 18777 * Verifies that directories exist and that ownership and labeling is 18778 * correct for all installed apps. 18779 */ 18780 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18781 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18782 + Integer.toHexString(flags)); 18783 18784 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18785 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18786 18787 boolean restoreconNeeded = false; 18788 18789 // First look for stale data that doesn't belong, and check if things 18790 // have changed since we did our last restorecon 18791 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18792 if (!isUserKeyUnlocked(userId)) { 18793 throw new RuntimeException( 18794 "Yikes, someone asked us to reconcile CE storage while " + userId 18795 + " was still locked; this would have caused massive data loss!"); 18796 } 18797 18798 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18799 18800 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18801 for (File file : files) { 18802 final String packageName = file.getName(); 18803 try { 18804 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18805 } catch (PackageManagerException e) { 18806 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18807 synchronized (mInstallLock) { 18808 destroyAppDataLI(volumeUuid, packageName, userId, 18809 StorageManager.FLAG_STORAGE_CE); 18810 } 18811 } 18812 } 18813 } 18814 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18815 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18816 18817 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18818 for (File file : files) { 18819 final String packageName = file.getName(); 18820 try { 18821 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18822 } catch (PackageManagerException e) { 18823 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18824 synchronized (mInstallLock) { 18825 destroyAppDataLI(volumeUuid, packageName, userId, 18826 StorageManager.FLAG_STORAGE_DE); 18827 } 18828 } 18829 } 18830 } 18831 18832 // Ensure that data directories are ready to roll for all packages 18833 // installed for this volume and user 18834 final List<PackageSetting> packages; 18835 synchronized (mPackages) { 18836 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18837 } 18838 int preparedCount = 0; 18839 for (PackageSetting ps : packages) { 18840 final String packageName = ps.name; 18841 if (ps.pkg == null) { 18842 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18843 // TODO: might be due to legacy ASEC apps; we should circle back 18844 // and reconcile again once they're scanned 18845 continue; 18846 } 18847 18848 if (ps.getInstalled(userId)) { 18849 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18850 18851 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18852 // We may have just shuffled around app data directories, so 18853 // prepare them one more time 18854 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18855 } 18856 18857 preparedCount++; 18858 } 18859 } 18860 18861 if (restoreconNeeded) { 18862 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18863 SELinuxMMAC.setRestoreconDone(ceDir); 18864 } 18865 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18866 SELinuxMMAC.setRestoreconDone(deDir); 18867 } 18868 } 18869 18870 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18871 + " packages; restoreconNeeded was " + restoreconNeeded); 18872 } 18873 18874 /** 18875 * Prepare app data for the given app just after it was installed or 18876 * upgraded. This method carefully only touches users that it's installed 18877 * for, and it forces a restorecon to handle any seinfo changes. 18878 * <p> 18879 * Verifies that directories exist and that ownership and labeling is 18880 * correct for all installed apps. If there is an ownership mismatch, it 18881 * will try recovering system apps by wiping data; third-party app data is 18882 * left intact. 18883 * <p> 18884 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18885 */ 18886 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18887 prepareAppDataAfterInstallInternal(pkg); 18888 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18889 for (int i = 0; i < childCount; i++) { 18890 PackageParser.Package childPackage = pkg.childPackages.get(i); 18891 prepareAppDataAfterInstallInternal(childPackage); 18892 } 18893 } 18894 18895 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18896 final PackageSetting ps; 18897 synchronized (mPackages) { 18898 ps = mSettings.mPackages.get(pkg.packageName); 18899 mSettings.writeKernelMappingLPr(ps); 18900 } 18901 18902 final UserManager um = mContext.getSystemService(UserManager.class); 18903 for (UserInfo user : um.getUsers()) { 18904 final int flags; 18905 if (um.isUserUnlocked(user.id)) { 18906 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18907 } else if (um.isUserRunning(user.id)) { 18908 flags = StorageManager.FLAG_STORAGE_DE; 18909 } else { 18910 continue; 18911 } 18912 18913 if (ps.getInstalled(user.id)) { 18914 // Whenever an app changes, force a restorecon of its data 18915 // TODO: when user data is locked, mark that we're still dirty 18916 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18917 } 18918 } 18919 } 18920 18921 /** 18922 * Prepare app data for the given app. 18923 * <p> 18924 * Verifies that directories exist and that ownership and labeling is 18925 * correct for all installed apps. If there is an ownership mismatch, this 18926 * will try recovering system apps by wiping data; third-party app data is 18927 * left intact. 18928 */ 18929 private void prepareAppData(String volumeUuid, int userId, int flags, 18930 PackageParser.Package pkg, boolean restoreconNeeded) { 18931 if (DEBUG_APP_DATA) { 18932 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18933 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18934 } 18935 18936 final String packageName = pkg.packageName; 18937 final ApplicationInfo app = pkg.applicationInfo; 18938 final int appId = UserHandle.getAppId(app.uid); 18939 18940 Preconditions.checkNotNull(app.seinfo); 18941 18942 synchronized (mInstallLock) { 18943 try { 18944 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18945 appId, app.seinfo, app.targetSdkVersion); 18946 } catch (InstallerException e) { 18947 if (app.isSystemApp()) { 18948 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18949 + ", but trying to recover: " + e); 18950 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18951 try { 18952 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18953 appId, app.seinfo, app.targetSdkVersion); 18954 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18955 } catch (InstallerException e2) { 18956 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18957 } 18958 } else { 18959 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18960 } 18961 } 18962 18963 if (restoreconNeeded) { 18964 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18965 } 18966 18967 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18968 // Create a native library symlink only if we have native libraries 18969 // and if the native libraries are 32 bit libraries. We do not provide 18970 // this symlink for 64 bit libraries. 18971 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18972 final String nativeLibPath = app.nativeLibraryDir; 18973 try { 18974 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18975 nativeLibPath, userId); 18976 } catch (InstallerException e) { 18977 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18978 } 18979 } 18980 } 18981 } 18982 } 18983 18984 /** 18985 * For system apps on non-FBE devices, this method migrates any existing 18986 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18987 * requested by the app. 18988 */ 18989 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18990 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18991 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18992 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18993 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18994 synchronized (mInstallLock) { 18995 try { 18996 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18997 } catch (InstallerException e) { 18998 logCriticalInfo(Log.WARN, 18999 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19000 } 19001 } 19002 return true; 19003 } else { 19004 return false; 19005 } 19006 } 19007 19008 public PackageFreezer freezePackage(String packageName, String killReason) { 19009 return new PackageFreezer(packageName, killReason); 19010 } 19011 19012 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19013 String killReason) { 19014 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19015 return new PackageFreezer(); 19016 } else { 19017 return freezePackage(packageName, killReason); 19018 } 19019 } 19020 19021 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19022 String killReason) { 19023 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19024 return new PackageFreezer(); 19025 } else { 19026 return freezePackage(packageName, killReason); 19027 } 19028 } 19029 19030 /** 19031 * Class that freezes and kills the given package upon creation, and 19032 * unfreezes it upon closing. This is typically used when doing surgery on 19033 * app code/data to prevent the app from running while you're working. 19034 */ 19035 private class PackageFreezer implements AutoCloseable { 19036 private final String mPackageName; 19037 private final PackageFreezer[] mChildren; 19038 19039 private final boolean mWeFroze; 19040 19041 private final AtomicBoolean mClosed = new AtomicBoolean(); 19042 private final CloseGuard mCloseGuard = CloseGuard.get(); 19043 19044 /** 19045 * Create and return a stub freezer that doesn't actually do anything, 19046 * typically used when someone requested 19047 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19048 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19049 */ 19050 public PackageFreezer() { 19051 mPackageName = null; 19052 mChildren = null; 19053 mWeFroze = false; 19054 mCloseGuard.open("close"); 19055 } 19056 19057 public PackageFreezer(String packageName, String killReason) { 19058 synchronized (mPackages) { 19059 mPackageName = packageName; 19060 mWeFroze = mFrozenPackages.add(mPackageName); 19061 19062 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19063 if (ps != null) { 19064 killApplication(ps.name, ps.appId, killReason); 19065 } 19066 19067 final PackageParser.Package p = mPackages.get(packageName); 19068 if (p != null && p.childPackages != null) { 19069 final int N = p.childPackages.size(); 19070 mChildren = new PackageFreezer[N]; 19071 for (int i = 0; i < N; i++) { 19072 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19073 killReason); 19074 } 19075 } else { 19076 mChildren = null; 19077 } 19078 } 19079 mCloseGuard.open("close"); 19080 } 19081 19082 @Override 19083 protected void finalize() throws Throwable { 19084 try { 19085 mCloseGuard.warnIfOpen(); 19086 close(); 19087 } finally { 19088 super.finalize(); 19089 } 19090 } 19091 19092 @Override 19093 public void close() { 19094 mCloseGuard.close(); 19095 if (mClosed.compareAndSet(false, true)) { 19096 synchronized (mPackages) { 19097 if (mWeFroze) { 19098 mFrozenPackages.remove(mPackageName); 19099 } 19100 19101 if (mChildren != null) { 19102 for (PackageFreezer freezer : mChildren) { 19103 freezer.close(); 19104 } 19105 } 19106 } 19107 } 19108 } 19109 } 19110 19111 /** 19112 * Verify that given package is currently frozen. 19113 */ 19114 private void checkPackageFrozen(String packageName) { 19115 synchronized (mPackages) { 19116 if (!mFrozenPackages.contains(packageName)) { 19117 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19118 } 19119 } 19120 } 19121 19122 @Override 19123 public int movePackage(final String packageName, final String volumeUuid) { 19124 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19125 19126 final int moveId = mNextMoveId.getAndIncrement(); 19127 mHandler.post(new Runnable() { 19128 @Override 19129 public void run() { 19130 try { 19131 movePackageInternal(packageName, volumeUuid, moveId); 19132 } catch (PackageManagerException e) { 19133 Slog.w(TAG, "Failed to move " + packageName, e); 19134 mMoveCallbacks.notifyStatusChanged(moveId, 19135 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19136 } 19137 } 19138 }); 19139 return moveId; 19140 } 19141 19142 private void movePackageInternal(final String packageName, final String volumeUuid, 19143 final int moveId) throws PackageManagerException { 19144 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19145 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19146 final PackageManager pm = mContext.getPackageManager(); 19147 19148 final boolean currentAsec; 19149 final String currentVolumeUuid; 19150 final File codeFile; 19151 final String installerPackageName; 19152 final String packageAbiOverride; 19153 final int appId; 19154 final String seinfo; 19155 final String label; 19156 final int targetSdkVersion; 19157 final PackageFreezer freezer; 19158 19159 // reader 19160 synchronized (mPackages) { 19161 final PackageParser.Package pkg = mPackages.get(packageName); 19162 final PackageSetting ps = mSettings.mPackages.get(packageName); 19163 if (pkg == null || ps == null) { 19164 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19165 } 19166 19167 if (pkg.applicationInfo.isSystemApp()) { 19168 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19169 "Cannot move system application"); 19170 } 19171 19172 if (pkg.applicationInfo.isExternalAsec()) { 19173 currentAsec = true; 19174 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19175 } else if (pkg.applicationInfo.isForwardLocked()) { 19176 currentAsec = true; 19177 currentVolumeUuid = "forward_locked"; 19178 } else { 19179 currentAsec = false; 19180 currentVolumeUuid = ps.volumeUuid; 19181 19182 final File probe = new File(pkg.codePath); 19183 final File probeOat = new File(probe, "oat"); 19184 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19185 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19186 "Move only supported for modern cluster style installs"); 19187 } 19188 } 19189 19190 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19191 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19192 "Package already moved to " + volumeUuid); 19193 } 19194 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19195 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19196 "Device admin cannot be moved"); 19197 } 19198 19199 if (mFrozenPackages.contains(packageName)) { 19200 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19201 "Failed to move already frozen package"); 19202 } 19203 19204 codeFile = new File(pkg.codePath); 19205 installerPackageName = ps.installerPackageName; 19206 packageAbiOverride = ps.cpuAbiOverrideString; 19207 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19208 seinfo = pkg.applicationInfo.seinfo; 19209 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19210 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19211 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19212 } 19213 19214 final Bundle extras = new Bundle(); 19215 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19216 extras.putString(Intent.EXTRA_TITLE, label); 19217 mMoveCallbacks.notifyCreated(moveId, extras); 19218 19219 int installFlags; 19220 final boolean moveCompleteApp; 19221 final File measurePath; 19222 19223 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19224 installFlags = INSTALL_INTERNAL; 19225 moveCompleteApp = !currentAsec; 19226 measurePath = Environment.getDataAppDirectory(volumeUuid); 19227 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19228 installFlags = INSTALL_EXTERNAL; 19229 moveCompleteApp = false; 19230 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19231 } else { 19232 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19233 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19234 || !volume.isMountedWritable()) { 19235 freezer.close(); 19236 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19237 "Move location not mounted private volume"); 19238 } 19239 19240 Preconditions.checkState(!currentAsec); 19241 19242 installFlags = INSTALL_INTERNAL; 19243 moveCompleteApp = true; 19244 measurePath = Environment.getDataAppDirectory(volumeUuid); 19245 } 19246 19247 final PackageStats stats = new PackageStats(null, -1); 19248 synchronized (mInstaller) { 19249 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19250 freezer.close(); 19251 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19252 "Failed to measure package size"); 19253 } 19254 } 19255 19256 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19257 + stats.dataSize); 19258 19259 final long startFreeBytes = measurePath.getFreeSpace(); 19260 final long sizeBytes; 19261 if (moveCompleteApp) { 19262 sizeBytes = stats.codeSize + stats.dataSize; 19263 } else { 19264 sizeBytes = stats.codeSize; 19265 } 19266 19267 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19268 freezer.close(); 19269 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19270 "Not enough free space to move"); 19271 } 19272 19273 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19274 19275 final CountDownLatch installedLatch = new CountDownLatch(1); 19276 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19277 @Override 19278 public void onUserActionRequired(Intent intent) throws RemoteException { 19279 throw new IllegalStateException(); 19280 } 19281 19282 @Override 19283 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19284 Bundle extras) throws RemoteException { 19285 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19286 + PackageManager.installStatusToString(returnCode, msg)); 19287 19288 installedLatch.countDown(); 19289 freezer.close(); 19290 19291 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19292 switch (status) { 19293 case PackageInstaller.STATUS_SUCCESS: 19294 mMoveCallbacks.notifyStatusChanged(moveId, 19295 PackageManager.MOVE_SUCCEEDED); 19296 break; 19297 case PackageInstaller.STATUS_FAILURE_STORAGE: 19298 mMoveCallbacks.notifyStatusChanged(moveId, 19299 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19300 break; 19301 default: 19302 mMoveCallbacks.notifyStatusChanged(moveId, 19303 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19304 break; 19305 } 19306 } 19307 }; 19308 19309 final MoveInfo move; 19310 if (moveCompleteApp) { 19311 // Kick off a thread to report progress estimates 19312 new Thread() { 19313 @Override 19314 public void run() { 19315 while (true) { 19316 try { 19317 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19318 break; 19319 } 19320 } catch (InterruptedException ignored) { 19321 } 19322 19323 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19324 final int progress = 10 + (int) MathUtils.constrain( 19325 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19326 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19327 } 19328 } 19329 }.start(); 19330 19331 final String dataAppName = codeFile.getName(); 19332 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19333 dataAppName, appId, seinfo, targetSdkVersion); 19334 } else { 19335 move = null; 19336 } 19337 19338 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19339 19340 final Message msg = mHandler.obtainMessage(INIT_COPY); 19341 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19342 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19343 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19344 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19345 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19346 msg.obj = params; 19347 19348 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19349 System.identityHashCode(msg.obj)); 19350 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19351 System.identityHashCode(msg.obj)); 19352 19353 mHandler.sendMessage(msg); 19354 } 19355 19356 @Override 19357 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19358 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19359 19360 final int realMoveId = mNextMoveId.getAndIncrement(); 19361 final Bundle extras = new Bundle(); 19362 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19363 mMoveCallbacks.notifyCreated(realMoveId, extras); 19364 19365 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19366 @Override 19367 public void onCreated(int moveId, Bundle extras) { 19368 // Ignored 19369 } 19370 19371 @Override 19372 public void onStatusChanged(int moveId, int status, long estMillis) { 19373 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19374 } 19375 }; 19376 19377 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19378 storage.setPrimaryStorageUuid(volumeUuid, callback); 19379 return realMoveId; 19380 } 19381 19382 @Override 19383 public int getMoveStatus(int moveId) { 19384 mContext.enforceCallingOrSelfPermission( 19385 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19386 return mMoveCallbacks.mLastStatus.get(moveId); 19387 } 19388 19389 @Override 19390 public void registerMoveCallback(IPackageMoveObserver callback) { 19391 mContext.enforceCallingOrSelfPermission( 19392 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19393 mMoveCallbacks.register(callback); 19394 } 19395 19396 @Override 19397 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19398 mContext.enforceCallingOrSelfPermission( 19399 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19400 mMoveCallbacks.unregister(callback); 19401 } 19402 19403 @Override 19404 public boolean setInstallLocation(int loc) { 19405 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19406 null); 19407 if (getInstallLocation() == loc) { 19408 return true; 19409 } 19410 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19411 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19412 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19413 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19414 return true; 19415 } 19416 return false; 19417 } 19418 19419 @Override 19420 public int getInstallLocation() { 19421 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19422 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19423 PackageHelper.APP_INSTALL_AUTO); 19424 } 19425 19426 /** Called by UserManagerService */ 19427 void cleanUpUser(UserManagerService userManager, int userHandle) { 19428 synchronized (mPackages) { 19429 mDirtyUsers.remove(userHandle); 19430 mUserNeedsBadging.delete(userHandle); 19431 mSettings.removeUserLPw(userHandle); 19432 mPendingBroadcasts.remove(userHandle); 19433 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19434 } 19435 synchronized (mInstallLock) { 19436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19437 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19438 final String volumeUuid = vol.getFsUuid(); 19439 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19440 try { 19441 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19442 } catch (InstallerException e) { 19443 Slog.w(TAG, "Failed to remove user data", e); 19444 } 19445 } 19446 synchronized (mPackages) { 19447 removeUnusedPackagesLILPw(userManager, userHandle); 19448 } 19449 } 19450 } 19451 19452 /** 19453 * We're removing userHandle and would like to remove any downloaded packages 19454 * that are no longer in use by any other user. 19455 * @param userHandle the user being removed 19456 */ 19457 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19458 final boolean DEBUG_CLEAN_APKS = false; 19459 int [] users = userManager.getUserIds(); 19460 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19461 while (psit.hasNext()) { 19462 PackageSetting ps = psit.next(); 19463 if (ps.pkg == null) { 19464 continue; 19465 } 19466 final String packageName = ps.pkg.packageName; 19467 // Skip over if system app 19468 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19469 continue; 19470 } 19471 if (DEBUG_CLEAN_APKS) { 19472 Slog.i(TAG, "Checking package " + packageName); 19473 } 19474 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19475 if (keep) { 19476 if (DEBUG_CLEAN_APKS) { 19477 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19478 } 19479 } else { 19480 for (int i = 0; i < users.length; i++) { 19481 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19482 keep = true; 19483 if (DEBUG_CLEAN_APKS) { 19484 Slog.i(TAG, " Keeping package " + packageName + " for user " 19485 + users[i]); 19486 } 19487 break; 19488 } 19489 } 19490 } 19491 if (!keep) { 19492 if (DEBUG_CLEAN_APKS) { 19493 Slog.i(TAG, " Removing package " + packageName); 19494 } 19495 mHandler.post(new Runnable() { 19496 public void run() { 19497 deletePackageX(packageName, userHandle, 0); 19498 } //end run 19499 }); 19500 } 19501 } 19502 } 19503 19504 /** Called by UserManagerService */ 19505 void createNewUser(int userHandle) { 19506 synchronized (mInstallLock) { 19507 try { 19508 mInstaller.createUserConfig(userHandle); 19509 } catch (InstallerException e) { 19510 Slog.w(TAG, "Failed to create user config", e); 19511 } 19512 mSettings.createNewUserLI(this, mInstaller, userHandle); 19513 } 19514 synchronized (mPackages) { 19515 applyFactoryDefaultBrowserLPw(userHandle); 19516 primeDomainVerificationsLPw(userHandle); 19517 } 19518 } 19519 19520 void newUserCreated(final int userHandle) { 19521 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19522 // If permission review for legacy apps is required, we represent 19523 // dagerous permissions for such apps as always granted runtime 19524 // permissions to keep per user flag state whether review is needed. 19525 // Hence, if a new user is added we have to propagate dangerous 19526 // permission grants for these legacy apps. 19527 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19528 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19529 | UPDATE_PERMISSIONS_REPLACE_ALL); 19530 } 19531 } 19532 19533 @Override 19534 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19535 mContext.enforceCallingOrSelfPermission( 19536 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19537 "Only package verification agents can read the verifier device identity"); 19538 19539 synchronized (mPackages) { 19540 return mSettings.getVerifierDeviceIdentityLPw(); 19541 } 19542 } 19543 19544 @Override 19545 public void setPermissionEnforced(String permission, boolean enforced) { 19546 // TODO: Now that we no longer change GID for storage, this should to away. 19547 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19548 "setPermissionEnforced"); 19549 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19550 synchronized (mPackages) { 19551 if (mSettings.mReadExternalStorageEnforced == null 19552 || mSettings.mReadExternalStorageEnforced != enforced) { 19553 mSettings.mReadExternalStorageEnforced = enforced; 19554 mSettings.writeLPr(); 19555 } 19556 } 19557 // kill any non-foreground processes so we restart them and 19558 // grant/revoke the GID. 19559 final IActivityManager am = ActivityManagerNative.getDefault(); 19560 if (am != null) { 19561 final long token = Binder.clearCallingIdentity(); 19562 try { 19563 am.killProcessesBelowForeground("setPermissionEnforcement"); 19564 } catch (RemoteException e) { 19565 } finally { 19566 Binder.restoreCallingIdentity(token); 19567 } 19568 } 19569 } else { 19570 throw new IllegalArgumentException("No selective enforcement for " + permission); 19571 } 19572 } 19573 19574 @Override 19575 @Deprecated 19576 public boolean isPermissionEnforced(String permission) { 19577 return true; 19578 } 19579 19580 @Override 19581 public boolean isStorageLow() { 19582 final long token = Binder.clearCallingIdentity(); 19583 try { 19584 final DeviceStorageMonitorInternal 19585 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19586 if (dsm != null) { 19587 return dsm.isMemoryLow(); 19588 } else { 19589 return false; 19590 } 19591 } finally { 19592 Binder.restoreCallingIdentity(token); 19593 } 19594 } 19595 19596 @Override 19597 public IPackageInstaller getPackageInstaller() { 19598 return mInstallerService; 19599 } 19600 19601 private boolean userNeedsBadging(int userId) { 19602 int index = mUserNeedsBadging.indexOfKey(userId); 19603 if (index < 0) { 19604 final UserInfo userInfo; 19605 final long token = Binder.clearCallingIdentity(); 19606 try { 19607 userInfo = sUserManager.getUserInfo(userId); 19608 } finally { 19609 Binder.restoreCallingIdentity(token); 19610 } 19611 final boolean b; 19612 if (userInfo != null && userInfo.isManagedProfile()) { 19613 b = true; 19614 } else { 19615 b = false; 19616 } 19617 mUserNeedsBadging.put(userId, b); 19618 return b; 19619 } 19620 return mUserNeedsBadging.valueAt(index); 19621 } 19622 19623 @Override 19624 public KeySet getKeySetByAlias(String packageName, String alias) { 19625 if (packageName == null || alias == null) { 19626 return null; 19627 } 19628 synchronized(mPackages) { 19629 final PackageParser.Package pkg = mPackages.get(packageName); 19630 if (pkg == null) { 19631 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19632 throw new IllegalArgumentException("Unknown package: " + packageName); 19633 } 19634 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19635 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19636 } 19637 } 19638 19639 @Override 19640 public KeySet getSigningKeySet(String packageName) { 19641 if (packageName == null) { 19642 return null; 19643 } 19644 synchronized(mPackages) { 19645 final PackageParser.Package pkg = mPackages.get(packageName); 19646 if (pkg == null) { 19647 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19648 throw new IllegalArgumentException("Unknown package: " + packageName); 19649 } 19650 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19651 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19652 throw new SecurityException("May not access signing KeySet of other apps."); 19653 } 19654 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19655 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19656 } 19657 } 19658 19659 @Override 19660 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19661 if (packageName == null || ks == null) { 19662 return false; 19663 } 19664 synchronized(mPackages) { 19665 final PackageParser.Package pkg = mPackages.get(packageName); 19666 if (pkg == null) { 19667 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19668 throw new IllegalArgumentException("Unknown package: " + packageName); 19669 } 19670 IBinder ksh = ks.getToken(); 19671 if (ksh instanceof KeySetHandle) { 19672 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19673 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19674 } 19675 return false; 19676 } 19677 } 19678 19679 @Override 19680 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19681 if (packageName == null || ks == null) { 19682 return false; 19683 } 19684 synchronized(mPackages) { 19685 final PackageParser.Package pkg = mPackages.get(packageName); 19686 if (pkg == null) { 19687 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19688 throw new IllegalArgumentException("Unknown package: " + packageName); 19689 } 19690 IBinder ksh = ks.getToken(); 19691 if (ksh instanceof KeySetHandle) { 19692 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19693 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19694 } 19695 return false; 19696 } 19697 } 19698 19699 private void deletePackageIfUnusedLPr(final String packageName) { 19700 PackageSetting ps = mSettings.mPackages.get(packageName); 19701 if (ps == null) { 19702 return; 19703 } 19704 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19705 // TODO Implement atomic delete if package is unused 19706 // It is currently possible that the package will be deleted even if it is installed 19707 // after this method returns. 19708 mHandler.post(new Runnable() { 19709 public void run() { 19710 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19711 } 19712 }); 19713 } 19714 } 19715 19716 /** 19717 * Check and throw if the given before/after packages would be considered a 19718 * downgrade. 19719 */ 19720 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19721 throws PackageManagerException { 19722 if (after.versionCode < before.mVersionCode) { 19723 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19724 "Update version code " + after.versionCode + " is older than current " 19725 + before.mVersionCode); 19726 } else if (after.versionCode == before.mVersionCode) { 19727 if (after.baseRevisionCode < before.baseRevisionCode) { 19728 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19729 "Update base revision code " + after.baseRevisionCode 19730 + " is older than current " + before.baseRevisionCode); 19731 } 19732 19733 if (!ArrayUtils.isEmpty(after.splitNames)) { 19734 for (int i = 0; i < after.splitNames.length; i++) { 19735 final String splitName = after.splitNames[i]; 19736 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19737 if (j != -1) { 19738 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19739 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19740 "Update split " + splitName + " revision code " 19741 + after.splitRevisionCodes[i] + " is older than current " 19742 + before.splitRevisionCodes[j]); 19743 } 19744 } 19745 } 19746 } 19747 } 19748 } 19749 19750 private static class MoveCallbacks extends Handler { 19751 private static final int MSG_CREATED = 1; 19752 private static final int MSG_STATUS_CHANGED = 2; 19753 19754 private final RemoteCallbackList<IPackageMoveObserver> 19755 mCallbacks = new RemoteCallbackList<>(); 19756 19757 private final SparseIntArray mLastStatus = new SparseIntArray(); 19758 19759 public MoveCallbacks(Looper looper) { 19760 super(looper); 19761 } 19762 19763 public void register(IPackageMoveObserver callback) { 19764 mCallbacks.register(callback); 19765 } 19766 19767 public void unregister(IPackageMoveObserver callback) { 19768 mCallbacks.unregister(callback); 19769 } 19770 19771 @Override 19772 public void handleMessage(Message msg) { 19773 final SomeArgs args = (SomeArgs) msg.obj; 19774 final int n = mCallbacks.beginBroadcast(); 19775 for (int i = 0; i < n; i++) { 19776 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19777 try { 19778 invokeCallback(callback, msg.what, args); 19779 } catch (RemoteException ignored) { 19780 } 19781 } 19782 mCallbacks.finishBroadcast(); 19783 args.recycle(); 19784 } 19785 19786 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19787 throws RemoteException { 19788 switch (what) { 19789 case MSG_CREATED: { 19790 callback.onCreated(args.argi1, (Bundle) args.arg2); 19791 break; 19792 } 19793 case MSG_STATUS_CHANGED: { 19794 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19795 break; 19796 } 19797 } 19798 } 19799 19800 private void notifyCreated(int moveId, Bundle extras) { 19801 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19802 19803 final SomeArgs args = SomeArgs.obtain(); 19804 args.argi1 = moveId; 19805 args.arg2 = extras; 19806 obtainMessage(MSG_CREATED, args).sendToTarget(); 19807 } 19808 19809 private void notifyStatusChanged(int moveId, int status) { 19810 notifyStatusChanged(moveId, status, -1); 19811 } 19812 19813 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19814 Slog.v(TAG, "Move " + moveId + " status " + status); 19815 19816 final SomeArgs args = SomeArgs.obtain(); 19817 args.argi1 = moveId; 19818 args.argi2 = status; 19819 args.arg3 = estMillis; 19820 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19821 19822 synchronized (mLastStatus) { 19823 mLastStatus.put(moveId, status); 19824 } 19825 } 19826 } 19827 19828 private final static class OnPermissionChangeListeners extends Handler { 19829 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19830 19831 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19832 new RemoteCallbackList<>(); 19833 19834 public OnPermissionChangeListeners(Looper looper) { 19835 super(looper); 19836 } 19837 19838 @Override 19839 public void handleMessage(Message msg) { 19840 switch (msg.what) { 19841 case MSG_ON_PERMISSIONS_CHANGED: { 19842 final int uid = msg.arg1; 19843 handleOnPermissionsChanged(uid); 19844 } break; 19845 } 19846 } 19847 19848 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19849 mPermissionListeners.register(listener); 19850 19851 } 19852 19853 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19854 mPermissionListeners.unregister(listener); 19855 } 19856 19857 public void onPermissionsChanged(int uid) { 19858 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19859 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19860 } 19861 } 19862 19863 private void handleOnPermissionsChanged(int uid) { 19864 final int count = mPermissionListeners.beginBroadcast(); 19865 try { 19866 for (int i = 0; i < count; i++) { 19867 IOnPermissionsChangeListener callback = mPermissionListeners 19868 .getBroadcastItem(i); 19869 try { 19870 callback.onPermissionsChanged(uid); 19871 } catch (RemoteException e) { 19872 Log.e(TAG, "Permission listener is dead", e); 19873 } 19874 } 19875 } finally { 19876 mPermissionListeners.finishBroadcast(); 19877 } 19878 } 19879 } 19880 19881 private class PackageManagerInternalImpl extends PackageManagerInternal { 19882 @Override 19883 public void setLocationPackagesProvider(PackagesProvider provider) { 19884 synchronized (mPackages) { 19885 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19886 } 19887 } 19888 19889 @Override 19890 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19891 synchronized (mPackages) { 19892 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19893 } 19894 } 19895 19896 @Override 19897 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19898 synchronized (mPackages) { 19899 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19900 } 19901 } 19902 19903 @Override 19904 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19905 synchronized (mPackages) { 19906 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19907 } 19908 } 19909 19910 @Override 19911 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19912 synchronized (mPackages) { 19913 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19914 } 19915 } 19916 19917 @Override 19918 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19919 synchronized (mPackages) { 19920 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19921 } 19922 } 19923 19924 @Override 19925 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19926 synchronized (mPackages) { 19927 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19928 packageName, userId); 19929 } 19930 } 19931 19932 @Override 19933 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19934 synchronized (mPackages) { 19935 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19936 packageName, userId); 19937 } 19938 } 19939 19940 @Override 19941 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19942 synchronized (mPackages) { 19943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19944 packageName, userId); 19945 } 19946 } 19947 19948 @Override 19949 public void setKeepUninstalledPackages(final List<String> packageList) { 19950 Preconditions.checkNotNull(packageList); 19951 List<String> removedFromList = null; 19952 synchronized (mPackages) { 19953 if (mKeepUninstalledPackages != null) { 19954 final int packagesCount = mKeepUninstalledPackages.size(); 19955 for (int i = 0; i < packagesCount; i++) { 19956 String oldPackage = mKeepUninstalledPackages.get(i); 19957 if (packageList != null && packageList.contains(oldPackage)) { 19958 continue; 19959 } 19960 if (removedFromList == null) { 19961 removedFromList = new ArrayList<>(); 19962 } 19963 removedFromList.add(oldPackage); 19964 } 19965 } 19966 mKeepUninstalledPackages = new ArrayList<>(packageList); 19967 if (removedFromList != null) { 19968 final int removedCount = removedFromList.size(); 19969 for (int i = 0; i < removedCount; i++) { 19970 deletePackageIfUnusedLPr(removedFromList.get(i)); 19971 } 19972 } 19973 } 19974 } 19975 19976 @Override 19977 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19978 synchronized (mPackages) { 19979 // If we do not support permission review, done. 19980 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19981 return false; 19982 } 19983 19984 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19985 if (packageSetting == null) { 19986 return false; 19987 } 19988 19989 // Permission review applies only to apps not supporting the new permission model. 19990 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19991 return false; 19992 } 19993 19994 // Legacy apps have the permission and get user consent on launch. 19995 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19996 return permissionsState.isPermissionReviewRequired(userId); 19997 } 19998 } 19999 20000 @Override 20001 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20002 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20003 } 20004 20005 @Override 20006 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20007 int userId) { 20008 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20009 } 20010 } 20011 20012 @Override 20013 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20014 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20015 synchronized (mPackages) { 20016 final long identity = Binder.clearCallingIdentity(); 20017 try { 20018 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20019 packageNames, userId); 20020 } finally { 20021 Binder.restoreCallingIdentity(identity); 20022 } 20023 } 20024 } 20025 20026 private static void enforceSystemOrPhoneCaller(String tag) { 20027 int callingUid = Binder.getCallingUid(); 20028 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20029 throw new SecurityException( 20030 "Cannot call " + tag + " from UID " + callingUid); 20031 } 20032 } 20033 20034 boolean isHistoricalPackageUsageAvailable() { 20035 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20036 } 20037 20038 /** 20039 * Return a <b>copy</b> of the collection of packages known to the package manager. 20040 * @return A copy of the values of mPackages. 20041 */ 20042 Collection<PackageParser.Package> getPackages() { 20043 synchronized (mPackages) { 20044 return new ArrayList<>(mPackages.values()); 20045 } 20046 } 20047 20048 /** 20049 * Logs process start information (including base APK hash) to the security log. 20050 * @hide 20051 */ 20052 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20053 String apkFile, int pid) { 20054 if (!SecurityLog.isLoggingEnabled()) { 20055 return; 20056 } 20057 Bundle data = new Bundle(); 20058 data.putLong("startTimestamp", System.currentTimeMillis()); 20059 data.putString("processName", processName); 20060 data.putInt("uid", uid); 20061 data.putString("seinfo", seinfo); 20062 data.putString("apkFile", apkFile); 20063 data.putInt("pid", pid); 20064 Message msg = mProcessLoggingHandler.obtainMessage( 20065 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20066 msg.setData(data); 20067 mProcessLoggingHandler.sendMessage(msg); 20068 } 20069} 20070